dotemacs

My Emacs configuration
git clone git://git.entf.net/dotemacs
Log | Files | Refs | LICENSE

org.el (842837B)


      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-2023 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, wp
      9 ;; URL: https://orgmode.org
     10 ;; Package-Requires: ((emacs "25.1"))
     11 
     12 ;; Version: 9.6.1
     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 
     85 (condition-case nil
     86     (load (concat (file-name-directory load-file-name)
     87 		  "org-loaddefs")
     88 	  nil t nil t)
     89   (error
     90    (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
     91    (sit-for 3)
     92    (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
     93    (sit-for 3)))
     94 
     95 (eval-and-compile (require 'org-macs))
     96 (require 'org-compat)
     97 (require 'org-keys)
     98 (require 'ol)
     99 (require 'oc)
    100 (require 'org-table)
    101 (require 'org-fold)
    102 
    103 (require 'org-cycle)
    104 (defvaralias 'org-hide-block-startup 'org-cycle-hide-block-startup)
    105 (defvaralias 'org-hide-drawer-startup 'org-cycle-hide-drawer-startup)
    106 (defvaralias 'org-pre-cycle-hook 'org-cycle-pre-hook)
    107 (defvaralias 'org-tab-first-hook 'org-cycle-tab-first-hook)
    108 (defalias 'org-global-cycle #'org-cycle-global)
    109 (defalias 'org-overview #'org-cycle-overview)
    110 (defalias 'org-content #'org-cycle-content)
    111 (defalias 'org-reveal #'org-fold-reveal)
    112 (defalias 'org-force-cycle-archived #'org-cycle-force-archived)
    113 
    114 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
    115 ;; some places -- e.g. see the macro `org-with-limited-levels'.
    116 (defvar org-outline-regexp "\\*+ "
    117   "Regexp to match Org headlines.")
    118 
    119 (defvar org-outline-regexp-bol "^\\*+ "
    120   "Regexp to match Org headlines.
    121 This is similar to `org-outline-regexp' but additionally makes
    122 sure that we are at the beginning of the line.")
    123 
    124 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
    125   "Matches a headline, putting stars and text into groups.
    126 Stars are put in group 1 and the trimmed body in group 2.")
    127 
    128 (declare-function calendar-check-holidays "holidays" (date))
    129 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
    130 (declare-function cdlatex-math-symbol "ext:cdlatex")
    131 (declare-function Info-goto-node "info" (nodename &optional fork strict-case))
    132 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
    133 (declare-function org-add-archive-files "org-archive" (files))
    134 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
    135 (declare-function org-agenda-todo-yesterday "org-agenda" (&optional arg))
    136 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span with-hour))
    137 (declare-function org-agenda-redo "org-agenda" (&optional all))
    138 (declare-function org-agenda-remove-restriction-lock "org-agenda" (&optional noupdate))
    139 (declare-function org-archive-subtree "org-archive" (&optional find-done))
    140 (declare-function org-archive-subtree-default "org-archive" ())
    141 (declare-function org-archive-to-archive-sibling "org-archive" ())
    142 (declare-function org-attach "org-attach" ())
    143 (declare-function org-attach-dir "org-attach"
    144 		  (&optional create-if-not-exists-p no-fs-check))
    145 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
    146 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
    147 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
    148 (declare-function org-clock-auto-clockout "org-clock" ())
    149 (declare-function org-clock-cancel "org-clock" ())
    150 (declare-function org-clock-display "org-clock" (&optional arg))
    151 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
    152 (declare-function org-clock-goto "org-clock" (&optional select))
    153 (declare-function org-clock-in "org-clock" (&optional select start-time))
    154 (declare-function org-clock-in-last "org-clock" (&optional arg))
    155 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
    156 (declare-function org-clock-out-if-current "org-clock" ())
    157 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
    158 (declare-function org-clock-report "org-clock" (&optional arg))
    159 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
    160 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
    161 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
    162 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
    163 (declare-function org-clock-update-time-maybe "org-clock" ())
    164 (declare-function org-clocktable-shift "org-clock" (dir n))
    165 (declare-function org-columns-quit "org-colview" ())
    166 (declare-function org-columns-insert-dblock "org-colview" ())
    167 (declare-function org-duration-from-minutes "org-duration" (minutes &optional fmt canonical))
    168 (declare-function org-duration-to-minutes "org-duration" (duration &optional canonical))
    169 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
    170 (declare-function org-element-at-point-no-context "org-element" (&optional pom))
    171 (declare-function org-element-cache-refresh "org-element" (pos))
    172 (declare-function org-element-cache-reset "org-element" (&optional all no-persistence))
    173 (declare-function org-element-cache-map "org-element" (func &rest keys))
    174 (declare-function org-element-contents "org-element" (element))
    175 (declare-function org-element-context "org-element" (&optional element))
    176 (declare-function org-element-copy "org-element" (datum))
    177 (declare-function org-element-create "org-element" (type &optional props &rest children))
    178 (declare-function org-element-extract-element "org-element" (element))
    179 (declare-function org-element-insert-before "org-element" (element location))
    180 (declare-function org-element-interpret-data "org-element" (data))
    181 (declare-function org-element-keyword-parser "org-element" (limit affiliated))
    182 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
    183 (declare-function org-element-link-parser "org-element" ())
    184 (declare-function org-element-map "org-element" (data types fun &optional info first-match no-recursion with-affiliated))
    185 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
    186 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
    187 (declare-function org-element-parse-secondary-string "org-element" (string restriction &optional parent))
    188 (declare-function org-element-property "org-element" (property element))
    189 (declare-function org-element-put-property "org-element" (element property value))
    190 (declare-function org-element-restriction "org-element" (element))
    191 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
    192 (declare-function org-element-timestamp-parser "org-element" ())
    193 (declare-function org-element-type "org-element" (element))
    194 (declare-function org-element--cache-active-p "org-element" ())
    195 (declare-function org-export-dispatch "ox" (&optional arg))
    196 (declare-function org-export-get-backend "ox" (name))
    197 (declare-function org-export-get-environment "ox" (&optional backend subtreep ext-plist))
    198 (declare-function org-feed-goto-inbox "org-feed" (feed))
    199 (declare-function org-feed-update-all "org-feed" ())
    200 (declare-function org-goto "org-goto" (&optional alternative-interface))
    201 (declare-function org-id-find-id-file "org-id" (id))
    202 (declare-function org-id-get-create "org-id" (&optional force))
    203 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
    204 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
    205 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
    206 (declare-function org-latex-make-preamble "ox-latex" (info &optional template snippet?))
    207 (declare-function org-num-mode "org-num" (&optional arg))
    208 (declare-function org-plot/gnuplot "org-plot" (&optional params))
    209 (declare-function org-persist-load "org-persist" (container &optional associated hash-must-match))
    210 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
    211 (declare-function org-timer "org-timer" (&optional restart no-insert))
    212 (declare-function org-timer-item "org-timer" (&optional arg))
    213 (declare-function org-timer-pause-or-continue "org-timer" (&optional stop))
    214 (declare-function org-timer-set-timer "org-timer" (&optional opt))
    215 (declare-function org-timer-start "org-timer" (&optional offset))
    216 (declare-function org-timer-stop "org-timer" ())
    217 (declare-function org-toggle-archive-tag "org-archive" (&optional find-done))
    218 (declare-function org-update-radio-target-regexp "ol" ())
    219 
    220 (defvar org-agenda-buffer-name)
    221 (defvar org-element-paragraph-separate)
    222 (defvar org-element-cache-map-continue-from)
    223 (defvar org-element--timestamp-regexp)
    224 (defvar org-indent-indentation-per-level)
    225 (defvar org-radio-target-regexp)
    226 (defvar org-target-link-regexp)
    227 (defvar org-target-regexp)
    228 (defvar org-id-overriding-file-name)
    229 
    230 ;; load languages based on value of `org-babel-load-languages'
    231 (defvar org-babel-load-languages)
    232 
    233 (defvar crm-separator)  ; dynamically scoped param
    234 
    235 ;;;###autoload
    236 (defun org-babel-do-load-languages (sym value)
    237   "Load the languages defined in `org-babel-load-languages'."
    238   (set-default-toplevel-value sym value)
    239   (dolist (pair org-babel-load-languages)
    240     (let ((active (cdr pair)) (lang (symbol-name (car pair))))
    241       (if active
    242 	  (require (intern (concat "ob-" lang)))
    243 	(fmakunbound
    244 	 (intern (concat "org-babel-execute:" lang)))
    245 	(fmakunbound
    246 	 (intern (concat "org-babel-expand-body:" lang)))))))
    247 
    248 
    249 ;;;###autoload
    250 (defun org-babel-load-file (file &optional compile)
    251   "Load Emacs Lisp source code blocks in the Org FILE.
    252 This function exports the source code using `org-babel-tangle'
    253 and then loads the resulting file using `load-file'.  With
    254 optional prefix argument COMPILE, the tangled Emacs Lisp file is
    255 byte-compiled before it is loaded."
    256   (interactive "fFile to load: \nP")
    257   (let ((tangled-file (concat (file-name-sans-extension file) ".el")))
    258     ;; Tangle only if the Elisp file is older than the Org file.
    259     ;; Catch the case when the .el file exists while the .org file is missing.
    260     (unless (file-exists-p file)
    261       (error "File to tangle does not exist: %s" file))
    262     (when (file-newer-than-file-p file tangled-file)
    263       (org-babel-tangle-file file
    264                              tangled-file
    265                              (rx string-start
    266                                  (or "emacs-lisp" "elisp")
    267                                  string-end))
    268       ;; Make sure that tangled file modification time is
    269       ;; updated even when `org-babel-tangle-file' does not make changes.
    270       ;; This avoids re-tangling changed FILE where the changes did
    271       ;; not affect the tangled code.
    272       (when (file-exists-p tangled-file)
    273         (set-file-times tangled-file)))
    274     (if compile
    275 	(progn
    276 	  (byte-compile-file tangled-file)
    277 	  (load-file (byte-compile-dest-file tangled-file))
    278 	  (message "Compiled and loaded %s" tangled-file))
    279       (load-file tangled-file)
    280       (message "Loaded %s" tangled-file))))
    281 
    282 (defcustom org-babel-load-languages '((emacs-lisp . t))
    283   "Languages which can be evaluated in Org buffers.
    284 \\<org-mode-map>
    285 This list can be used to load support for any of the available
    286 languages with babel support (see info node `(org) Languages').  Each
    287 language will depend on a different set of system executables and/or
    288 Emacs modes.
    289 
    290 When a language is \"loaded\", code blocks in that language can
    291 be evaluated with `org-babel-execute-src-block', which is bound
    292 by default to \\[org-ctrl-c-ctrl-c].
    293 
    294 The `org-babel-no-eval-on-ctrl-c-ctrl-c' option can be set to
    295 remove code block evaluation from \\[org-ctrl-c-ctrl-c].  By
    296 default, only Emacs Lisp is loaded, since it has no specific
    297 requirement."
    298   :group 'org-babel
    299   :set 'org-babel-do-load-languages
    300   :version "24.1"
    301   :type '(alist :tag "Babel Languages"
    302 		:key-type
    303 		(choice
    304 		 (const :tag "Awk" awk)
    305 		 (const :tag "C" C)
    306 		 (const :tag "R" R)
    307                  (const :tag "Calc" calc)
    308 		 (const :tag "Clojure" clojure)
    309 		 (const :tag "CSS" css)
    310 		 (const :tag "Ditaa" ditaa)
    311 		 (const :tag "Dot" dot)
    312                  (const :tag "Emacs Lisp" emacs-lisp)
    313 		 (const :tag "Forth" forth)
    314 		 (const :tag "Fortran" fortran)
    315 		 (const :tag "Gnuplot" gnuplot)
    316 		 (const :tag "Haskell" haskell)
    317                  (const :tag "Java" java)
    318 		 (const :tag "Javascript" js)
    319 		 (const :tag "LaTeX" latex)
    320                  (const :tag "Lilypond" lilypond)
    321 		 (const :tag "Lisp" lisp)
    322 		 (const :tag "Makefile" makefile)
    323 		 (const :tag "Maxima" maxima)
    324 		 (const :tag "Matlab" matlab)
    325                  (const :tag "Ocaml" ocaml)
    326 		 (const :tag "Octave" octave)
    327 		 (const :tag "Org" org)
    328 		 (const :tag "Perl" perl)
    329 		 (const :tag "Pico Lisp" picolisp)
    330 		 (const :tag "PlantUML" plantuml)
    331 		 (const :tag "Python" python)
    332 		 (const :tag "Ruby" ruby)
    333 		 (const :tag "Sass" sass)
    334 		 (const :tag "Scala" scala)
    335 		 (const :tag "Scheme" scheme)
    336 		 (const :tag "Screen" screen)
    337 		 (const :tag "Shell Script" shell)
    338                  (const :tag "Sql" sql)
    339 		 (const :tag "Sqlite" sqlite)
    340 		 (const :tag "Stan" stan))
    341 		:value-type (boolean :tag "Activate" :value t)))
    342 
    343 ;;;; Customization variables
    344 (defcustom org-clone-delete-id nil
    345   "Remove ID property of clones of a subtree.
    346 When non-nil, clones of a subtree don't inherit the ID property.
    347 Otherwise they inherit the ID property with a new unique
    348 identifier."
    349   :type 'boolean
    350   :version "24.1"
    351   :group 'org-id)
    352 
    353 ;;; Version
    354 (org-check-version)
    355 
    356 ;;;###autoload
    357 (defun org-version (&optional here full message)
    358   "Show the Org version.
    359 Interactively, or when MESSAGE is non-nil, show it in echo area.
    360 With prefix argument, or when HERE is non-nil, insert it at point.
    361 In non-interactive uses, a reduced version string is output unless
    362 FULL is given."
    363   (interactive (list current-prefix-arg t (not current-prefix-arg)))
    364   (let ((org-dir (ignore-errors (org-find-library-dir "org")))
    365         (save-load-suffixes load-suffixes)
    366 	(load-suffixes (list ".el"))
    367 	(org-install-dir
    368 	 (ignore-errors (org-find-library-dir "org-loaddefs"))))
    369     (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
    370       (org-load-noerror-mustsuffix (concat org-dir "org-version")))
    371     (let* ((load-suffixes save-load-suffixes)
    372 	   (release (org-release))
    373 	   (git-version (org-git-version))
    374 	   (version (format "Org mode version %s (%s @ %s)"
    375 			    release
    376 			    git-version
    377 			    (if org-install-dir
    378 				(if (string= org-dir org-install-dir)
    379 				    org-install-dir
    380 				  (concat "mixed installation! "
    381 					  org-install-dir
    382 					  " and "
    383 					  org-dir))
    384 			      "org-loaddefs.el can not be found!")))
    385 	   (version1 (if full version release)))
    386       (when here (insert version1))
    387       (when message (message "%s" version1))
    388       version1)))
    389 
    390 (defconst org-version (org-version))
    391 
    392 
    393 ;;; Syntax Constants
    394 ;;;; Comments
    395 (defconst org-comment-regexp
    396   (rx (seq bol (zero-or-more (any "\t ")) "#" (or " " eol)))
    397   "Regular expression for comment lines.")
    398 
    399 ;;;; Keyword
    400 (defconst org-keyword-regexp "^[ \t]*#\\+\\(\\S-+?\\):[ \t]*\\(.*\\)$"
    401   "Regular expression for keyword-lines.")
    402 
    403 ;;;; Block
    404 
    405 (defconst org-block-regexp
    406   "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
    407   "Regular expression for hiding blocks.")
    408 
    409 (defconst org-dblock-start-re
    410   "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
    411   "Matches the start line of a dynamic block, with parameters.")
    412 
    413 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
    414   "Matches the end of a dynamic block.")
    415 
    416 ;;;; Timestamp
    417 
    418 (defconst org-ts--internal-regexp
    419   (rx (seq
    420        (= 4 digit) "-" (= 2 digit) "-" (= 2 digit)
    421        (optional " " (*? nonl))))
    422   "Regular expression matching the innards of a time stamp.")
    423 
    424 (defconst org-ts-regexp (format "<\\(%s\\)>" org-ts--internal-regexp)
    425   "Regular expression for fast time stamp matching.")
    426 
    427 (defconst org-ts-regexp-inactive
    428   (format "\\[\\(%s\\)\\]" org-ts--internal-regexp)
    429   "Regular expression for fast inactive time stamp matching.")
    430 
    431 (defconst org-ts-regexp-both (format "[[<]\\(%s\\)[]>]" org-ts--internal-regexp)
    432   "Regular expression for fast time stamp matching.")
    433 
    434 (defconst org-ts-regexp0
    435   "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
    436   "Regular expression matching time strings for analysis.
    437 This one does not require the space after the date, so it can be used
    438 on a string that terminates immediately after the date.")
    439 
    440 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\(?: *\\([^]+0-9>\r\n -]+\\)\\)?\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
    441   "Regular expression matching time strings for analysis.")
    442 
    443 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
    444   "Regular expression matching time stamps, with groups.")
    445 
    446 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
    447   "Regular expression matching time stamps (also [..]), with groups.")
    448 
    449 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
    450   "Regular expression matching a time stamp range.")
    451 
    452 (defconst org-tr-regexp-both
    453   (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
    454   "Regular expression matching a time stamp range.")
    455 
    456 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
    457 				 org-ts-regexp "\\)?")
    458   "Regular expression matching a time stamp or time stamp range.")
    459 
    460 (defconst org-tsr-regexp-both
    461   (concat org-ts-regexp-both "\\(--?-?"
    462 	  org-ts-regexp-both "\\)?")
    463   "Regular expression matching a time stamp or time stamp range.
    464 The time stamps may be either active or inactive.")
    465 
    466 (defconst org-repeat-re
    467   "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\
    468 \\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
    469   "Regular expression for specifying repeated events.
    470 After a match, group 1 contains the repeat expression.")
    471 
    472 (defconst org-time-stamp-formats '("%Y-%m-%d %a" . "%Y-%m-%d %a %H:%M")
    473   "Formats for `format-time-string' which are used for time stamps.
    474 
    475 The value is a cons cell containing two strings.  The `car' and `cdr'
    476 of the cons cell are used to format time stamps that do not and do
    477 contain time, respectively.
    478 
    479 Leading \"<\"/\"[\" and trailing \">\"/\"]\" pair will be stripped
    480 from the format strings.
    481 
    482 Also, see `org-time-stamp-format'.")
    483 
    484 ;;;; Clock and Planning
    485 
    486 (defconst org-clock-string "CLOCK:"
    487   "String used as prefix for timestamps clocking work hours on an item.")
    488 
    489 (defvar org-closed-string "CLOSED:"
    490   "String used as the prefix for timestamps logging closing a TODO entry.")
    491 
    492 (defvar org-deadline-string "DEADLINE:"
    493   "String to mark deadline entries.
    494 \\<org-mode-map>
    495 A deadline is this string, followed by a time stamp.  It must be
    496 a word, terminated by a colon.  You can insert a schedule keyword
    497 and a timestamp with `\\[org-deadline]'.")
    498 
    499 (defvar org-scheduled-string "SCHEDULED:"
    500   "String to mark scheduled TODO entries.
    501 \\<org-mode-map>
    502 A schedule is this string, followed by a time stamp.  It must be
    503 a word, terminated by a colon.  You can insert a schedule keyword
    504 and a timestamp with `\\[org-schedule]'.")
    505 
    506 (defconst org-ds-keyword-length
    507   (+ 2
    508      (apply #'max
    509 	    (mapcar #'length
    510 		    (list org-deadline-string org-scheduled-string
    511 			  org-clock-string org-closed-string))))
    512   "Maximum length of the DEADLINE and SCHEDULED keywords.")
    513 
    514 (defconst org-planning-line-re
    515   (concat "^[ \t]*"
    516 	  (regexp-opt
    517 	   (list org-closed-string org-deadline-string org-scheduled-string)
    518 	   t))
    519   "Matches a line with planning info.
    520 Matched keyword is in group 1.")
    521 
    522 (defconst org-clock-line-re
    523   (concat "^[ \t]*" org-clock-string)
    524   "Matches a line with clock info.")
    525 
    526 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
    527   "Matches the DEADLINE keyword.")
    528 
    529 (defconst org-deadline-time-regexp
    530   (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
    531   "Matches the DEADLINE keyword together with a time stamp.")
    532 
    533 (defconst org-deadline-time-hour-regexp
    534   (concat "\\<" org-deadline-string
    535 	  " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
    536   "Matches the DEADLINE keyword together with a time-and-hour stamp.")
    537 
    538 (defconst org-deadline-line-regexp
    539   (concat "\\<\\(" org-deadline-string "\\).*")
    540   "Matches the DEADLINE keyword and the rest of the line.")
    541 
    542 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
    543   "Matches the SCHEDULED keyword.")
    544 
    545 (defconst org-scheduled-time-regexp
    546   (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
    547   "Matches the SCHEDULED keyword together with a time stamp.")
    548 
    549 (defconst org-scheduled-time-hour-regexp
    550   (concat "\\<" org-scheduled-string
    551 	  " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9+:hdwmy/ \t.-]*\\)>")
    552   "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
    553 
    554 (defconst org-closed-time-regexp
    555   (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
    556   "Matches the CLOSED keyword together with a time stamp.")
    557 
    558 (defconst org-keyword-time-regexp
    559   (concat "\\<"
    560 	  (regexp-opt
    561 	   (list org-scheduled-string org-deadline-string org-closed-string
    562 		 org-clock-string)
    563 	   t)
    564 	  " *[[<]\\([^]>]+\\)[]>]")
    565   "Matches any of the 4 keywords, together with the time stamp.")
    566 
    567 (defconst org-keyword-time-not-clock-regexp
    568   (concat
    569    "\\<"
    570    (regexp-opt
    571     (list org-scheduled-string org-deadline-string org-closed-string) t)
    572    " *[[<]\\([^]>]+\\)[]>]")
    573   "Matches any of the 3 keywords, together with the time stamp.")
    574 
    575 (defconst org-all-time-keywords
    576   (mapcar (lambda (w) (substring w 0 -1))
    577 	  (list org-scheduled-string org-deadline-string
    578 		org-clock-string org-closed-string))
    579   "List of time keywords.")
    580 
    581 ;;;; Drawer
    582 
    583 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
    584   "Matches first or last line of a hidden block.
    585 Group 1 contains drawer's name or \"END\".")
    586 
    587 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
    588   "Regular expression matching the first line of a property drawer.")
    589 
    590 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
    591   "Regular expression matching the last line of a property drawer.")
    592 
    593 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
    594   "Regular expression matching the first line of a clock drawer.")
    595 
    596 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
    597   "Regular expression matching the last line of a clock drawer.")
    598 
    599 (defconst org-logbook-drawer-re
    600   (rx (seq bol (0+ (any "\t ")) ":LOGBOOK:" (0+ (any "\t ")) "\n"
    601 	   (*? (0+ nonl) "\n")
    602 	   (0+ (any "\t ")) ":END:" (0+ (any "\t ")) eol))
    603   "Matches an entire LOGBOOK drawer.")
    604 
    605 (defconst org-property-drawer-re
    606   (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
    607 	  "\\(?:[ \t]*:\\S-+:\\(?:[ \t].*\\)?[ \t]*\n\\)*?"
    608 	  "[ \t]*:END:[ \t]*$")
    609   "Matches an entire property drawer.")
    610 
    611 (defconst org-clock-drawer-re
    612   (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
    613 	  org-clock-drawer-end-re "\\)\n?")
    614   "Matches an entire clock drawer.")
    615 
    616 ;;;; Headline
    617 
    618 (defconst org-heading-keyword-regexp-format
    619   "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
    620   "Printf format for a regexp matching a headline with some keyword.
    621 This regexp will match the headline of any node which has the
    622 exact keyword that is put into the format.  The keyword isn't in
    623 any group by default, but the stars and the body are.")
    624 
    625 (defconst org-heading-keyword-maybe-regexp-format
    626   "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
    627   "Printf format for a regexp matching a headline, possibly with some keyword.
    628 This regexp can match any headline with the specified keyword, or
    629 without a keyword.  The keyword isn't in any group by default,
    630 but the stars and the body are.")
    631 
    632 (defconst org-archive-tag "ARCHIVE"
    633   "The tag that marks a subtree as archived.
    634 An archived subtree does not open during visibility cycling, and does
    635 not contribute to the agenda listings.")
    636 
    637 (defconst org-tag-re "[[:alnum:]_@#%]+"
    638   "Regexp matching a single tag.")
    639 
    640 (defconst org-tag-group-re "[ \t]+\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
    641   "Regexp matching the tag group at the end of a line, with leading spaces.
    642 Tags are stored in match group 1.  Match group 2 stores the tags
    643 without the enclosing colons.")
    644 
    645 (defconst org-tag-line-re
    646   "^\\*+ \\(?:.*[ \t]\\)?\\(:\\([[:alnum:]_@#%:]+\\):\\)[ \t]*$"
    647   "Regexp matching tags in a headline.
    648 Tags are stored in match group 1.  Match group 2 stores the tags
    649 without the enclosing colons.")
    650 
    651 (eval-and-compile
    652   (defconst org-comment-string "COMMENT"
    653     "Entries starting with this keyword will never be exported.
    654 \\<org-mode-map>
    655 An entry can be toggled between COMMENT and normal with
    656 `\\[org-toggle-comment]'."))
    657 
    658 
    659 ;;;; LaTeX Environments and Fragments
    660 
    661 (defconst org-latex-regexps
    662   '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
    663     ;; ("$" "\\([ \t(]\\|^\\)\\(\\(\\([$]\\)\\([^ \t\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \t\n,.$]\\)\\4\\)\\)\\([ \t.,?;:'\")]\\|$\\)" 2 nil)
    664     ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
    665     ("$1" "\\([^$]\\|^\\)\\(\\$[^ \t\r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
    666     ("$"  "\\([^$]\\|^\\)\\(\\(\\$\\([^ \t\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \t\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|'\\|$\\)" 2 nil)
    667     ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
    668     ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
    669     ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
    670   "Regular expressions for matching embedded LaTeX.")
    671 
    672 ;;;; Node Property
    673 
    674 (defconst org-effort-property "Effort"
    675   "The property that is being used to keep track of effort estimates.
    676 Effort estimates given in this property need to be in the format
    677 defined in org-duration.el.")
    678 
    679 
    680 ;;; The custom variables
    681 
    682 (defgroup org nil
    683   "Outline-based notes management and organizer."
    684   :tag "Org"
    685   :group 'outlines
    686   :group 'calendar)
    687 
    688 (defcustom org-mode-hook nil
    689   "Mode hook for Org mode, run after the mode was turned on."
    690   :group 'org
    691   :type 'hook)
    692 
    693 (defcustom org-load-hook nil
    694   "Hook that is run after org.el has been loaded."
    695   :group 'org
    696   :type 'hook)
    697 
    698 (make-obsolete-variable
    699  'org-load-hook
    700  "use `with-eval-after-load' instead." "9.5")
    701 
    702 (defcustom org-log-buffer-setup-hook nil
    703   "Hook that is run after an Org log buffer is created."
    704   :group 'org
    705   :version "24.1"
    706   :type 'hook)
    707 
    708 (defvar org-modules)  ; defined below
    709 (defvar org-modules-loaded nil
    710   "Have the modules been loaded already?")
    711 
    712 ;;;###autoload
    713 (defun org-load-modules-maybe (&optional force)
    714   "Load all extensions listed in `org-modules'."
    715   (when (or force (not org-modules-loaded))
    716     (dolist (ext org-modules)
    717       (condition-case nil (require ext)
    718 	(error (message "Problems while trying to load feature `%s'" ext))))
    719     (setq org-modules-loaded t)))
    720 
    721 (defun org-set-modules (var value)
    722   "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
    723   (set-default-toplevel-value var value)
    724   (when (featurep 'org)
    725     (org-load-modules-maybe 'force)
    726     (org-element-cache-reset 'all)))
    727 
    728 (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)
    729   "Modules that should always be loaded together with org.el.
    730 
    731 If a description starts with <C>, the file is not part of Emacs and Org mode,
    732 so loading it will require that you have properly installed org-contrib
    733 package from NonGNU Emacs Lisp Package Archive
    734 https://elpa.nongnu.org/nongnu/org-contrib.html
    735 
    736 You can also use this system to load external packages (i.e. neither Org
    737 core modules, nor org-contrib modules).  Just add symbols
    738 to the end of the list.  If the package is called org-xyz.el, then you need
    739 to add the symbol `xyz', and the package must have a call to:
    740 
    741    (provide \\='org-xyz)
    742 
    743 For export specific modules, see also `org-export-backends'."
    744   :group 'org
    745   :set 'org-set-modules
    746   :package-version '(Org . "9.5")
    747   :type
    748   '(set :greedy t
    749 	(const :tag "   bbdb:              Links to BBDB entries" ol-bbdb)
    750 	(const :tag "   bibtex:            Links to BibTeX entries" ol-bibtex)
    751 	(const :tag "   crypt:             Encryption of subtrees" org-crypt)
    752 	(const :tag "   ctags:             Access to Emacs tags with links" org-ctags)
    753 	(const :tag "   docview:           Links to Docview buffers" ol-docview)
    754         (const :tag "   doi:               Links to DOI references" ol-doi)
    755 	(const :tag "   eww:               Store link to URL of Eww" ol-eww)
    756 	(const :tag "   gnus:              Links to GNUS folders/messages" ol-gnus)
    757 	(const :tag "   habit:             Track your consistency with habits" org-habit)
    758 	(const :tag "   id:                Global IDs for identifying entries" org-id)
    759 	(const :tag "   info:              Links to Info nodes" ol-info)
    760 	(const :tag "   inlinetask:        Tasks independent of outline hierarchy" org-inlinetask)
    761 	(const :tag "   irc:               Links to IRC/ERC chat sessions" ol-irc)
    762 	(const :tag "   mhe:               Links to MHE folders/messages" ol-mhe)
    763 	(const :tag "   mouse:             Additional mouse support" org-mouse)
    764 	(const :tag "   protocol:          Intercept calls from emacsclient" org-protocol)
    765 	(const :tag "   rmail:             Links to RMAIL folders/messages" ol-rmail)
    766 	(const :tag "   tempo:             Fast completion for structures" org-tempo)
    767 	(const :tag "   w3m:               Special cut/paste from w3m to Org mode." ol-w3m)
    768 	(const :tag "   eshell:            Links to working directories in Eshell" ol-eshell)
    769 
    770 	(const :tag "C  annotate-file:     Annotate a file with Org syntax" org-annotate-file)
    771 	(const :tag "C  bookmark:          Links to bookmarks" ol-bookmark)
    772 	(const :tag "C  checklist:         Extra functions for checklists in repeated tasks" org-checklist)
    773 	(const :tag "C  choose:            Use TODO keywords to mark decisions states" org-choose)
    774 	(const :tag "C  collector:         Collect properties into tables" org-collector)
    775 	(const :tag "C  depend:            TODO dependencies for Org mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
    776 	(const :tag "C  elisp-symbol:      Links to emacs-lisp symbols" ol-elisp-symbol)
    777 	(const :tag "C  eval-light:        Evaluate inbuffer-code on demand" org-eval-light)
    778 	(const :tag "C  eval:              Include command output as text" org-eval)
    779 	(const :tag "C  expiry:            Expiry mechanism for Org entries" org-expiry)
    780 	(const :tag "C  git-link:          Links to specific file version" ol-git-link)
    781 	(const :tag "C  interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
    782         (const :tag "C  invoice:           Help manage client invoices in Org mode" org-invoice)
    783 	(const :tag "C  learn:             SuperMemo's incremental learning algorithm" org-learn)
    784 	(const :tag "C  mac-iCal:          Imports events from iCal.app to the Emacs diary" org-mac-iCal)
    785 	(const :tag "C  mac-link:          Grab links and url from various mac Applications" org-mac-link)
    786 	(const :tag "C  mairix:            Hook mairix search into Org for different MUAs" org-mairix)
    787 	(const :tag "C  man:               Links to man pages in Org mode" ol-man)
    788 	(const :tag "C  mew:               Links to Mew folders/messages" ol-mew)
    789 	(const :tag "C  notify:            Notifications for Org mode" org-notify)
    790 	(const :tag "C  notmuch:           Provide Org links to notmuch searches or messages" ol-notmuch)
    791 	(const :tag "C  panel:             Simple routines for us with bad memory" org-panel)
    792 	(const :tag "C  registry:          A registry for Org links" org-registry)
    793 	(const :tag "C  screen:            Visit screen sessions through links" org-screen)
    794 	(const :tag "C  screenshot:        Take and manage screenshots in Org files" org-screenshot)
    795 	(const :tag "C  secretary:         Team management with Org" org-secretary)
    796 	(const :tag "C  sqlinsert:         Convert Org tables to SQL insertions" orgtbl-sqlinsert)
    797 	(const :tag "C  toc:               Table of contents for Org buffer" org-toc)
    798 	(const :tag "C  track:             Keep up with Org mode development" org-track)
    799 	(const :tag "C  velocity           Something like Notational Velocity for Org" org-velocity)
    800 	(const :tag "C  vm:                Links to VM folders/messages" ol-vm)
    801 	(const :tag "C  wikinodes:         CamelCase wiki-like links" org-wikinodes)
    802 	(const :tag "C  wl:                Links to Wanderlust folders/messages" ol-wl)
    803 	(repeat :tag "External packages" :inline t (symbol :tag "Package"))))
    804 
    805 (defvar org-export-registered-backends) ; From ox.el.
    806 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
    807 (declare-function org-export-backend-name "ox" (backend) t)
    808 (defcustom org-export-backends '(ascii html icalendar latex odt)
    809   "List of export back-ends that should be always available.
    810 
    811 If a description starts with <C>, the file is not part of Emacs and Org mode,
    812 so loading it will require that you have properly installed org-contrib
    813 package from NonGNU Emacs Lisp Package Archive
    814 https://elpa.nongnu.org/nongnu/org-contrib.html
    815 
    816 Unlike to `org-modules', libraries in this list will not be
    817 loaded along with Org, but only once the export framework is
    818 needed.
    819 
    820 This variable needs to be set before org.el is loaded.  If you
    821 need to make a change while Emacs is running, use the customize
    822 interface or run the following code, where VAL stands for the new
    823 value of the variable, after updating it:
    824 
    825   (progn
    826     (setq org-export-registered-backends
    827           (cl-remove-if-not
    828            (lambda (backend)
    829              (let ((name (org-export-backend-name backend)))
    830                (or (memq name val)
    831                    (catch \\='parentp
    832                      (dolist (b val)
    833                        (and (org-export-derived-backend-p b name)
    834                             (throw \\='parentp t)))))))
    835            org-export-registered-backends))
    836     (let ((new-list (mapcar #\\='org-export-backend-name
    837                             org-export-registered-backends)))
    838       (dolist (backend val)
    839         (cond
    840          ((not (load (format \"ox-%s\" backend) t t))
    841           (message \"Problems while trying to load export back-end \\=`%s\\='\"
    842                    backend))
    843          ((not (memq backend new-list)) (push backend new-list))))
    844       (set-default \\='org-export-backends new-list)))
    845 
    846 Adding a back-end to this list will also pull the back-end it
    847 depends on, if any."
    848   :group 'org
    849   :group 'org-export
    850   :version "26.1"
    851   :package-version '(Org . "9.0")
    852   :initialize 'custom-initialize-set
    853   :set (lambda (var val)
    854 	 (if (not (featurep 'ox)) (set-default-toplevel-value var val)
    855 	   ;; Any back-end not required anymore (not present in VAL and not
    856 	   ;; a parent of any back-end in the new value) is removed from the
    857 	   ;; list of registered back-ends.
    858 	   (setq org-export-registered-backends
    859 		 (cl-remove-if-not
    860 		  (lambda (backend)
    861 		    (let ((name (org-export-backend-name backend)))
    862 		      (or (memq name val)
    863 			  (catch 'parentp
    864 			    (dolist (b val)
    865 			      (and (org-export-derived-backend-p b name)
    866 				   (throw 'parentp t)))))))
    867 		  org-export-registered-backends))
    868 	   ;; Now build NEW-LIST of both new back-ends and required
    869 	   ;; parents.
    870 	   (let ((new-list (mapcar #'org-export-backend-name
    871 				   org-export-registered-backends)))
    872 	     (dolist (backend val)
    873 	       (cond
    874 		((not (load (format "ox-%s" backend) t t))
    875 		 (message "Problems while trying to load export back-end `%s'"
    876 			  backend))
    877 		((not (memq backend new-list)) (push backend new-list))))
    878 	     ;; Set VAR to that list with fixed dependencies.
    879 	     (set-default-toplevel-value var new-list))))
    880   :type '(set :greedy t
    881 	      (const :tag "   ascii       Export buffer to ASCII format" ascii)
    882 	      (const :tag "   beamer      Export buffer to Beamer presentation" beamer)
    883 	      (const :tag "   html        Export buffer to HTML format" html)
    884 	      (const :tag "   icalendar   Export buffer to iCalendar format" icalendar)
    885 	      (const :tag "   latex       Export buffer to LaTeX format" latex)
    886 	      (const :tag "   man         Export buffer to MAN format" man)
    887 	      (const :tag "   md          Export buffer to Markdown format" md)
    888 	      (const :tag "   odt         Export buffer to ODT format" odt)
    889 	      (const :tag "   org         Export buffer to Org format" org)
    890 	      (const :tag "   texinfo     Export buffer to Texinfo format" texinfo)
    891 	      (const :tag "C  confluence  Export buffer to Confluence Wiki format" confluence)
    892 	      (const :tag "C  deck        Export buffer to deck.js presentations" deck)
    893 	      (const :tag "C  freemind    Export buffer to Freemind mindmap format" freemind)
    894 	      (const :tag "C  groff       Export buffer to Groff format" groff)
    895 	      (const :tag "C  koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
    896 	      (const :tag "C  RSS 2.0     Export buffer to RSS 2.0 format" rss)
    897 	      (const :tag "C  s5          Export buffer to s5 presentations" s5)
    898 	      (const :tag "C  taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
    899 
    900 (eval-after-load 'ox
    901   '(dolist (backend org-export-backends)
    902      (condition-case nil (require (intern (format "ox-%s" backend)))
    903        (error (message "Problems while trying to load export back-end `%s'"
    904 		       backend)))))
    905 
    906 (defcustom org-support-shift-select nil
    907   "Non-nil means make shift-cursor commands select text when possible.
    908 \\<org-mode-map>
    909 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
    910 start selecting a region, or enlarge regions started in this way.
    911 In Org mode, in special contexts, these same keys are used for
    912 other purposes, important enough to compete with shift selection.
    913 Org tries to balance these needs by supporting `shift-select-mode'
    914 outside these special contexts, under control of this variable.
    915 
    916 The default of this variable is nil, to avoid confusing behavior.  Shifted
    917 cursor keys will then execute Org commands in the following contexts:
    918 - on a headline, changing TODO state (left/right) and priority (up/down)
    919 - on a time stamp, changing the time
    920 - in a plain list item, changing the bullet type
    921 - in a property definition line, switching between allowed values
    922 - in the BEGIN line of a clock table (changing the time block).
    923 - in a table, moving the cell in the specified direction.
    924 Outside these contexts, the commands will throw an error.
    925 
    926 When this variable is t and the cursor is not in a special
    927 context, Org mode will support shift-selection for making and
    928 enlarging regions.  To make this more effective, the bullet
    929 cycling will no longer happen anywhere in an item line, but only
    930 if the cursor is exactly on the bullet.
    931 
    932 If you set this variable to the symbol `always', then the keys
    933 will not be special in headlines, property lines, item lines, and
    934 table cells, to make shift selection work there as well.  If this is
    935 what you want, you can use the following alternative commands:
    936 `\\[org-todo]' and `\\[org-priority]' \
    937 to change TODO state and priority,
    938 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
    939 can be used to switch TODO sets,
    940 `\\[org-ctrl-c-minus]' to cycle item bullet types,
    941 and properties can be edited by hand or in column view.
    942 
    943 However, when the cursor is on a timestamp, shift-cursor commands
    944 will still edit the time stamp - this is just too good to give up."
    945   :group 'org
    946   :type '(choice
    947 	  (const :tag "Never" nil)
    948 	  (const :tag "When outside special context" t)
    949 	  (const :tag "Everywhere except timestamps" always)))
    950 
    951 (defcustom org-loop-over-headlines-in-active-region t
    952   "Shall some commands act upon headlines in the active region?
    953 
    954 When set to t, some commands will be performed in all headlines
    955 within the active region.
    956 
    957 When set to `start-level', some commands will be performed in all
    958 headlines within the active region, provided that these headlines
    959 are of the same level than the first one.
    960 
    961 When set to a string, those commands will be performed on the
    962 matching headlines within the active region.  Such string must be
    963 a tags/property/todo match as it is used in the agenda tags view.
    964 
    965 The list of commands is: `org-schedule', `org-deadline',
    966 `org-todo', `org-set-tags-command', `org-archive-subtree',
    967 `org-archive-set-tag', `org-toggle-archive-tag' and
    968 `org-archive-to-archive-sibling'.  The archiving commands skip
    969 already archived entries.
    970 
    971 See `org-agenda-loop-over-headlines-in-active-region' for the
    972 equivalent option for agenda views."
    973   :type '(choice (const :tag "Don't loop" nil)
    974 		 (const :tag "All headlines in active region" t)
    975 		 (const :tag "In active region, headlines at the same level than the first one" start-level)
    976 		 (string :tag "Tags/Property/Todo matcher"))
    977   :package-version '(Org . "9.4")
    978   :group 'org-todo
    979   :group 'org-archive)
    980 
    981 (defgroup org-startup nil
    982   "Startup options Org uses when first visiting a file."
    983   :tag "Org Startup"
    984   :group 'org)
    985 
    986 (defcustom org-startup-folded 'showeverything
    987   "Non-nil means entering Org mode will switch to OVERVIEW.
    988 
    989 This can also be configured on a per-file basis by adding one of
    990 the following lines anywhere in the buffer:
    991 
    992    #+STARTUP: fold              (or `overview', this is equivalent)
    993    #+STARTUP: nofold            (or `showall', this is equivalent)
    994    #+STARTUP: content
    995    #+STARTUP: show<n>levels (<n> = 2..5)
    996    #+STARTUP: showeverything
    997 
    998 Set `org-agenda-inhibit-startup' to a non-nil value if you want
    999 to ignore this option when Org opens agenda files for the first
   1000 time."
   1001   :group 'org-startup
   1002   :package-version '(Org . "9.4")
   1003   :type '(choice
   1004 	  (const :tag "nofold: show all" nil)
   1005 	  (const :tag "fold: overview" t)
   1006 	  (const :tag "fold: show two levels" show2levels)
   1007 	  (const :tag "fold: show three levels" show3levels)
   1008 	  (const :tag "fold: show four levels" show4evels)
   1009 	  (const :tag "fold: show five levels" show5levels)
   1010 	  (const :tag "content: all headlines" content)
   1011 	  (const :tag "show everything, even drawers" showeverything)))
   1012 
   1013 (defcustom org-startup-truncated t
   1014   "Non-nil means entering Org mode will set `truncate-lines'.
   1015 This is useful since some lines containing links can be very long and
   1016 uninteresting.  Also tables look terrible when wrapped.
   1017 
   1018 The variable `org-startup-truncated' allows to configure
   1019 truncation for Org mode different to the other modes that use the
   1020 variable `truncate-lines' and as a shortcut instead of putting
   1021 the variable `truncate-lines' into the `org-mode-hook'.  If one
   1022 wants to configure truncation for Org mode not statically but
   1023 dynamically e.g. in a hook like `ediff-prepare-buffer-hook' then
   1024 the variable `truncate-lines' has to be used because in such a
   1025 case it is too late to set the variable `org-startup-truncated'."
   1026   :group 'org-startup
   1027   :type 'boolean)
   1028 
   1029 (defcustom org-startup-indented nil
   1030   "Non-nil means turn on `org-indent-mode' on startup.
   1031 This can also be configured on a per-file basis by adding one of
   1032 the following lines anywhere in the buffer:
   1033 
   1034    #+STARTUP: indent
   1035    #+STARTUP: noindent"
   1036   :group 'org-structure
   1037   :type '(choice
   1038 	  (const :tag "Not" nil)
   1039 	  (const :tag "Globally (slow on startup in large files)" t)))
   1040 
   1041 (defcustom org-startup-numerated nil
   1042   "Non-nil means turn on `org-num-mode' on startup.
   1043 This can also be configured on a per-file basis by adding one of
   1044 the following lines anywhere in the buffer:
   1045 
   1046    #+STARTUP: num
   1047    #+STARTUP: nonum"
   1048   :group 'org-structure
   1049   :package-version '(Org . "9.4")
   1050   :type '(choice
   1051 	  (const :tag "Not" nil)
   1052 	  (const :tag "Globally" t)))
   1053 
   1054 (defcustom org-use-sub-superscripts t
   1055   "Non-nil means interpret \"_\" and \"^\" for display.
   1056 
   1057 If you want to control how Org exports those characters, see
   1058 `org-export-with-sub-superscripts'.
   1059 
   1060 When this option is turned on, you can use TeX-like syntax for
   1061 sub- and superscripts within the buffer.  Several characters after
   1062 \"_\" or \"^\" will be considered as a single item - so grouping
   1063 with {} is normally not needed.  For example, the following things
   1064 will be parsed as single sub- or superscripts:
   1065 
   1066  10^24   or   10^tau     several digits will be considered 1 item.
   1067  10^-12  or   10^-tau    a leading sign with digits or a word
   1068  x^2-y^3                 will be read as x^2 - y^3, because items are
   1069 			 terminated by almost any nonword/nondigit char.
   1070  x_{i^2} or   x^(2-i)    braces or parenthesis do grouping.
   1071 
   1072 Still, ambiguity is possible.  So when in doubt, use {} to enclose
   1073 the sub/superscript.  If you set this variable to the symbol `{}',
   1074 the braces are *required* in order to trigger interpretations as
   1075 sub/superscript.  This can be helpful in documents that need \"_\"
   1076 frequently in plain text."
   1077   :group 'org-startup
   1078   :version "24.4"
   1079   :package-version '(Org . "8.0")
   1080   :type '(choice
   1081 	  (const :tag "Always interpret" t)
   1082 	  (const :tag "Only with braces" {})
   1083 	  (const :tag "Never interpret" nil)))
   1084 
   1085 (defcustom org-startup-with-beamer-mode nil
   1086   "Non-nil means turn on `org-beamer-mode' on startup.
   1087 This can also be configured on a per-file basis by adding one of
   1088 the following lines anywhere in the buffer:
   1089 
   1090    #+STARTUP: beamer"
   1091   :group 'org-startup
   1092   :version "24.1"
   1093   :type 'boolean)
   1094 
   1095 (defcustom org-startup-align-all-tables nil
   1096   "Non-nil means align all tables when visiting a file.
   1097 This can also be configured on a per-file basis by adding one of
   1098 the following lines anywhere in the buffer:
   1099    #+STARTUP: align
   1100    #+STARTUP: noalign"
   1101   :group 'org-startup
   1102   :type 'boolean)
   1103 
   1104 (defcustom org-startup-shrink-all-tables nil
   1105   "Non-nil means shrink all table columns with a width cookie.
   1106 This can also be configured on a per-file basis by adding one of
   1107 the following lines anywhere in the buffer:
   1108    #+STARTUP: shrink"
   1109   :group 'org-startup
   1110   :type 'boolean
   1111   :version "27.1"
   1112   :package-version '(Org . "9.2")
   1113   :safe #'booleanp)
   1114 
   1115 (defcustom org-startup-with-inline-images nil
   1116   "Non-nil means show inline images when loading a new Org file.
   1117 This can also be configured on a per-file basis by adding one of
   1118 the following lines anywhere in the buffer:
   1119    #+STARTUP: inlineimages
   1120    #+STARTUP: noinlineimages"
   1121   :group 'org-startup
   1122   :version "24.1"
   1123   :type 'boolean)
   1124 
   1125 (defcustom org-startup-with-latex-preview nil
   1126   "Non-nil means preview LaTeX fragments when loading a new Org file.
   1127 
   1128 This can also be configured on a per-file basis by adding one of
   1129 the following lines anywhere in the buffer:
   1130    #+STARTUP: latexpreview
   1131    #+STARTUP: nolatexpreview"
   1132   :group 'org-startup
   1133   :version "24.4"
   1134   :package-version '(Org . "8.0")
   1135   :type 'boolean)
   1136 
   1137 (defcustom org-insert-mode-line-in-empty-file nil
   1138   "Non-nil means insert the first line setting Org mode in empty files.
   1139 When the function `org-mode' is called interactively in an empty file, this
   1140 normally means that the file name does not automatically trigger Org mode.
   1141 To ensure that the file will always be in Org mode in the future, a
   1142 line enforcing Org mode will be inserted into the buffer, if this option
   1143 has been set."
   1144   :group 'org-startup
   1145   :type 'boolean)
   1146 
   1147 (defcustom org-ellipsis nil
   1148   "The ellipsis to use in the Org mode outline.
   1149 
   1150 When nil, just use the standard three dots.  When a non-empty string,
   1151 use that string instead.
   1152 
   1153 The change affects only Org mode (which will then use its own display table).
   1154 Changing this requires executing `\\[org-mode]' in a buffer to become
   1155 effective.  It cannot be set as a local variable."
   1156   :group 'org-startup
   1157   :type '(choice (const :tag "Default" nil)
   1158 		 (string :tag "String" :value "...#")))
   1159 
   1160 (defvar org-display-table nil
   1161   "The display table for Org mode, in case `org-ellipsis' is non-nil.")
   1162 
   1163 (defcustom org-directory "~/org"
   1164   "Directory with Org files.
   1165 This is just a default location to look for Org files.  There is no need
   1166 at all to put your files into this directory.  It is used in the
   1167 following situations:
   1168 
   1169 1. When a capture template specifies a target file that is not an
   1170    absolute path.  The path will then be interpreted relative to
   1171    `org-directory'
   1172 2. When the value of variable `org-agenda-files' is a single file, any
   1173    relative paths in this file will be taken as relative to
   1174    `org-directory'."
   1175   :group 'org-refile
   1176   :group 'org-capture
   1177   :type 'directory)
   1178 
   1179 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
   1180   "Default target for storing notes.
   1181 Used as a fall back file for org-capture.el, for templates that
   1182 do not specify a target file."
   1183   :group 'org-refile
   1184   :group 'org-capture
   1185   :type 'file)
   1186 
   1187 (defcustom org-reverse-note-order nil
   1188   "Non-nil means store new notes at the beginning of a file or entry.
   1189 When nil, new notes will be filed to the end of a file or entry.
   1190 This can also be a list with cons cells of regular expressions that
   1191 are matched against file names, and values."
   1192   :group 'org-capture
   1193   :group 'org-refile
   1194   :type '(choice
   1195 	  (const :tag "Reverse always" t)
   1196 	  (const :tag "Reverse never" nil)
   1197 	  (repeat :tag "By file name regexp"
   1198 		  (cons regexp boolean))))
   1199 
   1200 (defgroup org-keywords nil
   1201   "Keywords in Org mode."
   1202   :tag "Org Keywords"
   1203   :group 'org)
   1204 
   1205 (defcustom org-closed-keep-when-no-todo nil
   1206   "Remove CLOSED: time-stamp when switching back to a non-todo state?"
   1207   :group 'org-todo
   1208   :group 'org-keywords
   1209   :version "24.4"
   1210   :package-version '(Org . "8.0")
   1211   :type 'boolean)
   1212 
   1213 (defgroup org-structure nil
   1214   "Options concerning the general structure of Org files."
   1215   :tag "Org Structure"
   1216   :group 'org)
   1217 
   1218 (defcustom org-indirect-buffer-display 'other-window
   1219   "How should indirect tree buffers be displayed?
   1220 
   1221 This applies to indirect buffers created with the commands
   1222 `org-tree-to-indirect-buffer' and `org-agenda-tree-to-indirect-buffer'.
   1223 
   1224 Valid values are:
   1225 current-window   Display in the current window
   1226 other-window     Just display in another window.
   1227 dedicated-frame  Create one new frame, and re-use it each time.
   1228 new-frame        Make a new frame each time.  Note that in this case
   1229                  previously-made indirect buffers are kept, and you need to
   1230                  kill these buffers yourself."
   1231   :group 'org-structure
   1232   :group 'org-agenda-windows
   1233   :type '(choice
   1234 	  (const :tag "In current window" current-window)
   1235 	  (const :tag "In current frame, other window" other-window)
   1236 	  (const :tag "Each time a new frame" new-frame)
   1237 	  (const :tag "One dedicated frame" dedicated-frame)))
   1238 
   1239 (defconst org-file-apps-gnu
   1240   '((remote . emacs)
   1241     (system . mailcap)
   1242     (t . mailcap))
   1243   "Default file applications on a UNIX or GNU/Linux system.
   1244 See `org-file-apps'.")
   1245 
   1246 (defconst org-file-apps-macos
   1247   '((remote . emacs)
   1248     (system . "open %s")
   1249     ("ps.gz"  . "gv %s")
   1250     ("eps.gz" . "gv %s")
   1251     ("dvi"    . "xdvi %s")
   1252     ("fig"    . "xfig %s")
   1253     (t . "open %s"))
   1254   "Default file applications on a macOS system.
   1255 The system \"open\" is known as a default, but we use X11 applications
   1256 for some files for which the OS does not have a good default.
   1257 See `org-file-apps'.")
   1258 
   1259 (defconst org-file-apps-windowsnt
   1260   (list '(remote . emacs)
   1261 	(cons 'system (lambda (file _path)
   1262 			(with-no-warnings (w32-shell-execute "open" file))))
   1263 	(cons t (lambda (file _path)
   1264 		  (with-no-warnings (w32-shell-execute "open" file)))))
   1265   "Default file applications on a Windows NT system.
   1266 The system \"open\" is used for most files.
   1267 See `org-file-apps'.")
   1268 
   1269 (defcustom org-file-apps
   1270   '((auto-mode . emacs)
   1271     (directory . emacs)
   1272     ("\\.mm\\'" . default)
   1273     ("\\.x?html?\\'" . default)
   1274     ("\\.pdf\\'" . default))
   1275   "Applications for opening `file:path' items in a document.
   1276 
   1277 \\<org-mode-map>
   1278 Org mode uses system defaults for different file types, but you
   1279 can use this variable to set the application for a given file
   1280 extension.  The entries in this list are cons cells where the car
   1281 identifies files and the cdr the corresponding command.
   1282 
   1283 Possible values for the file identifier are:
   1284 
   1285  \"string\"    A string as a file identifier can be interpreted in different
   1286                ways, depending on its contents:
   1287 
   1288                - Alphanumeric characters only:
   1289                  Match links with this file extension.
   1290                  Example: (\"pdf\" . \"evince %s\")
   1291                           to open PDFs with evince.
   1292 
   1293                - Regular expression: Match links where the
   1294                  filename matches the regexp.  If you want to
   1295                  use groups here, use shy groups.
   1296 
   1297                  Example: (\"\\\\.x?html\\\\\\='\" . \"firefox %s\")
   1298                           (\"\\\\(?:xhtml\\\\|html\\\\)\\\\\\='\" . \"firefox %s\")
   1299                           to open *.html and *.xhtml with firefox.
   1300 
   1301                - Regular expression which contains (non-shy) groups:
   1302                  Match links where the whole link, including \"::\", and
   1303                  anything after that, matches the regexp.
   1304                  In a custom command string, %1, %2, etc. are replaced with
   1305                  the parts of the link that were matched by the groups.
   1306                  For backwards compatibility, if a command string is given
   1307                  that does not use any of the group matches, this case is
   1308                  handled identically to the second one (i.e. match against
   1309                  file name only).
   1310                  In a custom function, you can access the group matches with
   1311                  (match-string n link).
   1312 
   1313                  Example: (\"\\\\.pdf::\\\\([0-9]+\\\\)\\\\\\='\" . \
   1314 \"evince -p %1 %s\")
   1315                      to open [[file:document.pdf::5]] with evince at page 5.
   1316 
   1317                  Likely, you will need more entries: without page
   1318                  number; with search pattern; with cross-reference
   1319                  anchor; some combination of options.  Consider simple
   1320                  pattern here and a Lisp function to determine command
   1321                  line arguments instead.  Passing argument list to
   1322                  `call-process' or `make-process' directly allows to
   1323                  avoid treating some character in peculiar file names
   1324                  as shell specialls causing executing part of file
   1325                  name as a subcommand.
   1326 
   1327  `directory'   Matches a directory
   1328  `remote'      Matches a remote file, accessible through tramp.
   1329                Remote files most likely should be visited through Emacs
   1330                because external applications cannot handle such paths.
   1331 `auto-mode'    Matches files that are matched by any entry in `auto-mode-alist',
   1332                so all files Emacs knows how to handle.  Using this with
   1333                command `emacs' will open most files in Emacs.  Beware that this
   1334                will also open html files inside Emacs, unless you add
   1335                (\"html\" . default) to the list as well.
   1336  `system'      The system command to open files, like `open' on Windows
   1337                and macOS, and mailcap under GNU/Linux.  This is the command
   1338                that will be selected if you call `org-open-at-point' with a
   1339                double prefix argument (`\\[universal-argument] \
   1340 \\[universal-argument] \\[org-open-at-point]').
   1341  t             Default for files not matched by any of the other options.
   1342 
   1343 Possible values for the command are:
   1344 
   1345  `emacs'       The file will be visited by the current Emacs process.
   1346  `default'     Use the default application for this file type, which is the
   1347                association for t in the list, most likely in the system-specific
   1348                part.  This can be used to overrule an unwanted setting in the
   1349                system-specific variable.
   1350  `system'      Use the system command for opening files, like \"open\".
   1351                This command is specified by the entry whose car is `system'.
   1352                Most likely, the system-specific version of this variable
   1353                does define this command, but you can overrule/replace it
   1354                here.
   1355 `mailcap'      Use command specified in the mailcaps.
   1356  string        A command to be executed by a shell; %s will be replaced
   1357                by the path to the file.
   1358  function      A Lisp function, which will be called with two arguments:
   1359                the file path and the original link string, without the
   1360                \"file:\" prefix.
   1361 
   1362 For more examples, see the system specific constants
   1363 `org-file-apps-macos'
   1364 `org-file-apps-windowsnt'
   1365 `org-file-apps-gnu'."
   1366   :group 'org
   1367   :package-version '(Org . "9.4")
   1368   :type '(repeat
   1369 	  (cons (choice :value ""
   1370 			(string :tag "Extension")
   1371 			(const :tag "System command to open files" system)
   1372 			(const :tag "Default for unrecognized files" t)
   1373 			(const :tag "Remote file" remote)
   1374 			(const :tag "Links to a directory" directory)
   1375 			(const :tag "Any files that have Emacs modes"
   1376 			       auto-mode))
   1377 		(choice :value ""
   1378 			(const :tag "Visit with Emacs" emacs)
   1379 			(const :tag "Use default" default)
   1380 			(const :tag "Use the system command" system)
   1381 			(string :tag "Command")
   1382 			(function :tag "Function")))))
   1383 
   1384 (defcustom org-resource-download-policy 'prompt
   1385   "The policy applied to requests to obtain remote resources.
   1386 
   1387 This affects keywords like #+setupfile and #+include on export,
   1388 `org-persist-write:url',and `org-attach-url' in non-interactive
   1389 Emacs sessions.
   1390 
   1391 This recognizes four possible values:
   1392 - t, remote resources should always be downloaded.
   1393 - prompt, you will be prompted to download resources not considered safe.
   1394 - safe, only resources considered safe will be downloaded.
   1395 - nil, never download remote resources.
   1396 
   1397 A resource is considered safe if it matches one of the patterns
   1398 in `org-safe-remote-resources'."
   1399   :group 'org
   1400   :package-version '(Org . "9.6")
   1401   :type '(choice (const :tag "Always download remote resources" t)
   1402                  (const :tag "Prompt before downloading an unsafe resource" prompt)
   1403                  (const :tag "Only download resources considered safe" safe)
   1404                  (const :tag "Never download any resources" nil)))
   1405 
   1406 (defcustom org-safe-remote-resources nil
   1407   "A list of regexp patterns matching safe URIs.
   1408 URI regexps are applied to both URLs and Org files requesting
   1409 remote resources."
   1410   :group 'org
   1411   :package-version '(Org . "9.6")
   1412   :type '(repeat regexp))
   1413 
   1414 (defcustom org-open-non-existing-files nil
   1415   "Non-nil means `org-open-file' opens non-existing files.
   1416 
   1417 When nil, an error is thrown.
   1418 
   1419 This variable applies only to external applications because they
   1420 might choke on non-existing files.  If the link is to a file that
   1421 will be opened in Emacs, the variable is ignored."
   1422   :group 'org
   1423   :type 'boolean
   1424   :safe #'booleanp)
   1425 
   1426 (defcustom org-open-directory-means-index-dot-org nil
   1427   "When non-nil a link to a directory really means to \"index.org\".
   1428 When nil, following a directory link runs Dired or opens
   1429 a finder/explorer window on that directory."
   1430   :group 'org
   1431   :type 'boolean
   1432   :safe #'booleanp)
   1433 
   1434 (defcustom org-bookmark-names-plist
   1435   '(:last-capture "org-capture-last-stored"
   1436 		  :last-refile "org-refile-last-stored"
   1437 		  :last-capture-marker "org-capture-last-stored-marker")
   1438   "Names for bookmarks automatically set by some Org commands.
   1439 This can provide strings as names for a number of bookmarks Org sets
   1440 automatically.  The following keys are currently implemented:
   1441   :last-capture
   1442   :last-capture-marker
   1443   :last-refile
   1444 When a key does not show up in the property list, the corresponding bookmark
   1445 is not set."
   1446   :group 'org-structure
   1447   :type 'plist)
   1448 
   1449 (defgroup org-edit-structure nil
   1450   "Options concerning structure editing in Org mode."
   1451   :tag "Org Edit Structure"
   1452   :group 'org-structure)
   1453 
   1454 (defcustom org-odd-levels-only nil
   1455   "Non-nil means skip even levels and only use odd levels for the outline.
   1456 This has the effect that two stars are being added/taken away in
   1457 promotion/demotion commands.  It also influences how levels are
   1458 handled by the exporters.
   1459 Changing it requires restart of `font-lock-mode' to become effective
   1460 for fontification also in regions already fontified.
   1461 You may also set this on a per-file basis by adding one of the following
   1462 lines to the buffer:
   1463 
   1464    #+STARTUP: odd
   1465    #+STARTUP: oddeven"
   1466   :group 'org-edit-structure
   1467   :group 'org-appearance
   1468   :type 'boolean)
   1469 
   1470 (defcustom org-adapt-indentation nil
   1471   "Non-nil means adapt indentation to outline node level.
   1472 
   1473 When set to t, Org assumes that you write outlines by indenting
   1474 text in each node to align with the headline, after the stars.
   1475 
   1476 When this variable is set to `headline-data', Org only adapts the
   1477 indentation of the data lines right below the headline, such as
   1478 planning/clock lines and property/logbook drawers.
   1479 
   1480 The following issues are influenced by this variable:
   1481 
   1482 - The indentation is increased by one space in a demotion
   1483   command, and decreased by one in a promotion command.  However,
   1484   in the latter case, if shifting some line in the entry body
   1485   would alter document structure (e.g., insert a new headline),
   1486   indentation is not changed at all.
   1487 
   1488 - Property drawers and planning information is inserted indented
   1489   when this variable is set.  When nil, they will not be indented.
   1490 
   1491 - TAB indents a line relative to current level.  The lines below
   1492   a headline will be indented when this variable is set to t.
   1493 
   1494 Note that this is all about true indentation, by adding and
   1495 removing space characters.  See also \"org-indent.el\" which does
   1496 level-dependent indentation in a virtual way, i.e. at display
   1497 time in Emacs."
   1498   :group 'org-edit-structure
   1499   :type '(choice
   1500 	  (const :tag "Adapt indentation for all lines" t)
   1501 	  (const :tag "Adapt indentation for headline data lines"
   1502 		 headline-data)
   1503 	  (const :tag "Do not adapt indentation at all" nil))
   1504   :safe (lambda (x) (memq x '(t nil headline-data))))
   1505 
   1506 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
   1507 
   1508 (defcustom org-special-ctrl-a/e nil
   1509   "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
   1510 
   1511 When t, `C-a' will bring back the cursor to the beginning of the
   1512 headline text, i.e. after the stars and after a possible TODO
   1513 keyword.  In an item, this will be the position after bullet and
   1514 check-box, if any.  When the cursor is already at that position,
   1515 another `C-a' will bring it to the beginning of the line.
   1516 
   1517 `C-e' will jump to the end of the headline, ignoring the presence
   1518 of tags in the headline.  A second `C-e' will then jump to the
   1519 true end of the line, after any tags.  This also means that, when
   1520 this variable is non-nil, `C-e' also will never jump beyond the
   1521 end of the heading of a folded section, i.e. not after the
   1522 ellipses.
   1523 
   1524 When set to the symbol `reversed', the first `C-a' or `C-e' works
   1525 normally, going to the true line boundary first.  Only a directly
   1526 following, identical keypress will bring the cursor to the
   1527 special positions.
   1528 
   1529 This may also be a cons cell where the behavior for `C-a' and
   1530 `C-e' is set separately."
   1531   :group 'org-edit-structure
   1532   :type '(choice
   1533 	  (const :tag "off" nil)
   1534 	  (const :tag "on: after stars/bullet and before tags first" t)
   1535 	  (const :tag "reversed: true line boundary first" reversed)
   1536 	  (cons :tag "Set C-a and C-e separately"
   1537 		(choice :tag "Special C-a"
   1538 			(const :tag "off" nil)
   1539 			(const :tag "on: after  stars/bullet first" t)
   1540 			(const :tag "reversed: before stars/bullet first" reversed))
   1541 		(choice :tag "Special C-e"
   1542 			(const :tag "off" nil)
   1543 			(const :tag "on: before tags first" t)
   1544 			(const :tag "reversed: after tags first" reversed)))))
   1545 
   1546 (defcustom org-special-ctrl-k nil
   1547   "Non-nil means that \\<org-mode-map>\\[org-kill-line] \
   1548 will behave specially in headlines.
   1549 
   1550 When nil, \\[org-kill-line] will call the default `kill-line' command.
   1551 Otherwise, the following will happen when point is in a headline:
   1552 
   1553 - At the beginning of a headline, kill the entire line.
   1554 - In the middle of the headline text, kill the text up to the tags.
   1555 - After the headline text and before the tags, kill all the tags."
   1556   :group 'org-edit-structure
   1557   :type 'boolean)
   1558 
   1559 (defcustom org-ctrl-k-protect-subtree nil
   1560   "Non-nil means, do not delete a hidden subtree with `C-k'.
   1561 When set to the symbol `error', simply throw an error when `C-k' is
   1562 used to kill (part-of) a headline that has hidden text behind it.
   1563 Any other non-nil value will result in a query to the user, if it is
   1564 OK to kill that hidden subtree.  When nil, kill without remorse."
   1565   :group 'org-edit-structure
   1566   :version "24.1"
   1567   :type '(choice
   1568 	  (const :tag "Do not protect hidden subtrees" nil)
   1569 	  (const :tag "Protect hidden subtrees with a security query" t)
   1570 	  (const :tag "Never kill a hidden subtree with C-k" error)))
   1571 
   1572 (defcustom org-special-ctrl-o t
   1573   "Non-nil means, make `open-line' (\\[open-line]) insert a row in tables."
   1574   :group 'org-edit-structure
   1575   :type 'boolean)
   1576 
   1577 (defcustom org-yank-folded-subtrees t
   1578   "Non-nil means when yanking subtrees, fold them.
   1579 If the kill is a single subtree, or a sequence of subtrees, i.e. if
   1580 it starts with a heading and all other headings in it are either children
   1581 or siblings, then fold all the subtrees.  However, do this only if no
   1582 text after the yank would be swallowed into a folded tree by this action."
   1583   :group 'org-edit-structure
   1584   :type 'boolean)
   1585 
   1586 (defcustom org-yank-adjusted-subtrees nil
   1587   "Non-nil means when yanking subtrees, adjust the level.
   1588 With this setting, `org-paste-subtree' is used to insert the subtree, see
   1589 this function for details."
   1590   :group 'org-edit-structure
   1591   :type 'boolean)
   1592 
   1593 (defcustom org-M-RET-may-split-line '((default . t))
   1594   "Non-nil means M-RET will split the line at the cursor position.
   1595 When nil, it will go to the end of the line before making a
   1596 new line.
   1597 You may also set this option in a different way for different
   1598 contexts.  Valid contexts are:
   1599 
   1600 headline  when creating a new headline
   1601 item      when creating a new item
   1602 table     in a table field
   1603 default   the value to be used for all contexts not explicitly
   1604           customized"
   1605   :group 'org-structure
   1606   :group 'org-table
   1607   :type '(choice
   1608 	  (const :tag "Always" t)
   1609 	  (const :tag "Never" nil)
   1610 	  (repeat :greedy t :tag "Individual contexts"
   1611 		  (cons
   1612 		   (choice :tag "Context"
   1613 			   (const headline)
   1614 			   (const item)
   1615 			   (const table)
   1616 			   (const default))
   1617 		   (boolean)))))
   1618 
   1619 (defcustom org-insert-heading-respect-content nil
   1620   "Non-nil means insert new headings after the current subtree.
   1621 \\<org-mode-map>
   1622 When nil, the new heading is created directly after the current line.
   1623 The commands `\\[org-insert-heading-respect-content]' and \
   1624 `\\[org-insert-todo-heading-respect-content]' turn this variable on
   1625 for the duration of the command."
   1626   :group 'org-structure
   1627   :type 'boolean)
   1628 
   1629 (defcustom org-blank-before-new-entry '((heading . auto)
   1630 					(plain-list-item . auto))
   1631   "Should `org-insert-heading' leave a blank line before new heading/item?
   1632 The value is an alist, with `heading' and `plain-list-item' as CAR,
   1633 and a boolean flag as CDR.  The cdr may also be the symbol `auto', in
   1634 which case Org will look at the surrounding headings/items and try to
   1635 make an intelligent decision whether to insert a blank line or not."
   1636   :group 'org-edit-structure
   1637   :type '(list
   1638 	  (cons (const heading)
   1639 		(choice (const :tag "Never" nil)
   1640 			(const :tag "Always" t)
   1641 			(const :tag "Auto" auto)))
   1642 	  (cons (const plain-list-item)
   1643 		(choice (const :tag "Never" nil)
   1644 			(const :tag "Always" t)
   1645 			(const :tag "Auto" auto)))))
   1646 
   1647 (defcustom org-insert-heading-hook nil
   1648   "Hook being run after inserting a new heading."
   1649   :group 'org-edit-structure
   1650   :type 'hook)
   1651 
   1652 (defgroup org-sparse-trees nil
   1653   "Options concerning sparse trees in Org mode."
   1654   :tag "Org Sparse Trees"
   1655   :group 'org-structure)
   1656 
   1657 (defcustom org-highlight-sparse-tree-matches t
   1658   "Non-nil means highlight all matches that define a sparse tree.
   1659 The highlights will automatically disappear the next time the buffer is
   1660 changed by an edit command."
   1661   :group 'org-sparse-trees
   1662   :type 'boolean)
   1663 
   1664 (defcustom org-remove-highlights-with-change t
   1665   "Non-nil means any change to the buffer will remove temporary highlights.
   1666 \\<org-mode-map>\
   1667 Such highlights are created by `org-occur' and `org-clock-display'.
   1668 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
   1669 to get rid of the highlights.
   1670 The highlights created by `org-latex-preview' always need
   1671 `\\[org-latex-preview]' to be removed."
   1672   :group 'org-sparse-trees
   1673   :group 'org-time
   1674   :type 'boolean)
   1675 
   1676 (defcustom org-occur-case-fold-search t
   1677   "Non-nil means `org-occur' should be case-insensitive.
   1678 If set to `smart' the search will be case-insensitive only if it
   1679 doesn't specify any upper case character."
   1680   :group 'org-sparse-trees
   1681   :version "26.1"
   1682   :type '(choice
   1683 	  (const :tag "Case-sensitive" nil)
   1684 	  (const :tag "Case-insensitive" t)
   1685 	  (const :tag "Case-insensitive for lower case searches only" smart)))
   1686 
   1687 (defcustom org-occur-hook '(org-first-headline-recenter)
   1688   "Hook that is run after `org-occur' has constructed a sparse tree.
   1689 This can be used to recenter the window to show as much of the structure
   1690 as possible."
   1691   :group 'org-sparse-trees
   1692   :type 'hook)
   1693 
   1694 (defcustom org-self-insert-cluster-for-undo nil
   1695   "Non-nil means cluster self-insert commands for undo when possible.
   1696 If this is set, then, like in the Emacs command loop, 20 consecutive
   1697 characters will be undone together.
   1698 This is configurable, because there is some impact on typing performance."
   1699   :group 'org-table
   1700   :type 'boolean)
   1701 
   1702 (defvaralias 'org-activate-links 'org-highlight-links)
   1703 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
   1704   "Types of links that should be highlighted in Org files.
   1705 
   1706 This is a list of symbols, each one of them leading to the
   1707 highlighting of a certain link type.
   1708 
   1709 You can still open links that are not highlighted.
   1710 
   1711 In principle, it does not hurt to turn on highlighting for all
   1712 link types.  There may be a small gain when turning off unused
   1713 link types.  The types are:
   1714 
   1715 bracket   The recommended [[link][description]] or [[link]] links with hiding.
   1716 angle     Links in angular brackets that may contain whitespace like
   1717           <bbdb:Carsten Dominik>.
   1718 plain     Plain links in normal text, no whitespace, like https://gnu.org.
   1719 radio     Text that is matched by a radio target, see manual for details.
   1720 tag       Tag settings in a headline (link to tag search).
   1721 date      Time stamps (link to calendar).
   1722 footnote  Footnote labels.
   1723 
   1724 If you set this variable during an Emacs session, use `org-mode-restart'
   1725 in the Org buffer so that the change takes effect."
   1726   :group 'org-appearance
   1727   :type '(set :greedy t
   1728 	      (const :tag "Double bracket links" bracket)
   1729 	      (const :tag "Angular bracket links" angle)
   1730 	      (const :tag "Plain text links" plain)
   1731 	      (const :tag "Radio target matches" radio)
   1732 	      (const :tag "Tags" tag)
   1733 	      (const :tag "Timestamps" date)
   1734 	      (const :tag "Footnotes" footnote)))
   1735 
   1736 (defcustom org-mark-ring-length 4
   1737   "Number of different positions to be recorded in the ring.
   1738 Changing this requires a restart of Emacs to work correctly."
   1739   :group 'org-link-follow
   1740   :type 'integer)
   1741 
   1742 (defgroup org-todo nil
   1743   "Options concerning TODO items in Org mode."
   1744   :tag "Org TODO"
   1745   :group 'org)
   1746 
   1747 (defgroup org-progress nil
   1748   "Options concerning Progress logging in Org mode."
   1749   :tag "Org Progress"
   1750   :group 'org-time)
   1751 
   1752 (defvar org-todo-interpretation-widgets
   1753   '((:tag "Sequence (cycling hits every state)" sequence)
   1754     (:tag "Type     (cycling directly to DONE)" type))
   1755   "The available interpretation symbols for customizing `org-todo-keywords'.
   1756 Interested libraries should add to this list.")
   1757 
   1758 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
   1759   "List of TODO entry keyword sequences and their interpretation.
   1760 \\<org-mode-map>This is a list of sequences.
   1761 
   1762 Each sequence starts with a symbol, either `sequence' or `type',
   1763 indicating if the keywords should be interpreted as a sequence of
   1764 action steps, or as different types of TODO items.  The first
   1765 keywords are states requiring action - these states will select a headline
   1766 for inclusion into the global TODO list Org produces.  If one of the
   1767 \"keywords\" is the vertical bar, \"|\", the remaining keywords
   1768 signify that no further action is necessary.  If \"|\" is not found,
   1769 the last keyword is treated as the only DONE state of the sequence.
   1770 
   1771 The command `\\[org-todo]' cycles an entry through these states, and one
   1772 additional state where no keyword is present.  For details about this
   1773 cycling, see the manual.
   1774 
   1775 TODO keywords and interpretation can also be set on a per-file basis with
   1776 the special #+SEQ_TODO and #+TYP_TODO lines.
   1777 
   1778 Each keyword can optionally specify a character for fast state selection
   1779 \(in combination with the variable `org-use-fast-todo-selection')
   1780 and specifiers for state change logging, using the same syntax that
   1781 is used in the \"#+TODO:\" lines.  For example, \"WAIT(w)\" says that
   1782 the WAIT state can be selected with the \"w\" key.  \"WAIT(w!)\"
   1783 indicates to record a time stamp each time this state is selected.
   1784 
   1785 Each keyword may also specify if a timestamp or a note should be
   1786 recorded when entering or leaving the state, by adding additional
   1787 characters in the parenthesis after the keyword.  This looks like this:
   1788 \"WAIT(w@/!)\".  \"@\" means to add a note (with time), \"!\" means to
   1789 record only the time of the state change.  With X and Y being either
   1790 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
   1791 Y when leaving the state if and only if the *target* state does not
   1792 define X.  You may omit any of the fast-selection key or X or /Y,
   1793 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
   1794 
   1795 For backward compatibility, this variable may also be just a list
   1796 of keywords.  In this case the interpretation (sequence or type) will be
   1797 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
   1798   :group 'org-todo
   1799   :group 'org-keywords
   1800   :type '(choice
   1801 	  (repeat :tag "Old syntax, just keywords"
   1802 		  (string :tag "Keyword"))
   1803 	  (repeat :tag "New syntax"
   1804 		  (cons
   1805 		   (choice
   1806 		    :tag "Interpretation"
   1807 		    ;;Quick and dirty way to see
   1808                     ;;`org-todo-interpretation'.  This takes the
   1809 		    ;;place of item arguments
   1810 		    :convert-widget
   1811 		    (lambda (widget)
   1812 		      (widget-put widget
   1813 				  :args (mapcar
   1814 					 (lambda (x)
   1815 					   (widget-convert
   1816 					    (cons 'const x)))
   1817 					 org-todo-interpretation-widgets))
   1818 		      widget))
   1819 		   (repeat
   1820 		    (string :tag "Keyword"))))))
   1821 
   1822 (defvar-local org-todo-keywords-1 nil
   1823   "All TODO and DONE keywords active in a buffer.")
   1824 (defvar org-todo-keywords-for-agenda nil)
   1825 (defvar org-done-keywords-for-agenda nil)
   1826 (defvar org-todo-keyword-alist-for-agenda nil)
   1827 (defvar org-tag-alist-for-agenda nil
   1828   "Alist of all tags from all agenda files.")
   1829 (defvar org-tag-groups-alist-for-agenda nil
   1830   "Alist of all groups tags from all current agenda files.")
   1831 (defvar-local org-tag-groups-alist nil)
   1832 (defvar org-agenda-contributing-files nil)
   1833 (defvar-local org-current-tag-alist nil
   1834   "Alist of all tag groups in current buffer.
   1835 This variable takes into consideration `org-tag-alist',
   1836 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
   1837 (defvar-local org-not-done-keywords nil)
   1838 (defvar-local org-done-keywords nil)
   1839 (defvar-local org-todo-heads nil)
   1840 (defvar-local org-todo-sets nil)
   1841 (defvar-local org-todo-log-states nil)
   1842 (defvar-local org-todo-kwd-alist nil)
   1843 (defvar-local org-todo-key-alist nil)
   1844 (defvar-local org-todo-key-trigger nil)
   1845 
   1846 (defcustom org-todo-interpretation 'sequence
   1847   "Controls how TODO keywords are interpreted.
   1848 This variable is in principle obsolete and is only used for
   1849 backward compatibility, if the interpretation of todo keywords is
   1850 not given already in `org-todo-keywords'.  See that variable for
   1851 more information."
   1852   :group 'org-todo
   1853   :group 'org-keywords
   1854   :type '(choice (const sequence)
   1855 		 (const type)))
   1856 
   1857 (defcustom org-use-fast-todo-selection 'auto
   1858   "\\<org-mode-map>\
   1859 Non-nil means use the fast todo selection scheme with `\\[org-todo]'.
   1860 This variable describes if and under what circumstances the cycling
   1861 mechanism for TODO keywords will be replaced by a single-key, direct
   1862 selection scheme, where the choices are displayed in a little window.
   1863 
   1864 When nil, fast selection is never used.  This means that the command
   1865 will always switch to the next state.
   1866 
   1867 When it is the symbol `auto', fast selection is whenever selection
   1868 keys have been defined.
   1869 
   1870 `expert' is like `auto', but no special window with the keyword
   1871 will be shown, choices will only be listed in the prompt.
   1872 
   1873 In all cases, the special interface is only used if access keys have
   1874 actually been assigned by the user, i.e. if keywords in the configuration
   1875 are followed by a letter in parenthesis, like TODO(t)."
   1876   :group 'org-todo
   1877   :set (lambda (var val)
   1878 	 (cond
   1879 	  ((eq var t) (set-default-toplevel-value var 'auto))
   1880 	  ((eq var 'prefix) (set-default-toplevel-value var nil))
   1881 	  (t (set-default-toplevel-value var val))))
   1882   :type '(choice
   1883 	  (const :tag "Never" nil)
   1884 	  (const :tag "Automatically, when key letter have been defined" auto)
   1885 	  (const :tag "Automatically, but don't show the selection window" expert)))
   1886 
   1887 (defcustom org-provide-todo-statistics t
   1888   "Non-nil means update todo statistics after insert and toggle.
   1889 ALL-HEADLINES means update todo statistics by including headlines
   1890 with no TODO keyword as well, counting them as not done.
   1891 A list of TODO keywords means the same, but skip keywords that are
   1892 not in this list.
   1893 When set to a list of two lists, the first list contains keywords
   1894 to consider as TODO keywords, the second list contains keywords
   1895 to consider as DONE keywords.
   1896 
   1897 When this is set, todo statistics is updated in the parent of the
   1898 current entry each time a todo state is changed."
   1899   :group 'org-todo
   1900   :type '(choice
   1901 	  (const :tag "Yes, only for TODO entries" t)
   1902 	  (const :tag "Yes, including all entries" all-headlines)
   1903 	  (repeat :tag "Yes, for TODOs in this list"
   1904 		  (string :tag "TODO keyword"))
   1905 	  (list :tag "Yes, for TODOs and DONEs in these lists"
   1906 		(repeat (string :tag "TODO keyword"))
   1907 		(repeat (string :tag "DONE keyword")))
   1908 	  (other :tag "No TODO statistics" nil)))
   1909 
   1910 (defcustom org-hierarchical-todo-statistics t
   1911   "Non-nil means TODO statistics covers just direct children.
   1912 When nil, all entries in the subtree are considered.
   1913 This has only an effect if `org-provide-todo-statistics' is set.
   1914 To set this to nil for only a single subtree, use a COOKIE_DATA
   1915 property and include the word \"recursive\" into the value."
   1916   :group 'org-todo
   1917   :type 'boolean)
   1918 
   1919 (defcustom org-after-todo-state-change-hook nil
   1920   "Hook which is run after the state of a TODO item was changed.
   1921 The new state (a string with a TODO keyword, or nil) is available in the
   1922 Lisp variable `org-state'."
   1923   :group 'org-todo
   1924   :type 'hook)
   1925 
   1926 (defvar org-blocker-hook nil
   1927   "Hook for functions that are allowed to block a state change.
   1928 
   1929 Functions in this hook should not modify the buffer.
   1930 Each function gets as its single argument a property list,
   1931 see `org-trigger-hook' for more information about this list.
   1932 
   1933 If any of the functions in this hook returns nil, the state change
   1934 is blocked.")
   1935 
   1936 (defvar org-trigger-hook nil
   1937   "Hook for functions that are triggered by a state change.
   1938 
   1939 Each function gets as its single argument a property list with at
   1940 least the following elements:
   1941 
   1942  (:type type-of-change :position pos-at-entry-start
   1943   :from old-state :to new-state)
   1944 
   1945 Depending on the type, more properties may be present.
   1946 
   1947 This mechanism is currently implemented for:
   1948 
   1949 TODO state changes
   1950 ------------------
   1951 :type  todo-state-change
   1952 :from  previous state (keyword as a string), or nil, or a symbol
   1953        `todo' or `done', to indicate the general type of state.
   1954 :to    new state, like in :from")
   1955 
   1956 (defcustom org-enforce-todo-dependencies nil
   1957   "Non-nil means undone TODO entries will block switching the parent to DONE.
   1958 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
   1959 be blocked if any prior sibling is not yet done.
   1960 Finally, if the parent is blocked because of ordered siblings of its own,
   1961 the child will also be blocked."
   1962   :set (lambda (var val)
   1963 	 (set-default-toplevel-value var val)
   1964 	 (if val
   1965 	     (add-hook 'org-blocker-hook
   1966 		       'org-block-todo-from-children-or-siblings-or-parent)
   1967 	   (remove-hook 'org-blocker-hook
   1968 			'org-block-todo-from-children-or-siblings-or-parent)))
   1969   :group 'org-todo
   1970   :type 'boolean)
   1971 
   1972 (defcustom org-enforce-todo-checkbox-dependencies nil
   1973   "Non-nil means unchecked boxes will block switching the parent to DONE.
   1974 When this is nil, checkboxes have no influence on switching TODO states.
   1975 When non-nil, you first need to check off all check boxes before the TODO
   1976 entry can be switched to DONE.
   1977 This variable needs to be set before org.el is loaded, and you need to
   1978 restart Emacs after a change to make the change effective.  The only way
   1979 to change it while Emacs is running is through the customize interface."
   1980   :set (lambda (var val)
   1981 	 (set-default-toplevel-value var val)
   1982 	 (if val
   1983 	     (add-hook 'org-blocker-hook
   1984 		       'org-block-todo-from-checkboxes)
   1985 	   (remove-hook 'org-blocker-hook
   1986 			'org-block-todo-from-checkboxes)))
   1987   :group 'org-todo
   1988   :type 'boolean)
   1989 
   1990 (defcustom org-treat-insert-todo-heading-as-state-change nil
   1991   "Non-nil means inserting a TODO heading is treated as state change.
   1992 So when the command `\\[org-insert-todo-heading]' is used, state change
   1993 logging will apply if appropriate.  When nil, the new TODO item will
   1994 be inserted directly, and no logging will take place."
   1995   :group 'org-todo
   1996   :type 'boolean)
   1997 
   1998 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
   1999   "Non-nil means switching TODO states with S-cursor counts as state change.
   2000 This is the default behavior.  However, setting this to nil allows a
   2001 convenient way to select a TODO state and bypass any logging associated
   2002 with that."
   2003   :group 'org-todo
   2004   :type 'boolean)
   2005 
   2006 (defcustom org-todo-state-tags-triggers nil
   2007   "Tag changes that should be triggered by TODO state changes.
   2008 This is a list.  Each entry is
   2009 
   2010   (state-change (tag . flag) .......)
   2011 
   2012 State-change can be a string with a state, and empty string to indicate the
   2013 state that has no TODO keyword, or it can be one of the symbols `todo'
   2014 or `done', meaning any not-done or done state, respectively."
   2015   :group 'org-todo
   2016   :group 'org-tags
   2017   :type '(repeat
   2018 	  (cons (choice :tag "When changing to"
   2019 			(const :tag "Not-done state" todo)
   2020 			(const :tag "Done state" done)
   2021 			(string :tag "State"))
   2022 		(repeat
   2023 		 (cons :tag "Tag action"
   2024 		       (string :tag "Tag")
   2025 		       (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
   2026 
   2027 (defcustom org-log-done nil
   2028   "Information to record when a task moves to the DONE state.
   2029 
   2030 Possible values are:
   2031 
   2032 nil     Don't add anything, just change the keyword
   2033 time    Add a time stamp to the task
   2034 note    Prompt for a note and add it with template `org-log-note-headings'
   2035 
   2036 This option can also be set with on a per-file-basis with
   2037 
   2038    #+STARTUP: nologdone
   2039    #+STARTUP: logdone
   2040    #+STARTUP: lognotedone
   2041 
   2042 You can have local logging settings for a subtree by setting the LOGGING
   2043 property to one or more of these keywords."
   2044   :group 'org-todo
   2045   :group 'org-progress
   2046   :type '(choice
   2047 	  (const :tag "No logging" nil)
   2048 	  (const :tag "Record CLOSED timestamp" time)
   2049 	  (const :tag "Record CLOSED timestamp with note." note)))
   2050 
   2051 ;; Normalize old uses of org-log-done.
   2052 (cond
   2053  ((eq org-log-done t) (setq org-log-done 'time))
   2054  ((and (listp org-log-done) (memq 'done org-log-done))
   2055   (setq org-log-done 'note)))
   2056 
   2057 (defcustom org-log-reschedule nil
   2058   "Information to record when the scheduling date of a task is modified.
   2059 
   2060 Possible values are:
   2061 
   2062 nil     Don't add anything, just change the date
   2063 time    Add a time stamp to the task
   2064 note    Prompt for a note and add it with template `org-log-note-headings'
   2065 
   2066 This option can also be set with on a per-file-basis with
   2067 
   2068    #+STARTUP: nologreschedule
   2069    #+STARTUP: logreschedule
   2070    #+STARTUP: lognotereschedule
   2071 
   2072 You can have local logging settings for a subtree by setting the LOGGING
   2073 property to one or more of these keywords.
   2074 
   2075 This variable has an effect when calling `org-schedule' or
   2076 `org-agenda-schedule' only."
   2077   :group 'org-todo
   2078   :group 'org-progress
   2079   :type '(choice
   2080 	  (const :tag "No logging" nil)
   2081 	  (const :tag "Record timestamp" time)
   2082 	  (const :tag "Record timestamp with note" note)))
   2083 
   2084 (defcustom org-log-redeadline nil
   2085   "Information to record when the deadline date of a task is modified.
   2086 
   2087 Possible values are:
   2088 
   2089 nil     Don't add anything, just change the date
   2090 time    Add a time stamp to the task
   2091 note    Prompt for a note and add it with template `org-log-note-headings'
   2092 
   2093 This option can also be set with on a per-file-basis with
   2094 
   2095    #+STARTUP: nologredeadline
   2096    #+STARTUP: logredeadline
   2097    #+STARTUP: lognoteredeadline
   2098 
   2099 You can have local logging settings for a subtree by setting the LOGGING
   2100 property to one or more of these keywords.
   2101 
   2102 This variable has an effect when calling `org-deadline' or
   2103 `org-agenda-deadline' only."
   2104   :group 'org-todo
   2105   :group 'org-progress
   2106   :type '(choice
   2107 	  (const :tag "No logging" nil)
   2108 	  (const :tag "Record timestamp" time)
   2109 	  (const :tag "Record timestamp with note." note)))
   2110 
   2111 (defcustom org-log-note-clock-out nil
   2112   "Non-nil means record a note when clocking out of an item.
   2113 This can also be configured on a per-file basis by adding one of
   2114 the following lines anywhere in the buffer:
   2115 
   2116    #+STARTUP: lognoteclock-out
   2117    #+STARTUP: nolognoteclock-out"
   2118   :group 'org-todo
   2119   :group 'org-progress
   2120   :type 'boolean)
   2121 
   2122 (defcustom org-log-done-with-time t
   2123   "Non-nil means the CLOSED time stamp will contain date and time.
   2124 When nil, only the date will be recorded."
   2125   :group 'org-progress
   2126   :type 'boolean)
   2127 
   2128 (defcustom org-log-note-headings
   2129   '((done .  "CLOSING NOTE %t")
   2130     (state . "State %-12s from %-12S %t")
   2131     (note .  "Note taken on %t")
   2132     (reschedule .  "Rescheduled from %S on %t")
   2133     (delschedule .  "Not scheduled, was %S on %t")
   2134     (redeadline .  "New deadline from %S on %t")
   2135     (deldeadline .  "Removed deadline, was %S on %t")
   2136     (refile . "Refiled on %t")
   2137     (clock-out . ""))
   2138   "Headings for notes added to entries.
   2139 
   2140 The value is an alist, with the car being a symbol indicating the
   2141 note context, and the cdr is the heading to be used.  The heading
   2142 may also be the empty string.  The following placeholders can be
   2143 used:
   2144 
   2145   %t  a time stamp.
   2146   %T  an active time stamp instead the default inactive one
   2147   %d  a short-format time stamp.
   2148   %D  an active short-format time stamp.
   2149   %s  the new TODO state or time stamp (inactive), in double quotes.
   2150   %S  the old TODO state or time stamp (inactive), in double quotes.
   2151   %u  the user name.
   2152   %U  full user name.
   2153 
   2154 In fact, it is not a good idea to change the `state' entry,
   2155 because Agenda Log mode depends on the format of these entries."
   2156   :group  'org-todo
   2157   :group  'org-progress
   2158   :type '(list :greedy t
   2159 	       (cons (const :tag "Heading when closing an item" done) string)
   2160 	       (cons (const :tag
   2161 			    "Heading when changing todo state (todo sequence only)"
   2162 			    state) string)
   2163 	       (cons (const :tag "Heading when just taking a note" note) string)
   2164 	       (cons (const :tag "Heading when rescheduling" reschedule) string)
   2165 	       (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
   2166 	       (cons (const :tag "Heading when changing deadline"  redeadline) string)
   2167 	       (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
   2168 	       (cons (const :tag "Heading when refiling" refile) string)
   2169 	       (cons (const :tag "Heading when clocking out" clock-out) string)))
   2170 
   2171 (unless (assq 'note org-log-note-headings)
   2172   (push '(note . "%t") org-log-note-headings))
   2173 
   2174 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
   2175 
   2176 (defcustom org-log-into-drawer nil
   2177   "Non-nil means insert state change notes and time stamps into a drawer.
   2178 When nil, state changes notes will be inserted after the headline and
   2179 any scheduling and clock lines, but not inside a drawer.
   2180 
   2181 The value of this variable should be the name of the drawer to use.
   2182 LOGBOOK is proposed as the default drawer for this purpose, you can
   2183 also set this to a string to define the drawer of your choice.
   2184 
   2185 A value of t is also allowed, representing \"LOGBOOK\".
   2186 
   2187 A value of t or nil can also be set with on a per-file-basis with
   2188 
   2189    #+STARTUP: logdrawer
   2190    #+STARTUP: nologdrawer
   2191 
   2192 If this variable is set, `org-log-state-notes-insert-after-drawers'
   2193 will be ignored.
   2194 
   2195 You can set the property LOG_INTO_DRAWER to overrule this setting for
   2196 a subtree.
   2197 
   2198 Do not check directly this variable in a Lisp program.  Call
   2199 function `org-log-into-drawer' instead."
   2200   :group 'org-todo
   2201   :group 'org-progress
   2202   :type '(choice
   2203 	  (const :tag "Not into a drawer" nil)
   2204 	  (const :tag "LOGBOOK" t)
   2205 	  (string :tag "Other")))
   2206 
   2207 (defun org-log-into-drawer ()
   2208   "Name of the log drawer, as a string, or nil.
   2209 This is the value of `org-log-into-drawer'.  However, if the
   2210 current entry has or inherits a LOG_INTO_DRAWER property, it will
   2211 be used instead of the default value."
   2212   (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
   2213     (cond ((equal p "nil") nil)
   2214 	  ((equal p "t") "LOGBOOK")
   2215 	  ((stringp p) p)
   2216 	  (p "LOGBOOK")
   2217 	  ((stringp org-log-into-drawer) org-log-into-drawer)
   2218 	  (org-log-into-drawer "LOGBOOK"))))
   2219 
   2220 (defcustom org-log-state-notes-insert-after-drawers nil
   2221   "Non-nil means insert state change notes after any drawers in entry.
   2222 Only the drawers that *immediately* follow the headline and the
   2223 deadline/scheduled line are skipped.
   2224 When nil, insert notes right after the heading and perhaps the line
   2225 with deadline/scheduling if present.
   2226 
   2227 This variable will have no effect if `org-log-into-drawer' is
   2228 set."
   2229   :group 'org-todo
   2230   :group 'org-progress
   2231   :type 'boolean)
   2232 
   2233 (defcustom org-log-states-order-reversed t
   2234   "Non-nil means the latest state note will be directly after heading.
   2235 When nil, the state change notes will be ordered according to time.
   2236 
   2237 This option can also be set with on a per-file-basis with
   2238 
   2239    #+STARTUP: logstatesreversed
   2240    #+STARTUP: nologstatesreversed"
   2241   :group 'org-todo
   2242   :group 'org-progress
   2243   :type 'boolean)
   2244 
   2245 (defcustom org-todo-repeat-to-state nil
   2246   "The TODO state to which a repeater should return the repeating task.
   2247 By default this is the first task of a TODO sequence or the
   2248 previous state of a TYPE_TODO set.  But you can specify to use
   2249 the previous state in a TODO sequence or a string.
   2250 
   2251 Alternatively, you can set the :REPEAT_TO_STATE: property of the
   2252 entry, which has precedence over this option."
   2253   :group 'org-todo
   2254   :version "24.1"
   2255   :type '(choice (const :tag "Use the previous TODO state" t)
   2256 		 (const :tag "Use the head of the TODO sequence" nil)
   2257 		 (string :tag "Use a specific TODO state")))
   2258 
   2259 (defcustom org-log-repeat 'time
   2260   "Non-nil means record moving through the DONE state when triggering repeat.
   2261 An auto-repeating task is immediately switched back to TODO when
   2262 marked DONE.  If you are not logging state changes (by adding \"@\"
   2263 or \"!\" to the TODO keyword definition), or set `org-log-done' to
   2264 record a closing note, there will be no record of the task moving
   2265 through DONE.  This variable forces taking a note anyway.
   2266 
   2267 nil     Don't force a record
   2268 time    Record a time stamp
   2269 note    Prompt for a note and add it with template `org-log-note-headings'
   2270 
   2271 This option can also be set with on a per-file-basis with
   2272 
   2273    #+STARTUP: nologrepeat
   2274    #+STARTUP: logrepeat
   2275    #+STARTUP: lognoterepeat
   2276 
   2277 You can have local logging settings for a subtree by setting the LOGGING
   2278 property to one or more of these keywords."
   2279   :group 'org-todo
   2280   :group 'org-progress
   2281   :type '(choice
   2282 	  (const :tag "Don't force a record" nil)
   2283 	  (const :tag "Force recording the DONE state" time)
   2284 	  (const :tag "Force recording a note with the DONE state" note)))
   2285 
   2286 (defcustom org-todo-repeat-hook nil
   2287   "Hook that is run after a task has been repeated."
   2288   :package-version '(Org . "9.2")
   2289   :group 'org-todo
   2290   :type 'hook)
   2291 
   2292 (defgroup org-priorities nil
   2293   "Priorities in Org mode."
   2294   :tag "Org Priorities"
   2295   :group 'org-todo)
   2296 
   2297 (defvaralias 'org-enable-priority-commands 'org-priority-enable-commands)
   2298 (defcustom org-priority-enable-commands t
   2299   "Non-nil means priority commands are active.
   2300 When nil, these commands will be disabled, so that you never accidentally
   2301 set a priority."
   2302   :group 'org-priorities
   2303   :type 'boolean)
   2304 
   2305 (defvaralias 'org-highest-priority 'org-priority-highest)
   2306 
   2307 (defcustom org-priority-highest ?A
   2308   "The highest priority of TODO items.
   2309 
   2310 A character like ?A, ?B, etc., or a numeric value like 1, 2, etc.
   2311 
   2312 The default is the character ?A, which is 65 as a numeric value.
   2313 
   2314 If you set `org-priority-highest' to a numeric value inferior to
   2315 65, Org assumes you want to use digits for the priority cookie.
   2316 If you set it to >=65, Org assumes you want to use alphabetical
   2317 characters.
   2318 
   2319 In both cases, the value of `org-priority-highest' must be
   2320 smaller than `org-priority-lowest': for example, if \"A\" is the
   2321 highest priority, it is smaller than the lowest \"C\" priority:
   2322 65 < 67."
   2323   :group 'org-priorities
   2324   :type '(choice
   2325 	  (character :tag "Character")
   2326 	  (integer :tag "Integer (< 65)")))
   2327 
   2328 (defvaralias 'org-lowest-priority 'org-priority-lowest)
   2329 (defcustom org-priority-lowest ?C
   2330   "The lowest priority of TODO items.
   2331 
   2332 A character like ?C, ?B, etc., or a numeric value like 9, 8, etc.
   2333 
   2334 The default is the character ?C, which is 67 as a numeric value.
   2335 
   2336 If you set `org-priority-lowest' to a numeric value inferior to
   2337 65, Org assumes you want to use digits for the priority cookie.
   2338 If you set it to >=65, Org assumes you want to use alphabetical
   2339 characters.
   2340 
   2341 In both cases, the value of `org-priority-lowest' must be greater
   2342 than `org-priority-highest': for example, if \"C\" is the lowest
   2343 priority, it is greater than the highest \"A\" priority: 67 >
   2344 65."
   2345   :group 'org-priorities
   2346   :type '(choice
   2347 	  (character :tag "Character")
   2348 	  (integer :tag "Integer (< 65)")))
   2349 
   2350 (defvaralias 'org-default-priority 'org-priority-default)
   2351 (defcustom org-priority-default ?B
   2352   "The default priority of TODO items.
   2353 This is the priority an item gets if no explicit priority is given.
   2354 When starting to cycle on an empty priority the first step in the cycle
   2355 depends on `org-priority-start-cycle-with-default'.  The resulting first
   2356 step priority must not exceed the range from `org-priority-highest' to
   2357 `org-priority-lowest' which means that `org-priority-default' has to be
   2358 in this range exclusive or inclusive to the range boundaries.  Else the
   2359 first step refuses to set the default and the second will fall back on
   2360 \(depending on the command used) the highest or lowest priority."
   2361   :group 'org-priorities
   2362   :type '(choice
   2363 	  (character :tag "Character")
   2364 	  (integer :tag "Integer (< 65)")))
   2365 
   2366 (defcustom org-priority-start-cycle-with-default t
   2367   "Non-nil means start with default priority when starting to cycle.
   2368 When this is nil, the first step in the cycle will be (depending on the
   2369 command used) one higher or lower than the default priority.
   2370 See also `org-priority-default'."
   2371   :group 'org-priorities
   2372   :type 'boolean)
   2373 
   2374 (defvaralias 'org-get-priority-function 'org-priority-get-priority-function)
   2375 (defcustom org-priority-get-priority-function nil
   2376   "Function to extract the priority from a string.
   2377 The string is normally the headline.  If this is nil, Org
   2378 computes the priority from the priority cookie like [#A] in the
   2379 headline.  It returns an integer, increasing by 1000 for each
   2380 priority level.
   2381 
   2382 The user can set a different function here, which should take a
   2383 string as an argument and return the numeric priority."
   2384   :group 'org-priorities
   2385   :version "24.1"
   2386   :type '(choice
   2387 	  (const nil)
   2388 	  (function)))
   2389 
   2390 (defgroup org-time nil
   2391   "Options concerning time stamps and deadlines in Org mode."
   2392   :tag "Org Time"
   2393   :group 'org)
   2394 
   2395 (defcustom org-time-stamp-rounding-minutes '(0 5)
   2396   "Number of minutes to round time stamps to.
   2397 \\<org-mode-map>\
   2398 These are two values, the first applies when first creating a time stamp.
   2399 The second applies when changing it with the commands `S-up' and `S-down'.
   2400 When changing the time stamp, this means that it will change in steps
   2401 of N minutes, as given by the second value.
   2402 
   2403 When a setting is 0 or 1, insert the time unmodified.  Useful rounding
   2404 numbers should be factors of 60, so for example 5, 10, 15.
   2405 
   2406 When this is larger than 1, you can still force an exact time stamp by using
   2407 a double prefix argument to a time stamp command like \
   2408 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
   2409 and by using a prefix arg to `S-up/down' to specify the exact number
   2410 of minutes to shift."
   2411   :group 'org-time
   2412   :get (lambda (var) ; Make sure both elements are there
   2413 	 (if (integerp (default-value var))
   2414 	     (list (default-value var) 5)
   2415 	   (default-value var)))
   2416   :type '(list
   2417 	  (integer :tag "when inserting times")
   2418 	  (integer :tag "when modifying times")))
   2419 
   2420 ;; Normalize old customizations of this variable.
   2421 (when (integerp org-time-stamp-rounding-minutes)
   2422   (setq org-time-stamp-rounding-minutes
   2423 	(list org-time-stamp-rounding-minutes
   2424 	      org-time-stamp-rounding-minutes)))
   2425 
   2426 (defcustom org-display-custom-times nil
   2427   "Non-nil means overlay custom formats over all time stamps.
   2428 The formats are defined through the variable `org-time-stamp-custom-formats'.
   2429 To turn this on on a per-file basis, insert anywhere in the file:
   2430    #+STARTUP: customtime"
   2431   :group 'org-time
   2432   :type 'sexp)
   2433 (make-variable-buffer-local 'org-display-custom-times)
   2434 
   2435 (defcustom org-time-stamp-custom-formats
   2436   '("%m/%d/%y %a" . "%m/%d/%y %a %H:%M") ; american
   2437   "Custom formats for time stamps.
   2438 
   2439 See `format-time-string' for the syntax.
   2440 
   2441 These are overlaid over the default ISO format if the variable
   2442 `org-display-custom-times' is set.  Time like %H:%M should be at the
   2443 end of the second format.  The custom formats are also honored by export
   2444 commands, if custom time display is turned on at the time of export.
   2445 
   2446 Leading \"<\" and trailing \">\" pair will be stripped from the format
   2447 strings."
   2448   :group 'org-time
   2449   :package-version '(Org . "9.6")
   2450   :type '(cons string string))
   2451 
   2452 (defun org-time-stamp-format (&optional with-time inactive custom)
   2453   "Get timestamp format for a time string.
   2454 
   2455 The format is based on `org-time-stamp-formats' (if CUSTOM is nil) or or
   2456 `org-time-stamp-custom-formats' (if CUSTOM if non-nil).
   2457 
   2458 When optional argument WITH-TIME is non-nil, the timestamp will contain
   2459 time.
   2460 
   2461 When optional argument INACTIVE is nil, format active timestamp.
   2462 When `no-brackets', strip timestamp brackets.
   2463 Otherwise, format inactive timestamp."
   2464   (let ((format (funcall
   2465                  (if with-time #'cdr #'car)
   2466                  (if custom
   2467                      org-time-stamp-custom-formats
   2468                    org-time-stamp-formats))))
   2469     ;; Strip brackets, if any.
   2470     (when (or (and (string-prefix-p "<" format)
   2471                    (string-suffix-p ">" format))
   2472               (and (string-prefix-p "[" format)
   2473                    (string-suffix-p "]" format)))
   2474       (setq format (substring format 1 -1)))
   2475     (pcase inactive
   2476       (`no-brackets format)
   2477       (`nil (concat "<" format ">"))
   2478       (_ (concat "[" format "]")))))
   2479 
   2480 (defcustom org-deadline-warning-days 14
   2481   "Number of days before expiration during which a deadline becomes active.
   2482 This variable governs the display in sparse trees and in the agenda.
   2483 When 0 or negative, it means use this number (the absolute value of it)
   2484 even if a deadline has a different individual lead time specified.
   2485 
   2486 Custom commands can set this variable in the options section."
   2487   :group 'org-time
   2488   :group 'org-agenda-daily/weekly
   2489   :type 'integer)
   2490 
   2491 (defcustom org-scheduled-delay-days 0
   2492   "Number of days before a scheduled item becomes active.
   2493 This variable governs the display in sparse trees and in the agenda.
   2494 The default value (i.e. 0) means: don't delay scheduled item.
   2495 When negative, it means use this number (the absolute value of it)
   2496 even if a scheduled item has a different individual delay time
   2497 specified.
   2498 
   2499 Custom commands can set this variable in the options section."
   2500   :group 'org-time
   2501   :group 'org-agenda-daily/weekly
   2502   :version "24.4"
   2503   :package-version '(Org . "8.0")
   2504   :type 'integer)
   2505 
   2506 (defcustom org-read-date-prefer-future t
   2507   "Non-nil means assume future for incomplete date input from user.
   2508 This affects the following situations:
   2509 1. The user gives a month but not a year.
   2510    For example, if it is April and you enter \"feb 2\", this will be read
   2511    as Feb 2, *next* year.  \"May 5\", however, will be this year.
   2512 2. The user gives a day, but no month.
   2513    For example, if today is the 15th, and you enter \"3\", Org will read
   2514    this as the third of *next* month.  However, if you enter \"17\",
   2515    it will be considered as *this* month.
   2516 
   2517 If you set this variable to the symbol `time', then also the following
   2518 will work:
   2519 
   2520 3. If the user gives a time.
   2521    If the time is before now, it will be interpreted as tomorrow.
   2522 
   2523 Currently none of this works for ISO week specifications.
   2524 
   2525 When this option is nil, the current day, month and year will always be
   2526 used as defaults.
   2527 
   2528 See also `org-agenda-jump-prefer-future'."
   2529   :group 'org-time
   2530   :type '(choice
   2531 	  (const :tag "Never" nil)
   2532 	  (const :tag "Check month and day" t)
   2533 	  (const :tag "Check month, day, and time" time)))
   2534 
   2535 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
   2536   "Should the agenda jump command prefer the future for incomplete dates?
   2537 The default is to do the same as configured in `org-read-date-prefer-future'.
   2538 But you can also set a deviating value here.
   2539 This may t or nil, or the symbol `org-read-date-prefer-future'."
   2540   :group 'org-agenda
   2541   :group 'org-time
   2542   :version "24.1"
   2543   :type '(choice
   2544 	  (const :tag "Use org-read-date-prefer-future"
   2545 		 org-read-date-prefer-future)
   2546 	  (const :tag "Never" nil)
   2547 	  (const :tag "Always" t)))
   2548 
   2549 (defcustom org-read-date-force-compatible-dates t
   2550   "Should date/time prompt force dates that are guaranteed to work in Emacs?
   2551 
   2552 Depending on the system Emacs is running on, certain dates cannot
   2553 be represented with the type used internally to represent time.
   2554 Dates between 1970-1-1 and 2038-1-1 can always be represented
   2555 correctly.  Some systems allow for earlier dates, some for later,
   2556 some for both.  One way to find out is to insert any date into an
   2557 Org buffer, putting the cursor on the year and hitting S-up and
   2558 S-down to test the range.
   2559 
   2560 When this variable is set to t, the date/time prompt will not let
   2561 you specify dates outside the 1970-2037 range, so it is certain that
   2562 these dates will work in whatever version of Emacs you are
   2563 running, and also that you can move a file from one Emacs implementation
   2564 to another.  Whenever Org is forcing the year for you, it will display
   2565 a message and beep.
   2566 
   2567 When this variable is nil, Org will check if the date is
   2568 representable in the specific Emacs implementation you are using.
   2569 If not, it will force a year, usually the current year, and beep
   2570 to remind you.  Currently this setting is not recommended because
   2571 the likelihood that you will open your Org files in an Emacs that
   2572 has limited date range is not negligible.
   2573 
   2574 A workaround for this problem is to use diary sexp dates for time
   2575 stamps outside of this range."
   2576   :group 'org-time
   2577   :version "24.1"
   2578   :type 'boolean)
   2579 
   2580 (defcustom org-read-date-display-live t
   2581   "Non-nil means display current interpretation of date prompt live.
   2582 This display will be in an overlay, in the minibuffer.  Note that
   2583 live display is only active when `org-read-date-popup-calendar'
   2584 is non-nil."
   2585   :group 'org-time
   2586   :type 'boolean)
   2587 
   2588 (defvaralias 'org-popup-calendar-for-date-prompt
   2589   'org-read-date-popup-calendar)
   2590 
   2591 (defcustom org-read-date-popup-calendar t
   2592   "Non-nil means pop up a calendar when prompting for a date.
   2593 In the calendar, the date can be selected with mouse-1.  However, the
   2594 minibuffer will also be active, and you can simply enter the date as well.
   2595 When nil, only the minibuffer will be available."
   2596   :group 'org-time
   2597   :type 'boolean)
   2598 
   2599 (defcustom org-extend-today-until 0
   2600   "The hour when your day really ends.  Must be an integer.
   2601 This has influence for the following applications:
   2602 - When switching the agenda to \"today\".  If it is still earlier than
   2603   the time given here, the day recognized as TODAY is actually yesterday.
   2604 - When a date is read from the user and it is still before the time given
   2605   here, the current date and time will be assumed to be yesterday, 23:59.
   2606   Also, timestamps inserted in capture templates follow this rule.
   2607 
   2608 IMPORTANT:  This is a feature whose implementation is and likely will
   2609 remain incomplete.  Really, it is only here because past midnight seems to
   2610 be the favorite working time of John Wiegley :-)"
   2611   :group 'org-time
   2612   :type 'integer)
   2613 
   2614 (defcustom org-use-effective-time nil
   2615   "If non-nil, consider `org-extend-today-until' when creating timestamps.
   2616 For example, if `org-extend-today-until' is 8, and it's 4am, then the
   2617 \"effective time\" of any timestamps between midnight and 8am will be
   2618 23:59 of the previous day."
   2619   :group 'org-time
   2620   :version "24.1"
   2621   :type 'boolean)
   2622 
   2623 (defcustom org-use-last-clock-out-time-as-effective-time nil
   2624   "When non-nil, use the last clock out time for `org-todo'.
   2625 Note that this option has precedence over the combined use of
   2626 `org-use-effective-time' and `org-extend-today-until'."
   2627   :group 'org-time
   2628   :version "24.4"
   2629   :package-version '(Org . "8.0")
   2630   :type 'boolean)
   2631 
   2632 (defcustom org-edit-timestamp-down-means-later nil
   2633   "Non-nil means S-down will increase the time in a time stamp.
   2634 When nil, S-up will increase."
   2635   :group 'org-time
   2636   :type 'boolean)
   2637 
   2638 (defcustom org-calendar-follow-timestamp-change t
   2639   "Non-nil means make the calendar window follow timestamp changes.
   2640 When a timestamp is modified and the calendar window is visible, it will be
   2641 moved to the new date."
   2642   :group 'org-time
   2643   :type 'boolean)
   2644 
   2645 (defgroup org-tags nil
   2646   "Options concerning tags in Org mode."
   2647   :tag "Org Tags"
   2648   :group 'org)
   2649 
   2650 (defcustom org-tag-alist nil
   2651   "Default tags available in Org files.
   2652 
   2653 The value of this variable is an alist.  Associations either:
   2654 
   2655   (TAG)
   2656   (TAG . SELECT)
   2657   (SPECIAL)
   2658 
   2659 where TAG is a tag as a string, SELECT is character, used to
   2660 select that tag through the fast tag selection interface, and
   2661 SPECIAL is one of the following keywords: `:startgroup',
   2662 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
   2663 `:newline'.  These keywords are used to define a hierarchy of
   2664 tags.  See manual for details.
   2665 
   2666 When this variable is nil, Org mode bases tag input on what is
   2667 already in the buffer.  The value can be overridden locally by
   2668 using a TAGS keyword, e.g.,
   2669 
   2670   #+TAGS: tag1 tag2
   2671 
   2672 See also `org-tag-persistent-alist' to sidestep this behavior."
   2673   :group 'org-tags
   2674   :type '(repeat
   2675 	  (choice
   2676 	   (cons :tag "Tag with key"
   2677 		 (string    :tag "Tag name")
   2678 		 (character :tag "Access char"))
   2679 	   (list :tag "Tag" (string :tag "Tag name"))
   2680 	   (const :tag "Start radio group" (:startgroup))
   2681 	   (const :tag "Start tag group, non distinct" (:startgrouptag))
   2682 	   (const :tag "Group tags delimiter" (:grouptags))
   2683 	   (const :tag "End radio group" (:endgroup))
   2684 	   (const :tag "End tag group, non distinct" (:endgrouptag))
   2685 	   (const :tag "New line" (:newline)))))
   2686 
   2687 (defcustom org-tag-persistent-alist nil
   2688   "Tags always available in Org files.
   2689 
   2690 The value of this variable is an alist.  Associations either:
   2691 
   2692   (TAG)
   2693   (TAG . SELECT)
   2694   (SPECIAL)
   2695 
   2696 where TAG is a tag as a string, SELECT is a character, used to
   2697 select that tag through the fast tag selection interface, and
   2698 SPECIAL is one of the following keywords: `:startgroup',
   2699 `:startgrouptag', `:grouptags', `:endgroup', `:endgrouptag' or
   2700 `:newline'.  These keywords are used to define a hierarchy of
   2701 tags.  See manual for details.
   2702 
   2703 Unlike to `org-tag-alist', tags defined in this variable do not
   2704 depend on a local TAGS keyword.  Instead, to disable these tags
   2705 on a per-file basis, insert anywhere in the file:
   2706 
   2707   #+STARTUP: noptag"
   2708   :group 'org-tags
   2709   :type '(repeat
   2710 	  (choice
   2711 	   (cons :tag "Tag with key"
   2712 		 (string    :tag "Tag name")
   2713 		 (character :tag "Access char"))
   2714 	   (list :tag "Tag" (string :tag "Tag name"))
   2715 	   (const :tag "Start radio group" (:startgroup))
   2716 	   (const :tag "Start tag group, non distinct" (:startgrouptag))
   2717 	   (const :tag "Group tags delimiter" (:grouptags))
   2718 	   (const :tag "End radio group" (:endgroup))
   2719 	   (const :tag "End tag group, non distinct" (:endgrouptag))
   2720 	   (const :tag "New line" (:newline)))))
   2721 
   2722 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
   2723   "If non-nil, always offer completion for all tags of all agenda files.
   2724 
   2725 Setting this variable locally allows for dynamic generation of tag
   2726 completions in capture buffers.
   2727 
   2728   (add-hook \\='org-capture-mode-hook
   2729             (lambda ()
   2730               (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
   2731   :group 'org-tags
   2732   :version "24.1"
   2733   :type 'boolean)
   2734 
   2735 (defvar org-file-tags nil
   2736   "List of tags that can be inherited by all entries in the file.
   2737 The tags will be inherited if the variable `org-use-tag-inheritance'
   2738 says they should be.
   2739 This variable is populated from #+FILETAGS lines.")
   2740 
   2741 (defcustom org-use-fast-tag-selection 'auto
   2742   "Non-nil means use fast tag selection scheme.
   2743 This is a special interface to select and deselect tags with single keys.
   2744 When nil, fast selection is never used.
   2745 When the symbol `auto', fast selection is used if and only if selection
   2746 characters for tags have been configured, either through the variable
   2747 `org-tag-alist' or through a #+TAGS line in the buffer.
   2748 When t, fast selection is always used and selection keys are assigned
   2749 automatically if necessary."
   2750   :group 'org-tags
   2751   :type '(choice
   2752 	  (const :tag "Always" t)
   2753 	  (const :tag "Never" nil)
   2754 	  (const :tag "When selection characters are configured" auto)))
   2755 
   2756 (defcustom org-fast-tag-selection-single-key nil
   2757   "Non-nil means fast tag selection exits after first change.
   2758 When nil, you have to press RET to exit it.
   2759 During fast tag selection, you can toggle this flag with `C-c'.
   2760 This variable can also have the value `expert'.  In this case, the window
   2761 displaying the tags menu is not even shown, until you press `C-c' again."
   2762   :group 'org-tags
   2763   :type '(choice
   2764 	  (const :tag "No" nil)
   2765 	  (const :tag "Yes" t)
   2766 	  (const :tag "Expert" expert)))
   2767 
   2768 (defvar org-fast-tag-selection-include-todo nil
   2769   "Non-nil means fast tags selection interface will also offer TODO states.
   2770 This is an undocumented feature, you should not rely on it.")
   2771 
   2772 (defcustom org-tags-column -77
   2773   "The column to which tags should be indented in a headline.
   2774 If this number is positive, it specifies the column.  If it is negative,
   2775 it means that the tags should be flushright to that column.  For example,
   2776 -80 works well for a normal 80 character screen.
   2777 When 0, place tags directly after headline text, with only one space in
   2778 between."
   2779   :group 'org-tags
   2780   :type 'integer)
   2781 
   2782 (defcustom org-auto-align-tags t
   2783   "Non-nil keeps tags aligned when modifying headlines.
   2784 Some operations (i.e. demoting) change the length of a headline and
   2785 therefore shift the tags around.  With this option turned on, after
   2786 each such operation the tags are again aligned to `org-tags-column'."
   2787   :group 'org-tags
   2788   :type 'boolean)
   2789 
   2790 (defcustom org-use-tag-inheritance t
   2791   "Non-nil means tags in levels apply also for sublevels.
   2792 When nil, only the tags directly given in a specific line apply there.
   2793 This may also be a list of tags that should be inherited, or a regexp that
   2794 matches tags that should be inherited.  Additional control is possible
   2795 with the variable  `org-tags-exclude-from-inheritance' which gives an
   2796 explicit list of tags to be excluded from inheritance, even if the value of
   2797 `org-use-tag-inheritance' would select it for inheritance.
   2798 
   2799 If this option is t, a match early-on in a tree can lead to a large
   2800 number of matches in the subtree when constructing the agenda or creating
   2801 a sparse tree.  If you only want to see the first match in a tree during
   2802 a search, check out the variable `org-tags-match-list-sublevels'."
   2803   :group 'org-tags
   2804   :type '(choice
   2805 	  (const :tag "Not" nil)
   2806 	  (const :tag "Always" t)
   2807 	  (repeat :tag "Specific tags" (string :tag "Tag"))
   2808 	  (regexp :tag "Tags matched by regexp")))
   2809 
   2810 (defcustom org-tags-exclude-from-inheritance nil
   2811   "List of tags that should never be inherited.
   2812 This is a way to exclude a few tags from inheritance.  For way to do
   2813 the opposite, to actively allow inheritance for selected tags,
   2814 see the variable `org-use-tag-inheritance'."
   2815   :group 'org-tags
   2816   :type '(repeat (string :tag "Tag")))
   2817 
   2818 (defun org-tag-inherit-p (tag)
   2819   "Check if TAG is one that should be inherited."
   2820   (cond
   2821    ((member tag org-tags-exclude-from-inheritance) nil)
   2822    ((eq org-use-tag-inheritance t) t)
   2823    ((not org-use-tag-inheritance) nil)
   2824    ((stringp org-use-tag-inheritance)
   2825     (string-match org-use-tag-inheritance tag))
   2826    ((listp org-use-tag-inheritance)
   2827     (member tag org-use-tag-inheritance))
   2828    (t (error "Invalid setting of `org-use-tag-inheritance'"))))
   2829 
   2830 (defcustom org-tags-match-list-sublevels t
   2831   "Non-nil means list also sublevels of headlines matching a search.
   2832 This variable applies to tags/property searches, and also to stuck
   2833 projects because this search is based on a tags match as well.
   2834 
   2835 When set to the symbol `indented', sublevels are indented with
   2836 leading dots.
   2837 
   2838 Because of tag inheritance (see variable `org-use-tag-inheritance'),
   2839 the sublevels of a headline matching a tag search often also match
   2840 the same search.  Listing all of them can create very long lists.
   2841 Setting this variable to nil causes subtrees of a match to be skipped.
   2842 
   2843 This variable is semi-obsolete and probably should always be true.  It
   2844 is better to limit inheritance to certain tags using the variables
   2845 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
   2846   :group 'org-tags
   2847   :type '(choice
   2848 	  (const :tag "No, don't list them" nil)
   2849 	  (const :tag "Yes, do list them" t)
   2850 	  (const :tag "List them, indented with leading dots" indented)))
   2851 
   2852 (defcustom org-tags-sort-function nil
   2853   "When set, tags are sorted using this function as a comparator."
   2854   :group 'org-tags
   2855   :type '(choice
   2856 	  (const :tag "No sorting" nil)
   2857 	  (const :tag "Alphabetical" string-collate-lessp)
   2858 	  (const :tag "Reverse alphabetical" org-string-collate-greaterp)
   2859 	  (function :tag "Custom function" nil)))
   2860 
   2861 (defvar org-tags-history nil
   2862   "History of minibuffer reads for tags.")
   2863 (defvar org-last-tags-completion-table nil
   2864   "The last used completion table for tags.")
   2865 (defvar org-after-tags-change-hook nil
   2866   "Hook that is run after the tags in a line have changed.")
   2867 
   2868 (defgroup org-properties nil
   2869   "Options concerning properties in Org mode."
   2870   :tag "Org Properties"
   2871   :group 'org)
   2872 
   2873 (defcustom org-property-format "%-10s %s"
   2874   "How property key/value pairs should be formatted by `indent-line'.
   2875 When `indent-line' hits a property definition, it will format the line
   2876 according to this format, mainly to make sure that the values are
   2877 lined-up with respect to each other."
   2878   :group 'org-properties
   2879   :type 'string)
   2880 
   2881 (defcustom org-properties-postprocess-alist nil
   2882   "Alist of properties and functions to adjust inserted values.
   2883 Elements of this alist must be of the form
   2884 
   2885   ([string] [function])
   2886 
   2887 where [string] must be a property name and [function] must be a
   2888 lambda expression: this lambda expression must take one argument,
   2889 the value to adjust, and return the new value as a string.
   2890 
   2891 For example, this element will allow the property \"Remaining\"
   2892 to be updated wrt the relation between the \"Effort\" property
   2893 and the clock summary:
   2894 
   2895  ((\"Remaining\" (lambda(value)
   2896                    (let ((clocksum (org-clock-sum-current-item))
   2897                          (effort (org-duration-to-minutes
   2898                                    (org-entry-get (point) \"Effort\"))))
   2899                      (org-minutes-to-clocksum-string (- effort clocksum))))))"
   2900   :group 'org-properties
   2901   :version "24.1"
   2902   :type '(alist :key-type (string     :tag "Property")
   2903 		:value-type (function :tag "Function")))
   2904 
   2905 (defcustom org-use-property-inheritance nil
   2906   "Non-nil means properties apply also for sublevels.
   2907 
   2908 This setting is chiefly used during property searches.  Turning it on can
   2909 cause significant overhead when doing a search, which is why it is not
   2910 on by default.
   2911 
   2912 When nil, only the properties directly given in the current entry count.
   2913 When t, every property is inherited.  The value may also be a list of
   2914 properties that should have inheritance, or a regular expression matching
   2915 properties that should be inherited.
   2916 
   2917 However, note that some special properties use inheritance under special
   2918 circumstances (not in searches).  Examples are CATEGORY, ARCHIVE, COLUMNS,
   2919 and the properties ending in \"_ALL\" when they are used as descriptor
   2920 for valid values of a property.
   2921 
   2922 Note for programmers:
   2923 When querying an entry with `org-entry-get', you can control if inheritance
   2924 should be used.  By default, `org-entry-get' looks only at the local
   2925 properties.  You can request inheritance by setting the inherit argument
   2926 to t (to force inheritance) or to `selective' (to respect the setting
   2927 in this variable)."
   2928   :group 'org-properties
   2929   :type '(choice
   2930 	  (const :tag "Not" nil)
   2931 	  (const :tag "Always" t)
   2932 	  (repeat :tag "Specific properties" (string :tag "Property"))
   2933 	  (regexp :tag "Properties matched by regexp")))
   2934 
   2935 (defun org-property-inherit-p (property)
   2936   "Return a non-nil value if PROPERTY should be inherited."
   2937   (cond
   2938    ((eq org-use-property-inheritance t) t)
   2939    ((not org-use-property-inheritance) nil)
   2940    ((stringp org-use-property-inheritance)
   2941     (string-match org-use-property-inheritance property))
   2942    ((listp org-use-property-inheritance)
   2943     (member-ignore-case property org-use-property-inheritance))
   2944    (t (error "Invalid setting of `org-use-property-inheritance'"))))
   2945 
   2946 (defcustom org-property-separators nil
   2947   "An alist to control how properties are combined.
   2948 
   2949 The car of each item should be either a list of property names or
   2950 a regular expression, while the cdr should be the separator to
   2951 use when combining that property.
   2952 
   2953 If an alist item cannot be found that matches a given property, a
   2954 single space will be used as the separator."
   2955   :group 'org-properties
   2956   :package-version '(Org . "9.6")
   2957   :type '(alist :key-type (choice (repeat :tag "Properties" string)
   2958                                   (string :tag "Regular Expression"))
   2959                 :value-type (restricted-sexp :tag "Separator"
   2960                                              :match-alternatives (stringp)
   2961                                              :value " ")))
   2962 
   2963 (defun org--property-get-separator (property)
   2964   "Get the separator to use for combining PROPERTY."
   2965   (or
   2966    (catch 'separator
   2967      (dolist (spec org-property-separators)
   2968        (if (listp (car spec))
   2969            (if (member property (car spec))
   2970                (throw 'separator (cdr spec)))
   2971          (if (string-match-p (car spec) property)
   2972              (throw 'separator (cdr spec))))))
   2973    " "))
   2974 
   2975 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
   2976   "The default column format, if no other format has been defined.
   2977 This variable can be set on the per-file basis by inserting a line
   2978 
   2979 #+COLUMNS: %25ITEM ....."
   2980   :group 'org-properties
   2981   :type 'string)
   2982 
   2983 (defcustom org-columns-default-format-for-agenda nil
   2984   "The default column format in an agenda buffer.
   2985 This will be used for column view in the agenda unless a format has
   2986 been set by adding `org-overriding-columns-format' to the local
   2987 settings list of a custom agenda view.  When nil, the columns format
   2988 for the first item in the agenda list will be used, or as a fall-back,
   2989 `org-columns-default-format'."
   2990   :group 'org-properties
   2991   :type '(choice
   2992 	  (const :tag "No default" nil)
   2993 	  (string :tag "Format string")))
   2994 
   2995 (defcustom org-columns-ellipses ".."
   2996   "The ellipses to be used when a field in column view is truncated.
   2997 When this is the empty string, as many characters as possible are shown,
   2998 but then there will be no visual indication that the field has been truncated.
   2999 When this is a string of length N, the last N characters of a truncated
   3000 field are replaced by this string.  If the column is narrower than the
   3001 ellipses string, only part of the ellipses string will be shown."
   3002   :group 'org-properties
   3003   :type 'string)
   3004 
   3005 (defconst org-global-properties-fixed
   3006   '(("VISIBILITY_ALL" . "folded children content all")
   3007     ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
   3008   "List of property/value pairs that can be inherited by any entry.
   3009 
   3010 These are fixed values, for the preset properties.  The user variable
   3011 that can be used to add to this list is `org-global-properties'.
   3012 
   3013 The entries in this list are cons cells where the car is a property
   3014 name and cdr is a string with the value.  If the value represents
   3015 multiple items like an \"_ALL\" property, separate the items by
   3016 spaces.")
   3017 
   3018 (defcustom org-global-properties nil
   3019   "List of property/value pairs that can be inherited by any entry.
   3020 
   3021 This list will be combined with the constant `org-global-properties-fixed'.
   3022 
   3023 The entries in this list are cons cells where the car is a property
   3024 name and cdr is a string with the value.
   3025 
   3026 Buffer local properties are added either by a document property drawer
   3027 
   3028 :PROPERTIES:
   3029 :NAME: VALUE
   3030 :END:
   3031 
   3032 or by adding lines like
   3033 
   3034 #+PROPERTY: NAME VALUE"
   3035   :group 'org-properties
   3036   :type '(repeat
   3037 	  (cons (string :tag "Property")
   3038 		(string :tag "Value"))))
   3039 
   3040 (defvar-local org-keyword-properties nil
   3041   "List of property/value pairs inherited by any entry.
   3042 
   3043 Valid for the current buffer.  This variable is populated from
   3044 PROPERTY keywords.
   3045 
   3046 Note that properties are defined also in property drawers.
   3047 Properties defined there take precedence over properties defined
   3048 as keywords.")
   3049 
   3050 (defgroup org-agenda nil
   3051   "Options concerning agenda views in Org mode."
   3052   :tag "Org Agenda"
   3053   :group 'org)
   3054 
   3055 (defvar-local org-category nil
   3056   "Variable used by Org files to set a category for agenda display.
   3057 There are multiple ways to set the category.  One way is to set
   3058 it in the document property drawer.  For example:
   3059 
   3060 :PROPERTIES:
   3061 :CATEGORY: ELisp
   3062 :END:
   3063 
   3064 Other ways to define it is as an Emacs file variable, for example
   3065 
   3066 #   -*- mode: org; org-category: \"ELisp\"
   3067 
   3068 or for the file to contain a special line:
   3069 
   3070 #+CATEGORY: ELisp
   3071 
   3072 If the file does not specify a category, then file's base name
   3073 is used instead.")
   3074 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
   3075 
   3076 (defcustom org-agenda-files nil
   3077   "The files to be used for agenda display.
   3078 
   3079 If an entry is a directory, all files in that directory that are matched
   3080 by `org-agenda-file-regexp' will be part of the file list.
   3081 
   3082 If the value of the variable is not a list but a single file name, then
   3083 the list of agenda files is actually stored and maintained in that file,
   3084 one agenda file per line.  In this file paths can be given relative to
   3085 `org-directory'.  Tilde expansion and environment variable substitution
   3086 are also made.
   3087 
   3088 Entries may be added to this list with `\\[org-agenda-file-to-front]'
   3089 and removed with `\\[org-remove-file]'."
   3090   :group 'org-agenda
   3091   :type '(choice
   3092 	  (repeat :tag "List of files and directories" file)
   3093 	  (file :tag "Store list in a file\n" :value "~/.agenda_files")))
   3094 
   3095 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
   3096   "Regular expression to match files for `org-agenda-files'.
   3097 If any element in the list in that variable contains a directory instead
   3098 of a normal file, all files in that directory that are matched by this
   3099 regular expression will be included."
   3100   :group 'org-agenda
   3101   :type 'regexp)
   3102 
   3103 (defvaralias 'org-agenda-multi-occur-extra-files
   3104   'org-agenda-text-search-extra-files)
   3105 
   3106 (defcustom org-agenda-text-search-extra-files nil
   3107   "List of extra files to be searched by text search commands.
   3108 These files will be searched in addition to the agenda files by the
   3109 commands `org-search-view' (`\\[org-agenda] s') \
   3110 and `org-occur-in-agenda-files'.
   3111 Note that these files will only be searched for text search commands,
   3112 not for the other agenda views like todo lists, tag searches or the weekly
   3113 agenda.  This variable is intended to list notes and possibly archive files
   3114 that should also be searched by these two commands.
   3115 In fact, if the first element in the list is the symbol `agenda-archives',
   3116 then all archive files of all agenda files will be added to the search
   3117 scope."
   3118   :group 'org-agenda
   3119   :type '(set :greedy t
   3120 	      (const :tag "Agenda Archives" agenda-archives)
   3121 	      (repeat :inline t (file))))
   3122 
   3123 (defcustom org-agenda-skip-unavailable-files nil
   3124   "Non-nil means to just skip non-reachable files in `org-agenda-files'.
   3125 A nil value means to remove them, after a query, from the list."
   3126   :group 'org-agenda
   3127   :type 'boolean)
   3128 
   3129 (defgroup org-latex nil
   3130   "Options for embedding LaTeX code into Org mode."
   3131   :tag "Org LaTeX"
   3132   :group 'org)
   3133 
   3134 (defcustom org-format-latex-options
   3135   '(:foreground default :background default :scale 1.0
   3136 		:html-foreground "Black" :html-background "Transparent"
   3137 		:html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
   3138   "Options for creating images from LaTeX fragments.
   3139 This is a property list with the following properties:
   3140 :foreground  the foreground color for images embedded in Emacs, e.g. \"Black\".
   3141              `default' means use the foreground of the default face.
   3142              `auto' means use the foreground from the text face.
   3143 :background  the background color, or \"Transparent\".
   3144              `default' means use the background of the default face.
   3145              `auto' means use the background from the text face.
   3146 :scale       a scaling factor for the size of the images, to get more pixels
   3147 :html-foreground, :html-background, :html-scale
   3148              the same numbers for HTML export.
   3149 :matchers    a list indicating which matchers should be used to
   3150              find LaTeX fragments.  Valid members of this list are:
   3151              \"begin\" find environments
   3152              \"$1\"    find single characters surrounded by $.$
   3153              \"$\"     find math expressions surrounded by $...$
   3154              \"$$\"    find math expressions surrounded by $$....$$
   3155              \"\\(\"    find math expressions surrounded by \\(...\\)
   3156              \"\\=\\[\"    find math expressions surrounded by \\=\\[...\\]"
   3157   :group 'org-latex
   3158   :type 'plist)
   3159 
   3160 (defcustom org-format-latex-signal-error t
   3161   "Non-nil means signal an error when image creation of LaTeX snippets fails.
   3162 When nil, just push out a message."
   3163   :group 'org-latex
   3164   :version "24.1"
   3165   :type 'boolean)
   3166 
   3167 (defcustom org-latex-to-mathml-jar-file nil
   3168   "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
   3169 Use this to specify additional executable file say a jar file.
   3170 
   3171 When using MathToWeb as the converter, specify the full-path to
   3172 your mathtoweb.jar file."
   3173   :group 'org-latex
   3174   :version "24.1"
   3175   :type '(choice
   3176 	  (const :tag "None" nil)
   3177 	  (file :tag "JAR file" :must-match t)))
   3178 
   3179 (defcustom org-latex-to-mathml-convert-command nil
   3180   "Command to convert LaTeX fragments to MathML.
   3181 Replace format-specifiers in the command as noted below and use
   3182 `shell-command' to convert LaTeX to MathML.
   3183 %j:     Executable file in fully expanded form as specified by
   3184         `org-latex-to-mathml-jar-file'.
   3185 %I:     Input LaTeX file in fully expanded form.
   3186 %i:     The latex fragment to be converted.
   3187 %o:     Output MathML file.
   3188 
   3189 This command is used by `org-create-math-formula'.
   3190 
   3191 When using MathToWeb as the converter, set this option to
   3192 \"java -jar %j -unicode -force -df %o %I\".
   3193 
   3194 When using LaTeXML set this option to
   3195 \"latexmlmath \"%i\" --presentationmathml=%o\"."
   3196   :group 'org-latex
   3197   :version "24.1"
   3198   :type '(choice
   3199 	  (const :tag "None" nil)
   3200 	  (string :tag "\nShell command")))
   3201 
   3202 (defcustom org-latex-to-html-convert-command nil
   3203   "Command to convert LaTeX fragments to HTML.
   3204 This command is very open-ended: the output of the command will
   3205 directly replace the LaTeX fragment in the resulting HTML.
   3206 Replace format-specifiers in the command as noted below and use
   3207 `shell-command' to convert LaTeX to HTML.
   3208 %i:     The LaTeX fragment to be converted.
   3209 
   3210 For example, this could be used with LaTeXML as
   3211 \"latexmlc \\='literal:%i\\=' --profile=math --preload=siunitx.sty 2>/dev/null\"."
   3212   :group 'org-latex
   3213   :package-version '(Org . "9.4")
   3214   :type '(choice
   3215 	  (const :tag "None" nil)
   3216 	  (string :tag "Shell command")))
   3217 
   3218 (defcustom org-preview-latex-default-process 'dvipng
   3219   "The default process to convert LaTeX fragments to image files.
   3220 All available processes and theirs documents can be found in
   3221 `org-preview-latex-process-alist', which see."
   3222   :group 'org-latex
   3223   :version "26.1"
   3224   :package-version '(Org . "9.0")
   3225   :type 'symbol)
   3226 
   3227 (defcustom org-preview-latex-process-alist
   3228   '((dvipng
   3229      :programs ("latex" "dvipng")
   3230      :description "dvi > png"
   3231      :message "you need to install the programs: latex and dvipng."
   3232      :image-input-type "dvi"
   3233      :image-output-type "png"
   3234      :image-size-adjust (1.0 . 1.0)
   3235      :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
   3236      :image-converter ("dvipng -D %D -T tight -o %O %f")
   3237      :transparent-image-converter
   3238      ("dvipng -D %D -T tight -bg Transparent -o %O %f"))
   3239     (dvisvgm
   3240      :programs ("latex" "dvisvgm")
   3241      :description "dvi > svg"
   3242      :message "you need to install the programs: latex and dvisvgm."
   3243      :image-input-type "dvi"
   3244      :image-output-type "svg"
   3245      :image-size-adjust (1.7 . 1.5)
   3246      :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
   3247      :image-converter ("dvisvgm %f --no-fonts --exact-bbox --scale=%S --output=%O"))
   3248     (imagemagick
   3249      :programs ("latex" "convert")
   3250      :description "pdf > png"
   3251      :message "you need to install the programs: latex and imagemagick."
   3252      :image-input-type "pdf"
   3253      :image-output-type "png"
   3254      :image-size-adjust (1.0 . 1.0)
   3255      :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
   3256      :image-converter
   3257      ("convert -density %D -trim -antialias %f -quality 100 %O")))
   3258   "Definitions of external processes for LaTeX previewing.
   3259 Org mode can use some external commands to generate TeX snippet's images for
   3260 previewing or inserting into HTML files, e.g., \"dvipng\".  This variable tells
   3261 `org-create-formula-image' how to call them.
   3262 
   3263 The value is an alist with the pattern (NAME . PROPERTIES).  NAME is a symbol.
   3264 PROPERTIES accepts the following attributes:
   3265 
   3266   :programs           list of strings, required programs.
   3267   :description        string, describe the process.
   3268   :message            string, message it when required programs cannot be found.
   3269   :image-input-type   string, input file type of image converter (e.g., \"dvi\").
   3270   :image-output-type  string, output file type of image converter (e.g., \"png\").
   3271   :image-size-adjust  cons of numbers, the car element is used to adjust LaTeX
   3272                       image size showed in buffer and the cdr element is for
   3273                       HTML file.  This option is only useful for process
   3274                       developers, users should use variable
   3275                       `org-format-latex-options' instead.
   3276   :post-clean         list of strings, files matched are to be cleaned up once
   3277                       the image is generated.  When nil, the files with \".dvi\",
   3278                       \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
   3279                       \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
   3280                       be cleaned up.
   3281   :latex-header       list of strings, the LaTeX header of the snippet file.
   3282                       When nil, the fallback value is used instead, which is
   3283                       controlled by `org-format-latex-header',
   3284                       `org-latex-default-packages-alist' and
   3285                       `org-latex-packages-alist', which see.
   3286   :latex-compiler     list of LaTeX commands, as strings.  Each of them is given
   3287                       to the shell.  Place-holders \"%t\", \"%b\" and \"%o\" are
   3288                       replaced with values defined below.
   3289   :image-converter    list of image converter commands strings.  Each of them is
   3290                       given to the shell and supports any of the following
   3291                       place-holders defined below.
   3292 
   3293 If set, :transparent-image-converter is used instead of :image-converter to
   3294 convert an image when the background color is nil or \"Transparent\".
   3295 
   3296 Place-holders used by `:image-converter' and `:latex-compiler':
   3297 
   3298   %f    input file name
   3299   %b    base name of input file
   3300   %o    base directory of input file
   3301   %O    absolute output file name
   3302 
   3303 Place-holders only used by `:image-converter':
   3304 
   3305   %D    dpi, which is used to adjust image size by some processing commands.
   3306   %S    the image size scale ratio, which is used to adjust image size by some
   3307         processing commands."
   3308   :group 'org-latex
   3309   :package-version '(Org . "9.6")
   3310   :type '(alist :tag "LaTeX to image backends"
   3311 		:value-type (plist)))
   3312 
   3313 (defcustom org-preview-latex-image-directory "ltximg/"
   3314   "Path to store latex preview images.
   3315 A relative path here creates many directories relative to the
   3316 processed Org files paths.  An absolute path puts all preview
   3317 images at the same place."
   3318   :group 'org-latex
   3319   :version "26.1"
   3320   :package-version '(Org . "9.0")
   3321   :type 'string)
   3322 
   3323 (defun org-format-latex-mathml-available-p ()
   3324   "Return t if `org-latex-to-mathml-convert-command' is usable."
   3325   (save-match-data
   3326     (when (and (boundp 'org-latex-to-mathml-convert-command)
   3327 	       org-latex-to-mathml-convert-command)
   3328       (let ((executable (car (split-string
   3329 			      org-latex-to-mathml-convert-command))))
   3330 	(when (executable-find executable)
   3331 	  (if (string-match
   3332 	       "%j" org-latex-to-mathml-convert-command)
   3333 	      (file-readable-p org-latex-to-mathml-jar-file)
   3334 	    t))))))
   3335 
   3336 (defcustom org-format-latex-header "\\documentclass{article}
   3337 \\usepackage[usenames]{color}
   3338 \[DEFAULT-PACKAGES]
   3339 \[PACKAGES]
   3340 \\pagestyle{empty}             % do not remove
   3341 % The settings below are copied from fullpage.sty
   3342 \\setlength{\\textwidth}{\\paperwidth}
   3343 \\addtolength{\\textwidth}{-3cm}
   3344 \\setlength{\\oddsidemargin}{1.5cm}
   3345 \\addtolength{\\oddsidemargin}{-2.54cm}
   3346 \\setlength{\\evensidemargin}{\\oddsidemargin}
   3347 \\setlength{\\textheight}{\\paperheight}
   3348 \\addtolength{\\textheight}{-\\headheight}
   3349 \\addtolength{\\textheight}{-\\headsep}
   3350 \\addtolength{\\textheight}{-\\footskip}
   3351 \\addtolength{\\textheight}{-3cm}
   3352 \\setlength{\\topmargin}{1.5cm}
   3353 \\addtolength{\\topmargin}{-2.54cm}"
   3354   "The document header used for processing LaTeX fragments.
   3355 It is imperative that this header make sure that no page number
   3356 appears on the page.  The package defined in the variables
   3357 `org-latex-default-packages-alist' and `org-latex-packages-alist'
   3358 will either replace the placeholder \"[PACKAGES]\" in this
   3359 header, or they will be appended."
   3360   :group 'org-latex
   3361   :type 'string)
   3362 
   3363 (defun org-set-packages-alist (var val)
   3364   "Set the packages alist and make sure it has 3 elements per entry."
   3365   (set-default-toplevel-value var (mapcar (lambda (x)
   3366 		     (if (and (consp x) (= (length x) 2))
   3367 			 (list (car x) (nth 1 x) t)
   3368 		       x))
   3369 		   val)))
   3370 
   3371 (defun org-get-packages-alist (var)
   3372   "Get the packages alist and make sure it has 3 elements per entry."
   3373   (mapcar (lambda (x)
   3374 	    (if (and (consp x) (= (length x) 2))
   3375 		(list (car x) (nth 1 x) t)
   3376 	      x))
   3377 	  (default-value var)))
   3378 
   3379 (defcustom org-latex-default-packages-alist
   3380   '(("AUTO" "inputenc"  t ("pdflatex"))
   3381     ("T1"   "fontenc"   t ("pdflatex"))
   3382     (""     "graphicx"  t)
   3383     (""     "longtable" nil)
   3384     (""     "wrapfig"   nil)
   3385     (""     "rotating"  nil)
   3386     ("normalem" "ulem"  t)
   3387     (""     "amsmath"   t)
   3388     (""     "amssymb"   t)
   3389     (""     "capt-of"   nil)
   3390     (""     "hyperref"  nil))
   3391   "Alist of default packages to be inserted in the header.
   3392 
   3393 Change this only if one of the packages here causes an
   3394 incompatibility with another package you are using.
   3395 
   3396 The packages in this list are needed by one part or another of
   3397 Org mode to function properly:
   3398 
   3399 - inputenc, fontenc:  for basic font and character selection
   3400 - graphicx: for including images
   3401 - longtable: For multipage tables
   3402 - wrapfig: for figure placement
   3403 - rotating: for sideways figures and tables
   3404 - ulem: for underline and strike-through
   3405 - amsmath: for subscript and superscript and math environments
   3406 - amssymb: for various symbols used for interpreting the entities
   3407   in `org-entities'.  You can skip some of this package if you don't
   3408   use any of the symbols.
   3409 - capt-of: for captions outside of floats
   3410 - hyperref: for cross references
   3411 
   3412 Therefore you should not modify this variable unless you know
   3413 what you are doing.  The one reason to change it anyway is that
   3414 you might be loading some other package that conflicts with one
   3415 of the default packages.  Each element is either a cell or
   3416 a string.
   3417 
   3418 A cell is of the format
   3419 
   3420   (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
   3421 
   3422 If SNIPPET-FLAG is non-nil, the package also needs to be included
   3423 when compiling LaTeX snippets into images for inclusion into
   3424 non-LaTeX output.
   3425 
   3426 COMPILERS is a list of compilers that should include the package,
   3427 see `org-latex-compiler'.  If the document compiler is not in the
   3428 list, and the list is non-nil, the package will not be inserted
   3429 in the final document.
   3430 
   3431 A string will be inserted as-is in the header of the document."
   3432   :group 'org-latex
   3433   :group 'org-export-latex
   3434   :set 'org-set-packages-alist
   3435   :get 'org-get-packages-alist
   3436   :version "26.1"
   3437   :package-version '(Org . "8.3")
   3438   :type '(repeat
   3439 	  (choice
   3440 	   (list :tag "options/package pair"
   3441 		 (string :tag "options")
   3442 		 (string :tag "package")
   3443 		 (boolean :tag "Snippet")
   3444 		 (choice
   3445 		  (const :tag "For all compilers" nil)
   3446 		  (repeat :tag "Allowed compiler" string)))
   3447 	   (string :tag "A line of LaTeX"))))
   3448 
   3449 (defcustom org-latex-packages-alist nil
   3450   "Alist of packages to be inserted in every LaTeX header.
   3451 
   3452 These will be inserted after `org-latex-default-packages-alist'.
   3453 Each element is either a cell or a string.
   3454 
   3455 A cell is of the format:
   3456 
   3457     (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
   3458 
   3459 SNIPPET-FLAG, when non-nil, indicates that this package is also
   3460 needed when turning LaTeX snippets into images for inclusion into
   3461 non-LaTeX output.
   3462 
   3463 COMPILERS is a list of compilers that should include the package,
   3464 see `org-latex-compiler'.  If the document compiler is not in the
   3465 list, and the list is non-nil, the package will not be inserted
   3466 in the final document.
   3467 
   3468 A string will be inserted as-is in the header of the document.
   3469 
   3470 Make sure that you only list packages here which:
   3471 
   3472   - you want in every file;
   3473   - do not conflict with the setup in `org-format-latex-header';
   3474   - do not conflict with the default packages in
   3475     `org-latex-default-packages-alist'."
   3476   :group 'org-latex
   3477   :group 'org-export-latex
   3478   :set 'org-set-packages-alist
   3479   :get 'org-get-packages-alist
   3480   :type '(repeat
   3481 	  (choice
   3482 	   (list :tag "options/package pair"
   3483 		 (string :tag "options")
   3484 		 (string :tag "package")
   3485 		 (boolean :tag "Snippet"))
   3486 	   (string :tag "A line of LaTeX"))))
   3487 
   3488 (defgroup org-appearance nil
   3489   "Settings for Org mode appearance."
   3490   :tag "Org Appearance"
   3491   :group 'org)
   3492 
   3493 (defcustom org-level-color-stars-only nil
   3494   "Non-nil means fontify only the stars in each headline.
   3495 When nil, the entire headline is fontified.
   3496 Changing it requires restart of `font-lock-mode' to become effective
   3497 also in regions already fontified."
   3498   :group 'org-appearance
   3499   :type 'boolean)
   3500 
   3501 (defcustom org-hide-leading-stars nil
   3502   "Non-nil means hide the first N-1 stars in a headline.
   3503 This works by using the face `org-hide' for these stars.  This
   3504 face is white for a light background, and black for a dark
   3505 background.  You may have to customize the face `org-hide' to
   3506 make this work.
   3507 Changing it requires restart of `font-lock-mode' to become effective
   3508 also in regions already fontified.
   3509 You may also set this on a per-file basis by adding one of the following
   3510 lines to the buffer:
   3511 
   3512    #+STARTUP: hidestars
   3513    #+STARTUP: showstars"
   3514   :group 'org-appearance
   3515   :type 'boolean)
   3516 
   3517 (defcustom org-hidden-keywords nil
   3518   "List of symbols corresponding to keywords to be hidden in the Org buffer.
   3519 For example, a value (title) for this list makes the document's title
   3520 appear in the buffer without the initial \"#+TITLE:\" part."
   3521   :group 'org-appearance
   3522   :package-version '(Org . "9.5")
   3523   :type '(set (const :tag "#+AUTHOR" author)
   3524 	      (const :tag "#+DATE" date)
   3525 	      (const :tag "#+EMAIL" email)
   3526 	      (const :tag "#+SUBTITLE" subtitle)
   3527 	      (const :tag "#+TITLE" title)))
   3528 
   3529 (defcustom org-custom-properties nil
   3530   "List of properties (as strings) with a special meaning.
   3531 The default use of these custom properties is to let the user
   3532 hide them with `org-toggle-custom-properties-visibility'."
   3533   :group 'org-properties
   3534   :group 'org-appearance
   3535   :version "24.3"
   3536   :type '(repeat (string :tag "Property Name")))
   3537 
   3538 (defcustom org-fontify-todo-headline nil
   3539   "Non-nil means change the face of a headline if it is marked as TODO.
   3540 Normally, only the TODO/DONE keyword indicates the state of a headline.
   3541 When this is non-nil, the headline after the keyword is set to the
   3542 `org-headline-todo' as an additional indication."
   3543   :group 'org-appearance
   3544   :package-version '(Org . "9.4")
   3545   :type 'boolean
   3546   :safe #'booleanp)
   3547 
   3548 (defcustom org-fontify-done-headline t
   3549   "Non-nil means change the face of a headline if it is marked DONE.
   3550 Normally, only the TODO/DONE keyword indicates the state of a headline.
   3551 When this is non-nil, the headline after the keyword is set to the
   3552 `org-headline-done' as an additional indication."
   3553   :group 'org-appearance
   3554   :package-version '(Org . "9.4")
   3555   :type 'boolean)
   3556 
   3557 (defcustom org-fontify-emphasized-text t
   3558   "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
   3559 Changing this variable requires a restart of Emacs to take effect."
   3560   :group 'org-appearance
   3561   :type 'boolean)
   3562 
   3563 (defcustom org-fontify-whole-heading-line nil
   3564   "Non-nil means fontify the whole line for headings.
   3565 This is useful when setting a background color for the
   3566 org-level-* faces."
   3567   :group 'org-appearance
   3568   :type 'boolean)
   3569 
   3570 (defcustom org-fontify-whole-block-delimiter-line t
   3571   "Non-nil means fontify the whole line for begin/end lines of blocks.
   3572 This is useful when setting a background color for the
   3573 org-block-begin-line and org-block-end-line faces."
   3574   :group 'org-appearance
   3575   :type 'boolean)
   3576 
   3577 (defcustom org-highlight-latex-and-related nil
   3578   "Non-nil means highlight LaTeX related syntax in the buffer.
   3579 When non-nil, the value should be a list containing any of the
   3580 following symbols:
   3581   `native'   Highlight LaTeX snippets and environments natively.
   3582   `latex'    Highlight LaTeX snippets and environments.
   3583   `script'   Highlight subscript and superscript.
   3584   `entities' Highlight entities."
   3585   :group 'org-appearance
   3586   :version "24.4"
   3587   :package-version '(Org . "8.0")
   3588   :type '(choice
   3589 	  (const :tag "No highlighting" nil)
   3590 	  (set :greedy t :tag "Highlight"
   3591 	       (const :tag "LaTeX snippets and environments (native)" native)
   3592 	       (const :tag "LaTeX snippets and environments" latex)
   3593 	       (const :tag "Subscript and superscript" script)
   3594 	       (const :tag "Entities" entities))))
   3595 
   3596 (defcustom org-hide-emphasis-markers nil
   3597   "Non-nil mean font-lock should hide the emphasis marker characters."
   3598   :group 'org-appearance
   3599   :type 'boolean
   3600   :safe #'booleanp)
   3601 
   3602 (defcustom org-hide-macro-markers nil
   3603   "Non-nil mean font-lock should hide the brackets marking macro calls."
   3604   :group 'org-appearance
   3605   :type 'boolean)
   3606 
   3607 (defcustom org-pretty-entities nil
   3608   "Non-nil means show entities as UTF8 characters.
   3609 When nil, the \\name form remains in the buffer."
   3610   :group 'org-appearance
   3611   :version "24.1"
   3612   :type 'boolean)
   3613 
   3614 (defcustom org-pretty-entities-include-sub-superscripts t
   3615   "Non-nil means, pretty entity display includes formatting sub/superscripts."
   3616   :group 'org-appearance
   3617   :version "24.1"
   3618   :type 'boolean)
   3619 
   3620 (defvar org-emph-re nil
   3621   "Regular expression for matching emphasis.
   3622 After a match, the match groups contain these elements:
   3623 0  The match of the full regular expression, including the characters
   3624    before and after the proper match
   3625 1  The character before the proper match, or empty at beginning of line
   3626 2  The proper match, including the leading and trailing markers
   3627 3  The leading marker like * or /, indicating the type of highlighting
   3628 4  The text between the emphasis markers, not including the markers
   3629 5  The character after the match, empty at the end of a line")
   3630 
   3631 (defvar org-verbatim-re nil
   3632   "Regular expression for matching verbatim text.")
   3633 
   3634 (defvar org-emphasis-regexp-components) ; defined just below
   3635 (defvar org-emphasis-alist) ; defined just below
   3636 (defun org-set-emph-re (var val)
   3637   "Set variable and compute the emphasis regular expression."
   3638   (set-default-toplevel-value var val)
   3639   (when (and (boundp 'org-emphasis-alist)
   3640 	     (boundp 'org-emphasis-regexp-components)
   3641 	     org-emphasis-alist org-emphasis-regexp-components)
   3642     (pcase-let*
   3643 	((`(,pre ,post ,border ,body ,nl) org-emphasis-regexp-components)
   3644 	 (body (if (<= nl 0) body
   3645 		 (format "%s*?\\(?:\n%s*?\\)\\{0,%d\\}" body body nl)))
   3646 	 (template
   3647 	  (format (concat "\\([%s]\\|^\\)" ;before markers
   3648 			  "\\(\\([%%s]\\)\\([^%s]\\|[^%s]%s[^%s]\\)\\3\\)"
   3649 			  "\\([%s]\\|$\\)") ;after markers
   3650 		  pre border border body border post)))
   3651       (setq org-emph-re (format template "*/_+"))
   3652       (setq org-verbatim-re (format template "=~")))))
   3653 
   3654 ;; This used to be a defcustom (Org <8.0) but allowing the users to
   3655 ;; set this option proved cumbersome.  See this message/thread:
   3656 ;; https://orgmode.org/list/B72CDC2B-72F6-43A8-AC70-E6E6295766EC@gmail.com
   3657 (defvar org-emphasis-regexp-components
   3658   '("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)
   3659   "Components used to build the regular expression for emphasis.
   3660 This is a list with five entries.  Terminology:  In an emphasis string
   3661 like \" *strong word* \", we call the initial space PREMATCH, the final
   3662 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
   3663 and \"trong wor\" is the body.  The different components in this variable
   3664 specify what is allowed/forbidden in each part:
   3665 
   3666 pre          Chars allowed as prematch.  Beginning of line will be allowed too.
   3667 post         Chars allowed as postmatch.  End of line will be allowed too.
   3668 border       The chars *forbidden* as border characters.
   3669 body-regexp  A regexp like \".\" to match a body character.  Don't use
   3670              non-shy groups here, and don't allow newline here.
   3671 newline      The maximum number of newlines allowed in an emphasis exp.
   3672 
   3673 You need to reload Org or to restart Emacs after setting this.")
   3674 
   3675 (defcustom org-emphasis-alist
   3676   '(("*" bold)
   3677     ("/" italic)
   3678     ("_" underline)
   3679     ("=" org-verbatim verbatim)
   3680     ("~" org-code verbatim)
   3681     ("+" (:strike-through t)))
   3682   "Alist of characters and faces to emphasize text.
   3683 Text starting and ending with a special character will be emphasized,
   3684 for example *bold*, _underlined_ and /italic/.  This variable sets the
   3685 marker characters and the face to be used by font-lock for highlighting
   3686 in Org buffers.
   3687 
   3688 You need to reload Org or to restart Emacs after customizing this."
   3689   :group 'org-appearance
   3690   :set 'org-set-emph-re
   3691   :version "24.4"
   3692   :package-version '(Org . "8.0")
   3693   :type '(repeat
   3694 	  (list
   3695 	   (string :tag "Marker character")
   3696 	   (choice
   3697 	    (face :tag "Font-lock-face")
   3698 	    (plist :tag "Face property list"))
   3699 	   (option (const verbatim)))))
   3700 
   3701 (defvar org-protecting-blocks '("src" "example" "export")
   3702   "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
   3703 This is needed for font-lock setup.")
   3704 
   3705 ;;; Functions and variables from their packages
   3706 ;;  Declared here to avoid compiler warnings
   3707 (defvar mark-active)
   3708 
   3709 ;; Various packages
   3710 (declare-function calc-eval "calc" (str &optional separator &rest args))
   3711 (declare-function calendar-forward-day "cal-move" (arg))
   3712 (declare-function calendar-goto-date "cal-move" (date))
   3713 (declare-function calendar-goto-today "cal-move" ())
   3714 (declare-function calendar-iso-from-absolute "cal-iso" (date))
   3715 (declare-function calendar-iso-to-absolute "cal-iso" (date))
   3716 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
   3717 (declare-function cdlatex-tab "ext:cdlatex" ())
   3718 (declare-function dired-get-filename
   3719 		  "dired"
   3720 		  (&optional localp no-error-if-not-filep))
   3721 (declare-function org-agenda-change-all-lines
   3722 		  "org-agenda"
   3723 		  (newhead hdmarker &optional fixface just-this))
   3724 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
   3725 		  "org-agenda"
   3726 		  (&optional end))
   3727 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
   3728 (declare-function org-agenda-format-item
   3729 		  "org-agenda"
   3730 		  (extra txt &optional level category tags dotime
   3731 			 remove-re habitp))
   3732 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
   3733 (declare-function org-agenda-save-markers-for-cut-and-paste
   3734 		  "org-agenda"
   3735 		  (beg end))
   3736 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
   3737 (declare-function org-agenda-skip "org-agenda" (&optional element))
   3738 (declare-function org-attach-expand "org-attach" (file))
   3739 (declare-function org-attach-reveal "org-attach" ())
   3740 (declare-function org-attach-reveal-in-emacs "org-attach" ())
   3741 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
   3742 (declare-function org-indent-mode "org-indent" (&optional arg))
   3743 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
   3744 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
   3745 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
   3746 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
   3747 (declare-function parse-time-string "parse-time" (string))
   3748 
   3749 (defvar align-mode-rules-list)
   3750 (defvar calc-embedded-close-formula)
   3751 (defvar calc-embedded-open-formula)
   3752 (defvar calc-embedded-open-mode)
   3753 (defvar font-lock-unfontify-region-function)
   3754 (defvar org-agenda-tags-todo-honor-ignore-options)
   3755 (defvar remember-data-file)
   3756 (defvar texmathp-why)
   3757 
   3758 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
   3759 (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
   3760 (declare-function org-resolve-clocks "org-clock"
   3761 		  (&optional also-non-dangling-p prompt last-valid))
   3762 
   3763 (defvar org-clock-start-time)
   3764 (defvar org-clock-marker (make-marker)
   3765   "Marker recording the last clock-in.")
   3766 (defvar org-clock-hd-marker (make-marker)
   3767   "Marker recording the last clock-in, but the headline position.")
   3768 (defvar org-clock-heading ""
   3769   "The heading of the current clock entry.")
   3770 (defun org-clocking-buffer ()
   3771   "Return the buffer where the clock is currently running.
   3772 Return nil if no clock is running."
   3773   (marker-buffer org-clock-marker))
   3774 (defalias 'org-clock-is-active #'org-clocking-buffer)
   3775 
   3776 (defun org-check-running-clock ()
   3777   "Check if the current buffer contains the running clock.
   3778 If yes, offer to stop it and to save the buffer with the changes."
   3779   (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
   3780 	     (y-or-n-p (format "Clock-out in buffer %s before killing it? "
   3781 			       (buffer-name))))
   3782     (org-clock-out)
   3783     (when (y-or-n-p "Save changed buffer?")
   3784       (save-buffer))))
   3785 
   3786 (defun org-clocktable-try-shift (dir n)
   3787   "Check if this line starts a clock table, if yes, shift the time block."
   3788   (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
   3789     (org-clocktable-shift dir n)))
   3790 
   3791 ;;;###autoload
   3792 (defun org-clock-persistence-insinuate ()
   3793   "Set up hooks for clock persistence."
   3794   (require 'org-clock)
   3795   (add-hook 'org-mode-hook 'org-clock-load)
   3796   (add-hook 'kill-emacs-hook 'org-clock-save))
   3797 
   3798 (defun org-clock-auto-clockout-insinuate ()
   3799   "Set up hook for auto clocking out when Emacs is idle.
   3800 See `org-clock-auto-clockout-timer'.
   3801 
   3802 This function is meant to be added to the user configuration."
   3803   (require 'org-clock)
   3804   (add-hook 'org-clock-in-hook #'org-clock-auto-clockout t))
   3805 
   3806 (defgroup org-archive nil
   3807   "Options concerning archiving in Org mode."
   3808   :tag "Org Archive"
   3809   :group 'org-structure)
   3810 
   3811 (defcustom org-archive-location "%s_archive::"
   3812   "The location where subtrees should be archived.
   3813 
   3814 The value of this variable is a string, consisting of two parts,
   3815 separated by a double-colon.  The first part is a filename and
   3816 the second part is a headline.
   3817 
   3818 When the filename is omitted, archiving happens in the same file.
   3819 %s in the filename will be replaced by the current file
   3820 name (without the directory part).  Archiving to a different file
   3821 is useful to keep archived entries from contributing to the
   3822 Org Agenda.
   3823 
   3824 The archived entries will be filed as subtrees of the specified
   3825 headline.  When the headline is omitted, the subtrees are simply
   3826 filed away at the end of the file, as top-level entries.  Also in
   3827 the heading you can use %s to represent the file name, this can be
   3828 useful when using the same archive for a number of different files.
   3829 
   3830 Here are a few examples:
   3831 \"%s_archive::\"
   3832 	If the current file is Projects.org, archive in file
   3833 	Projects.org_archive, as top-level trees.  This is the default.
   3834 
   3835 \"::* Archived Tasks\"
   3836 	Archive in the current file, under the top-level headline
   3837 	\"* Archived Tasks\".
   3838 
   3839 \"~/org/archive.org::\"
   3840 	Archive in file ~/org/archive.org (absolute path), as top-level trees.
   3841 
   3842 \"~/org/archive.org::* From %s\"
   3843 	Archive in file ~/org/archive.org (absolute path), under headlines
   3844         \"From FILENAME\" where file name is the current file name.
   3845 
   3846 \"~/org/datetree.org::datetree/* Finished Tasks\"
   3847         The \"datetree/\" string is special, signifying to archive
   3848         items to the datetree.  Items are placed in either the CLOSED
   3849         date of the item, or the current date if there is no CLOSED date.
   3850         The heading will be a subentry to the current date.  There doesn't
   3851         need to be a heading, but there always needs to be a slash after
   3852         datetree.  For example, to store archived items directly in the
   3853         datetree, use \"~/org/datetree.org::datetree/\".
   3854 
   3855 \"basement::** Finished Tasks\"
   3856 	Archive in file ./basement (relative path), as level 3 trees
   3857 	below the level 2 heading \"** Finished Tasks\".
   3858 
   3859 You may define it locally by setting an ARCHIVE property.  If
   3860 such a property is found in the file or in an entry, and anywhere
   3861 up the hierarchy, it will be used.
   3862 
   3863 You can also set it for the whole file using the keyword-syntax:
   3864 
   3865 #+ARCHIVE: basement::** Finished Tasks"
   3866   :group 'org-archive
   3867   :type 'string)
   3868 
   3869 (defcustom org-agenda-skip-archived-trees t
   3870   "Non-nil means the agenda will skip any items located in archived trees.
   3871 An archived tree is a tree marked with the tag ARCHIVE.  The use of this
   3872 variable is no longer recommended, you should leave it at the value t.
   3873 Instead, use the key `v' to cycle the archives-mode in the agenda."
   3874   :group 'org-archive
   3875   :group 'org-agenda-skip
   3876   :type 'boolean)
   3877 
   3878 (defcustom org-columns-skip-archived-trees t
   3879   "Non-nil means ignore archived trees when creating column view."
   3880   :group 'org-archive
   3881   :group 'org-properties
   3882   :type 'boolean)
   3883 
   3884 (defcustom org-sparse-tree-open-archived-trees nil
   3885   "Non-nil means sparse tree construction shows matches in archived trees.
   3886 When nil, matches in these trees are highlighted, but the trees are kept in
   3887 collapsed state."
   3888   :group 'org-archive
   3889   :group 'org-sparse-trees
   3890   :type 'boolean)
   3891 
   3892 (defcustom org-sparse-tree-default-date-type nil
   3893   "The default date type when building a sparse tree.
   3894 When this is nil, a date is a scheduled or a deadline timestamp.
   3895 Otherwise, these types are allowed:
   3896 
   3897         all: all timestamps
   3898      active: only active timestamps (<...>)
   3899    inactive: only inactive timestamps ([...])
   3900   scheduled: only scheduled timestamps
   3901    deadline: only deadline timestamps"
   3902   :type '(choice (const :tag "Scheduled or deadline" nil)
   3903 		 (const :tag "All timestamps" all)
   3904 		 (const :tag "Only active timestamps" active)
   3905 		 (const :tag "Only inactive timestamps" inactive)
   3906 		 (const :tag "Only scheduled timestamps" scheduled)
   3907 		 (const :tag "Only deadline timestamps" deadline)
   3908 		 (const :tag "Only closed timestamps" closed))
   3909   :version "26.1"
   3910   :package-version '(Org . "8.3")
   3911   :group 'org-sparse-trees)
   3912 
   3913 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
   3914 
   3915 ;; Declare Column View Code
   3916 
   3917 (declare-function org-columns-get-format-and-top-level "org-colview" ())
   3918 (declare-function org-columns-compute "org-colview" (property))
   3919 
   3920 ;; Declare ID code
   3921 
   3922 (declare-function org-id-store-link "org-id")
   3923 (declare-function org-id-locations-load "org-id")
   3924 (declare-function org-id-locations-save "org-id")
   3925 (defvar org-id-track-globally)
   3926 
   3927 ;;; Variables for pre-computed regular expressions, all buffer local
   3928 
   3929 (defvar-local org-todo-regexp nil
   3930   "Matches any of the TODO state keywords.
   3931 Since TODO keywords are case-sensitive, `case-fold-search' is
   3932 expected to be bound to nil when matching against this regexp.")
   3933 
   3934 (defvar-local org-not-done-regexp nil
   3935   "Matches any of the TODO state keywords except the last one.
   3936 Since TODO keywords are case-sensitive, `case-fold-search' is
   3937 expected to be bound to nil when matching against this regexp.")
   3938 
   3939 (defvar-local org-not-done-heading-regexp nil
   3940   "Matches a TODO headline that is not done.
   3941 Since TODO keywords are case-sensitive, `case-fold-search' is
   3942 expected to be bound to nil when matching against this regexp.")
   3943 
   3944 (defvar-local org-todo-line-regexp nil
   3945   "Matches a headline and puts TODO state into group 2 if present.
   3946 Since TODO keywords are case-sensitive, `case-fold-search' is
   3947 expected to be bound to nil when matching against this regexp.")
   3948 
   3949 (defvar-local org-complex-heading-regexp nil
   3950   "Matches a headline and puts everything into groups:
   3951 
   3952 group 1: Stars
   3953 group 2: The TODO keyword, maybe
   3954 group 3: Priority cookie
   3955 group 4: True headline
   3956 group 5: Tags
   3957 
   3958 Since TODO keywords are case-sensitive, `case-fold-search' is
   3959 expected to be bound to nil when matching against this regexp.")
   3960 
   3961 (defvar-local org-complex-heading-regexp-format nil
   3962   "Printf format to make regexp to match an exact headline.
   3963 This regexp will match the headline of any node which has the
   3964 exact headline text that is put into the format, but may have any
   3965 TODO state, priority, tags, statistics cookies (at the beginning
   3966 or end of the headline title), or COMMENT keyword.")
   3967 
   3968 (defvar-local org-todo-line-tags-regexp nil
   3969   "Matches a headline and puts TODO state into group 2 if present.
   3970 Also put tags into group 4 if tags are present.")
   3971 
   3972 (defconst org-plain-time-of-day-regexp
   3973   (concat
   3974    "\\(\\<[012]?[0-9]"
   3975    "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
   3976    "\\(--?"
   3977    "\\(\\<[012]?[0-9]"
   3978    "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
   3979    "\\)?")
   3980   "Regular expression to match a plain time or time range.
   3981 Examples:  11:45 or 8am-13:15 or 2:45-2:45pm.  After a match, the following
   3982 groups carry important information:
   3983 0  the full match
   3984 1  the first time, range or not
   3985 8  the second time, if it is a range.")
   3986 
   3987 (defconst org-plain-time-extension-regexp
   3988   (concat
   3989    "\\(\\<[012]?[0-9]"
   3990    "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
   3991    "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
   3992   "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
   3993 Examples:  11:45 or 8am-13:15 or 2:45-2:45pm.  After a match, the following
   3994 groups carry important information:
   3995 0  the full match
   3996 7  hours of duration
   3997 9  minutes of duration")
   3998 
   3999 (defconst org-stamp-time-of-day-regexp
   4000   (concat
   4001    "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
   4002    "\\([012][0-9]:[0-5][0-9]\\)\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?>"
   4003    "\\(--?"
   4004    "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
   4005   "Regular expression to match a timestamp time or time range.
   4006 After a match, the following groups carry important information:
   4007 0  the full match
   4008 1  date plus weekday, for back referencing to make sure
   4009      both times are on the same day
   4010 2  the first time, range or not
   4011 4  the second time, if it is a range.")
   4012 
   4013 (defconst org-startup-options
   4014   '(("fold" org-startup-folded t)
   4015     ("overview" org-startup-folded t)
   4016     ("nofold" org-startup-folded nil)
   4017     ("showall" org-startup-folded nil)
   4018     ("show2levels" org-startup-folded show2levels)
   4019     ("show3levels" org-startup-folded show3levels)
   4020     ("show4levels" org-startup-folded show4levels)
   4021     ("show5levels" org-startup-folded show5levels)
   4022     ("showeverything" org-startup-folded showeverything)
   4023     ("content" org-startup-folded content)
   4024     ("indent" org-startup-indented t)
   4025     ("noindent" org-startup-indented nil)
   4026     ("num" org-startup-numerated t)
   4027     ("nonum" org-startup-numerated nil)
   4028     ("hidestars" org-hide-leading-stars t)
   4029     ("showstars" org-hide-leading-stars nil)
   4030     ("odd" org-odd-levels-only t)
   4031     ("oddeven" org-odd-levels-only nil)
   4032     ("align" org-startup-align-all-tables t)
   4033     ("noalign" org-startup-align-all-tables nil)
   4034     ("shrink" org-startup-shrink-all-tables t)
   4035     ("inlineimages" org-startup-with-inline-images t)
   4036     ("noinlineimages" org-startup-with-inline-images nil)
   4037     ("latexpreview" org-startup-with-latex-preview t)
   4038     ("nolatexpreview" org-startup-with-latex-preview nil)
   4039     ("customtime" org-display-custom-times t)
   4040     ("logdone" org-log-done time)
   4041     ("lognotedone" org-log-done note)
   4042     ("nologdone" org-log-done nil)
   4043     ("lognoteclock-out" org-log-note-clock-out t)
   4044     ("nolognoteclock-out" org-log-note-clock-out nil)
   4045     ("logrepeat" org-log-repeat state)
   4046     ("lognoterepeat" org-log-repeat note)
   4047     ("logdrawer" org-log-into-drawer t)
   4048     ("nologdrawer" org-log-into-drawer nil)
   4049     ("logstatesreversed" org-log-states-order-reversed t)
   4050     ("nologstatesreversed" org-log-states-order-reversed nil)
   4051     ("nologrepeat" org-log-repeat nil)
   4052     ("logreschedule" org-log-reschedule time)
   4053     ("lognotereschedule" org-log-reschedule note)
   4054     ("nologreschedule" org-log-reschedule nil)
   4055     ("logredeadline" org-log-redeadline time)
   4056     ("lognoteredeadline" org-log-redeadline note)
   4057     ("nologredeadline" org-log-redeadline nil)
   4058     ("logrefile" org-log-refile time)
   4059     ("lognoterefile" org-log-refile note)
   4060     ("nologrefile" org-log-refile nil)
   4061     ("fninline" org-footnote-define-inline t)
   4062     ("nofninline" org-footnote-define-inline nil)
   4063     ("fnlocal" org-footnote-section nil)
   4064     ("fnauto" org-footnote-auto-label t)
   4065     ("fnprompt" org-footnote-auto-label nil)
   4066     ("fnconfirm" org-footnote-auto-label confirm)
   4067     ("fnplain" org-footnote-auto-label plain)
   4068     ("fnadjust" org-footnote-auto-adjust t)
   4069     ("nofnadjust" org-footnote-auto-adjust nil)
   4070     ("constcgs" constants-unit-system cgs)
   4071     ("constSI" constants-unit-system SI)
   4072     ("noptag" org-tag-persistent-alist nil)
   4073     ("hideblocks" org-hide-block-startup t)
   4074     ("nohideblocks" org-hide-block-startup nil)
   4075     ("hidedrawers" org-hide-drawer-startup t)
   4076     ("nohidedrawers" org-hide-drawer-startup nil)
   4077     ("beamer" org-startup-with-beamer-mode t)
   4078     ("entitiespretty" org-pretty-entities t)
   4079     ("entitiesplain" org-pretty-entities nil))
   4080   "Variable associated with STARTUP options for Org.
   4081 Each element is a list of three items: the startup options (as written
   4082 in the #+STARTUP line), the corresponding variable, and the value to set
   4083 this variable to if the option is found.  An optional fourth element PUSH
   4084 means to push this value onto the list in the variable.")
   4085 
   4086 (defcustom org-group-tags t
   4087   "When non-nil (the default), use group tags.
   4088 This can be turned on/off through `org-toggle-tags-groups'."
   4089   :group 'org-tags
   4090   :group 'org-startup
   4091   :type 'boolean)
   4092 
   4093 (defvar org-inhibit-startup nil)        ; Dynamically-scoped param.
   4094 
   4095 (defun org-toggle-tags-groups ()
   4096   "Toggle support for group tags.
   4097 Support for group tags is controlled by the option
   4098 `org-group-tags', which is non-nil by default."
   4099   (interactive)
   4100   (setq org-group-tags (not org-group-tags))
   4101   (cond ((and (derived-mode-p 'org-agenda-mode)
   4102 	      org-group-tags)
   4103 	 (org-agenda-redo))
   4104 	((derived-mode-p 'org-mode)
   4105 	 (let ((org-inhibit-startup t)) (org-mode))))
   4106   (message "Groups tags support has been turned %s"
   4107 	   (if org-group-tags "on" "off")))
   4108 
   4109 (defun org--tag-add-to-alist (alist1 alist2)
   4110   "Merge tags from ALIST1 into ALIST2.
   4111 
   4112 Duplicates tags outside a group are removed.  Keywords and order
   4113 are preserved.
   4114 
   4115 The function assumes ALIST1 and ALIST2 are proper tag alists.
   4116 See `org-tag-alist' for their structure."
   4117   (cond
   4118    ((null alist2) alist1)
   4119    ((null alist1) alist2)
   4120    (t
   4121     (let ((to-add nil)
   4122 	  (group-flag nil))
   4123       (dolist (tag-pair alist1)
   4124 	(pcase tag-pair
   4125 	  (`(,(or :startgrouptag :startgroup))
   4126 	   (setq group-flag t)
   4127 	   (push tag-pair to-add))
   4128 	  (`(,(or :endgrouptag :endgroup))
   4129 	   (setq group-flag nil)
   4130 	   (push tag-pair to-add))
   4131 	  (`(,(or :grouptags :newline))
   4132 	   (push tag-pair to-add))
   4133 	  (`(,tag . ,_)
   4134 	   ;; Remove duplicates from ALIST1, unless they are in
   4135 	   ;; a group.  Indeed, it makes sense to have a tag appear in
   4136 	   ;; multiple groups.
   4137 	   (when (or group-flag (not (assoc tag alist2)))
   4138 	     (push tag-pair to-add)))
   4139 	  (_ (error "Invalid association in tag alist: %S" tag-pair))))
   4140       ;; Preserve order of ALIST1.
   4141       (append (nreverse to-add) alist2)))))
   4142 
   4143 (defun org-priority-to-value (s)
   4144   "Convert priority string S to its numeric value."
   4145   (or (save-match-data
   4146 	(and (string-match "\\([0-9]+\\)" s)
   4147 	     (string-to-number (match-string 1 s))))
   4148       (string-to-char s)))
   4149 
   4150 (defun org-set-regexps-and-options (&optional tags-only)
   4151   "Precompute regular expressions used in the current buffer.
   4152 When optional argument TAGS-ONLY is non-nil, only compute tags
   4153 related expressions."
   4154   (when (derived-mode-p 'org-mode)
   4155     (let ((alist (org-collect-keywords
   4156 		  (append '("FILETAGS" "TAGS")
   4157 			  (and (not tags-only)
   4158 			       '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
   4159 				 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
   4160 				 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))
   4161 		  '("ARCHIVE" "CATEGORY" "COLUMNS" "PRIORITIES"))))
   4162       ;; Startup options.  Get this early since it does change
   4163       ;; behavior for other options (e.g., tags).
   4164       (let ((startup (cl-mapcan (lambda (value) (split-string value))
   4165 				(cdr (assoc "STARTUP" alist)))))
   4166 	(dolist (option startup)
   4167 	  (pcase (assoc-string option org-startup-options t)
   4168 	    (`(,_ ,variable ,value t)
   4169 	     (unless (listp (symbol-value variable))
   4170 	       (set (make-local-variable variable) nil))
   4171 	     (add-to-list variable value))
   4172 	    (`(,_ ,variable ,value . ,_)
   4173 	     (set (make-local-variable variable) value))
   4174 	    (_ nil))))
   4175       (setq-local org-file-tags
   4176 		  (mapcar #'org-add-prop-inherited
   4177 			  (cl-mapcan (lambda (value)
   4178 				       (cl-mapcan
   4179 					(lambda (k) (org-split-string k ":"))
   4180 					(split-string value)))
   4181 				     (cdr (assoc "FILETAGS" alist)))))
   4182       (setq org-current-tag-alist
   4183 	    (org--tag-add-to-alist
   4184 	     org-tag-persistent-alist
   4185 	     (let ((tags (cdr (assoc "TAGS" alist))))
   4186 	       (if tags
   4187 		   (org-tag-string-to-alist
   4188 		    (mapconcat #'identity tags "\n"))
   4189 		 org-tag-alist))))
   4190       (setq org-tag-groups-alist
   4191 	    (org-tag-alist-to-groups org-current-tag-alist))
   4192       (unless tags-only
   4193 	;; Properties.
   4194 	(let ((properties nil))
   4195 	  (dolist (value (cdr (assoc "PROPERTY" alist)))
   4196 	    (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
   4197 	      (setq properties (org--update-property-plist
   4198 				(match-string-no-properties 1 value)
   4199 				(match-string-no-properties 2 value)
   4200 				properties))))
   4201 	  (setq-local org-keyword-properties properties))
   4202 	;; Archive location.
   4203 	(let ((archive (cdr (assoc "ARCHIVE" alist))))
   4204 	  (when archive (setq-local org-archive-location archive)))
   4205 	;; Category.
   4206 	(let ((category (cdr (assoc "CATEGORY" alist))))
   4207 	  (when category
   4208 	    (setq-local org-category (intern category))
   4209 	    (setq-local org-keyword-properties
   4210 			(org--update-property-plist
   4211 			 "CATEGORY" category org-keyword-properties))))
   4212 	;; Columns.
   4213 	(let ((column (cdr (assoc "COLUMNS" alist))))
   4214 	  (when column (setq-local org-columns-default-format column)))
   4215 	;; Constants.
   4216 	(let ((store nil))
   4217 	  (dolist (pair (cl-mapcan #'split-string
   4218 				   (cdr (assoc "CONSTANTS" alist))))
   4219 	    (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" pair)
   4220 	      (let* ((name (match-string 1 pair))
   4221 		     (value (match-string 2 pair))
   4222 		     (old (assoc name store)))
   4223 		(if old (setcdr old value)
   4224 		  (push (cons name value) store)))))
   4225 	  (setq org-table-formula-constants-local store))
   4226 	;; Link abbreviations.
   4227 	(let ((links
   4228 	       (delq nil
   4229 		     (mapcar
   4230 		      (lambda (value)
   4231 			(and (or
   4232                               ;; "abbrev with spaces" spec
   4233                               (string-match "\\`\"\\(.+[^\\]\\)\"[ \t]+\\(.+\\)" value)
   4234                               ;; abbrev spec
   4235                               (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value))
   4236 			     (cons (match-string-no-properties 1 value)
   4237 				   (match-string-no-properties 2 value))))
   4238 		      (cdr (assoc "LINK" alist))))))
   4239 	  (when links (setq org-link-abbrev-alist-local (nreverse links))))
   4240 	;; Priorities.
   4241 	(let ((value (cdr (assoc "PRIORITIES" alist))))
   4242 	  (pcase (and value (split-string value))
   4243 	    (`(,high ,low ,default . ,_)
   4244 	     (setq-local org-priority-highest (org-priority-to-value high))
   4245 	     (setq-local org-priority-lowest (org-priority-to-value low))
   4246 	     (setq-local org-priority-default (org-priority-to-value default)))))
   4247 	;; Scripts.
   4248 	(let ((value (cdr (assoc "OPTIONS" alist))))
   4249 	  (dolist (option value)
   4250 	    (when (string-match "\\^:\\(t\\|nil\\|{}\\)" option)
   4251 	      (setq-local org-use-sub-superscripts
   4252 			  (read (match-string 1 option))))))
   4253 	;; TODO keywords.
   4254 	(setq-local org-todo-kwd-alist nil)
   4255 	(setq-local org-todo-key-alist nil)
   4256 	(setq-local org-todo-key-trigger nil)
   4257 	(setq-local org-todo-keywords-1 nil)
   4258 	(setq-local org-done-keywords nil)
   4259 	(setq-local org-todo-heads nil)
   4260 	(setq-local org-todo-sets nil)
   4261 	(setq-local org-todo-log-states nil)
   4262 	(let ((todo-sequences
   4263 	       (or (append (mapcar (lambda (value)
   4264 				     (cons 'type (split-string value)))
   4265 				   (cdr (assoc "TYP_TODO" alist)))
   4266 			   (mapcar (lambda (value)
   4267 				     (cons 'sequence (split-string value)))
   4268 				   (append (cdr (assoc "TODO" alist))
   4269 					   (cdr (assoc "SEQ_TODO" alist)))))
   4270 		   (let ((d (default-value 'org-todo-keywords)))
   4271 		     (if (not (stringp (car d))) d
   4272 		       ;; XXX: Backward compatibility code.
   4273 		       (list (cons org-todo-interpretation d)))))))
   4274 	  (dolist (sequence todo-sequences)
   4275 	    (let* ((sequence (or (run-hook-with-args-until-success
   4276 				  'org-todo-setup-filter-hook sequence)
   4277 				 sequence))
   4278 		   (sequence-type (car sequence))
   4279 		   (keywords (cdr sequence))
   4280 		   (sep (member "|" keywords))
   4281 		   names alist)
   4282 	      (dolist (k (remove "|" keywords))
   4283 		(unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
   4284 				      k)
   4285 		  (error "Invalid TODO keyword %s" k))
   4286 		(let ((name (match-string 1 k))
   4287 		      (key (match-string 2 k))
   4288 		      (log (org-extract-log-state-settings k)))
   4289 		  (push name names)
   4290 		  (push (cons name (and key (string-to-char key))) alist)
   4291 		  (when log (push log org-todo-log-states))))
   4292 	      (let* ((names (nreverse names))
   4293 		     (done (if sep (org-remove-keyword-keys (cdr sep))
   4294 			     (last names)))
   4295 		     (head (car names))
   4296 		     (tail (list sequence-type head (car done) (org-last done))))
   4297 		(add-to-list 'org-todo-heads head 'append)
   4298 		(push names org-todo-sets)
   4299 		(setq org-done-keywords (append org-done-keywords done nil))
   4300 		(setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
   4301 		(setq org-todo-key-alist
   4302 		      (append org-todo-key-alist
   4303 			      (and alist
   4304 				   (append '((:startgroup))
   4305 					   (nreverse alist)
   4306 					   '((:endgroup))))))
   4307 		(dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
   4308 	(setq org-todo-sets (nreverse org-todo-sets)
   4309 	      org-todo-kwd-alist (nreverse org-todo-kwd-alist)
   4310 	      org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
   4311 	      org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
   4312 	;; Compute the regular expressions and other local variables.
   4313 	;; Using `org-outline-regexp-bol' would complicate them much,
   4314 	;; because of the fixed white space at the end of that string.
   4315 	(unless org-done-keywords
   4316 	  (setq org-done-keywords
   4317 		(and org-todo-keywords-1 (last org-todo-keywords-1))))
   4318 	(setq org-not-done-keywords
   4319 	      (org-delete-all org-done-keywords
   4320 			      (copy-sequence org-todo-keywords-1))
   4321 	      org-todo-regexp (regexp-opt org-todo-keywords-1 t)
   4322 	      org-not-done-regexp (regexp-opt org-not-done-keywords t)
   4323 	      org-not-done-heading-regexp
   4324 	      (format org-heading-keyword-regexp-format org-not-done-regexp)
   4325 	      org-todo-line-regexp
   4326 	      (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
   4327 	      org-complex-heading-regexp
   4328 	      (concat "^\\(\\*+\\)"
   4329 		      "\\(?: +" org-todo-regexp "\\)?"
   4330 		      "\\(?: +\\(\\[#.\\]\\)\\)?"
   4331 		      "\\(?: +\\(.*?\\)\\)??"
   4332 		      "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
   4333 		      "[ \t]*$")
   4334 	      org-complex-heading-regexp-format
   4335 	      (concat "^\\(\\*+\\)"
   4336 		      "\\(?: +" org-todo-regexp "\\)?"
   4337 		      "\\(?: +\\(\\[#.\\]\\)\\)?"
   4338 		      "\\(?: +"
   4339                       ;; Headline might be commented
   4340                       "\\(?:" org-comment-string " +\\)?"
   4341 		      ;; Stats cookies can be stuck to body.
   4342 		      "\\(?:\\[[0-9%%/]+\\] *\\)*"
   4343 		      "\\(%s\\)"
   4344 		      "\\(?: *\\[[0-9%%/]+\\]\\)*"
   4345 		      "\\)"
   4346 		      "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
   4347 		      "[ \t]*$")
   4348 	      org-todo-line-tags-regexp
   4349 	      (concat "^\\(\\*+\\)"
   4350 		      "\\(?: +" org-todo-regexp "\\)?"
   4351 		      "\\(?: +\\(.*?\\)\\)??"
   4352 		      "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
   4353 		      "[ \t]*$"))
   4354 	(org-compute-latex-and-related-regexp)))))
   4355 
   4356 (defun org-collect-keywords (keywords &optional unique directory)
   4357   "Return values for KEYWORDS in current buffer, as an alist.
   4358 
   4359 KEYWORDS is a list of strings.  Return value is a list of
   4360 elements with the pattern:
   4361 
   4362   (NAME . LIST-OF-VALUES)
   4363 
   4364 where NAME is the upcase name of the keyword, and LIST-OF-VALUES
   4365 is a list of non-empty values, as strings, in order of appearance
   4366 in the buffer.
   4367 
   4368 When KEYWORD appears in UNIQUE list, LIST-OF-VALUE is its first
   4369 value, empty or not, appearing in the buffer, as a string.
   4370 
   4371 When KEYWORD appears in DIRECTORIES, each value is a cons cell:
   4372 
   4373   (VALUE . DIRECTORY)
   4374 
   4375 where VALUE is the regular value, and DIRECTORY is the variable
   4376 `default-directory' for the buffer containing the keyword.  This
   4377 is important for values containing relative file names, since the
   4378 function follows SETUPFILE keywords, and may change its working
   4379 directory."
   4380   (let* ((keywords (cons "SETUPFILE" (mapcar #'upcase keywords)))
   4381 	 (unique (mapcar #'upcase unique))
   4382 	 (alist (org--collect-keywords-1
   4383 		 keywords unique directory
   4384 		 (and buffer-file-name (list buffer-file-name))
   4385 		 nil)))
   4386     ;; Re-order results.
   4387     (dolist (entry alist)
   4388       (pcase entry
   4389 	(`(,_ . ,(and value (pred consp)))
   4390 	 (setcdr entry (nreverse value)))))
   4391     (nreverse alist)))
   4392 
   4393 (defun org--collect-keywords-1 (keywords unique directory files alist)
   4394   (org-with-point-at 1
   4395     (let ((case-fold-search t)
   4396 	  (regexp (org-make-options-regexp keywords)))
   4397       (while (and keywords (re-search-forward regexp nil t))
   4398         (let ((element (org-element-at-point)))
   4399           (when (eq 'keyword (org-element-type element))
   4400             (let ((value (org-element-property :value element)))
   4401               (pcase (org-element-property :key element)
   4402 		("SETUPFILE"
   4403 		 (when (and (org-string-nw-p value)
   4404 			    (not buffer-read-only)) ;FIXME: bug in Gnus?
   4405 		   (let* ((uri (org-strip-quotes value))
   4406 			  (uri-is-url (org-url-p uri))
   4407 			  (uri (if uri-is-url
   4408 				   uri
   4409 				 (expand-file-name uri))))
   4410 		     (unless (member uri files)
   4411 		       (with-temp-buffer
   4412 			 (unless uri-is-url
   4413 			   (setq default-directory (file-name-directory uri)))
   4414 			 (let ((contents (org-file-contents uri :noerror)))
   4415 			   (when contents
   4416 			     (insert contents)
   4417 			     ;; Fake Org mode: `org-element-at-point'
   4418 			     ;; doesn't need full set-up.
   4419 			     (let ((major-mode 'org-mode))
   4420 			       (setq alist
   4421 				     (org--collect-keywords-1
   4422 				      keywords unique directory
   4423 				      (cons uri files)
   4424 				      alist))))))))))
   4425 		(keyword
   4426 		 (let ((entry (assoc keyword alist))
   4427 		       (final
   4428 			(cond ((not (member keyword directory)) value)
   4429 			      (buffer-file-name
   4430 			       (cons value
   4431 				     (file-name-directory buffer-file-name)))
   4432 			      (t (cons value default-directory)))))
   4433 		   (cond ((member keyword unique)
   4434 			  (push (cons keyword final) alist)
   4435 			  (setq keywords (remove keyword keywords))
   4436 			  (setq regexp (org-make-options-regexp keywords)))
   4437 			 ((null entry) (push (list keyword final) alist))
   4438 			 (t (push final (cdr entry)))))))))))
   4439       alist)))
   4440 
   4441 (defun org-tag-string-to-alist (s)
   4442   "Return tag alist associated to string S.
   4443 S is a value for TAGS keyword or produced with
   4444 `org-tag-alist-to-string'.  Return value is an alist suitable for
   4445 `org-tag-alist' or `org-tag-persistent-alist'."
   4446   (let ((lines (mapcar #'split-string (split-string s "\n" t)))
   4447 	(tag-re (concat "\\`\\(" org-tag-re "\\|{.+?}\\)" ; regular expression
   4448 			"\\(?:(\\(.\\))\\)?\\'"))
   4449 	alist group-flag)
   4450     (dolist (tokens lines (cdr (nreverse alist)))
   4451       (push '(:newline) alist)
   4452       (while tokens
   4453 	(let ((token (pop tokens)))
   4454 	  (pcase token
   4455 	    ("{"
   4456 	     (push '(:startgroup) alist)
   4457 	     (when (equal (nth 1 tokens) ":") (setq group-flag t)))
   4458 	    ("}"
   4459 	     (push '(:endgroup) alist)
   4460 	     (setq group-flag nil))
   4461 	    ("["
   4462 	     (push '(:startgrouptag) alist)
   4463 	     (when (equal (nth 1 tokens) ":") (setq group-flag t)))
   4464 	    ("]"
   4465 	     (push '(:endgrouptag) alist)
   4466 	     (setq group-flag nil))
   4467 	    (":"
   4468 	     (push '(:grouptags) alist))
   4469 	    ((guard (string-match tag-re token))
   4470 	     (let ((tag (match-string 1 token))
   4471 		   (key (and (match-beginning 2)
   4472 			     (string-to-char (match-string 2 token)))))
   4473 	       ;; Push all tags in groups, no matter if they already
   4474 	       ;; appear somewhere else in the list.
   4475 	       (when (or group-flag (not (assoc tag alist)))
   4476 		 (push (cons tag key) alist))))))))))
   4477 
   4478 (defun org-tag-alist-to-string (alist &optional skip-key)
   4479   "Return tag string associated to ALIST.
   4480 
   4481 ALIST is an alist, as defined in `org-tag-alist' or
   4482 `org-tag-persistent-alist', or produced with
   4483 `org-tag-string-to-alist'.
   4484 
   4485 Return value is a string suitable as a value for \"TAGS\"
   4486 keyword.
   4487 
   4488 When optional argument SKIP-KEY is non-nil, skip selection keys
   4489 next to tags."
   4490   (mapconcat (lambda (token)
   4491 	       (pcase token
   4492 		 (`(:startgroup) "{")
   4493 		 (`(:endgroup) "}")
   4494 		 (`(:startgrouptag) "[")
   4495 		 (`(:endgrouptag) "]")
   4496 		 (`(:grouptags) ":")
   4497 		 (`(:newline) "\\n")
   4498 		 ((and
   4499 		   (guard (not skip-key))
   4500 		   `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
   4501 		  (format "%s(%c)" tag key))
   4502 		 (`(,(and tag (pred stringp)) . ,_) tag)
   4503 		 (_ (user-error "Invalid tag token: %S" token))))
   4504 	     alist
   4505 	     " "))
   4506 
   4507 (defun org-tag-alist-to-groups (alist)
   4508   "Return group alist from tag ALIST.
   4509 ALIST is an alist, as defined in `org-tag-alist' or
   4510 `org-tag-persistent-alist', or produced with
   4511 `org-tag-string-to-alist'.  Return value is an alist following
   4512 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
   4513 a string, summarizing TAGS, as a list of strings."
   4514   (let (groups group-status current-group)
   4515     (dolist (token alist (nreverse groups))
   4516       (pcase token
   4517 	(`(,(or :startgroup :startgrouptag)) (setq group-status t))
   4518 	(`(,(or :endgroup :endgrouptag))
   4519 	 (when (eq group-status 'append)
   4520 	   (push (nreverse current-group) groups))
   4521 	 (setq group-status nil current-group nil))
   4522 	(`(:grouptags) (setq group-status 'append))
   4523 	((and `(,tag . ,_) (guard group-status))
   4524 	 (if (eq group-status 'append) (push tag current-group)
   4525 	   (setq current-group (list tag))))
   4526 	(_ nil)))))
   4527 
   4528 (defvar org--file-cache (make-hash-table :test #'equal)
   4529   "Hash table to store contents of files referenced via a URL.
   4530 This is the cache of file URLs read using `org-file-contents'.")
   4531 
   4532 (defun org-reset-file-cache ()
   4533   "Reset the cache of files downloaded by `org-file-contents'."
   4534   (clrhash org--file-cache))
   4535 
   4536 (defun org-file-contents (file &optional noerror nocache)
   4537   "Return the contents of FILE, as a string.
   4538 
   4539 FILE can be a file name or URL.
   4540 
   4541 If FILE is a URL, download the contents.  If the URL contents are
   4542 already cached in the `org--file-cache' hash table, the download step
   4543 is skipped.
   4544 
   4545 If NOERROR is non-nil, ignore the error when unable to read the FILE
   4546 from file or URL, and return nil.
   4547 
   4548 If NOCACHE is non-nil, do a fresh fetch of FILE even if cached version
   4549 is available.  This option applies only if FILE is a URL."
   4550   (let* ((is-url (org-url-p file))
   4551          (cache (and is-url
   4552                      (not nocache)
   4553                      (gethash file org--file-cache))))
   4554     (cond
   4555      (cache)
   4556      (is-url
   4557       (if (org--should-fetch-remote-resource-p file)
   4558           (with-current-buffer (url-retrieve-synchronously file)
   4559             (goto-char (point-min))
   4560             ;; Move point to after the url-retrieve header.
   4561             (search-forward "\n\n" nil :move)
   4562             ;; Search for the success code only in the url-retrieve header.
   4563             (if (save-excursion
   4564                   (re-search-backward "HTTP.*\\s-+200\\s-OK" nil :noerror))
   4565                 ;; Update the cache `org--file-cache' and return contents.
   4566                 (puthash file
   4567                          (buffer-substring-no-properties (point) (point-max))
   4568                          org--file-cache)
   4569               (funcall (if noerror #'message #'user-error)
   4570                        "Unable to fetch file from %S"
   4571                        file)
   4572               nil))
   4573         (funcall (if noerror #'message #'user-error)
   4574                  "The remote resource %S is considered unsafe, and will not be downloaded."
   4575                  file)))
   4576      (t
   4577       (with-temp-buffer
   4578         (condition-case nil
   4579 	    (progn
   4580 	      (insert-file-contents file)
   4581 	      (buffer-string))
   4582 	  (file-error
   4583            (funcall (if noerror #'message #'user-error)
   4584 		    "Unable to read file %S"
   4585 		    file)
   4586 	   nil)))))))
   4587 
   4588 (defun org--should-fetch-remote-resource-p (uri)
   4589   "Return non-nil if the URI should be fetched."
   4590   (or (eq org-resource-download-policy t)
   4591       (org--safe-remote-resource-p uri)
   4592       (and (eq org-resource-download-policy 'prompt)
   4593            (org--confirm-resource-safe uri))))
   4594 
   4595 (defun org--safe-remote-resource-p (uri)
   4596   "Return non-nil if URI is considered safe.
   4597 This checks every pattern in `org-safe-remote-resources', and
   4598 returns non-nil if any of them match."
   4599   (let ((uri-patterns org-safe-remote-resources)
   4600         (file-uri (and (buffer-file-name (buffer-base-buffer))
   4601                        (concat "file://" (file-truename (buffer-file-name (buffer-base-buffer))))))
   4602         match-p)
   4603     (while (and (not match-p) uri-patterns)
   4604       (setq match-p (or (string-match-p (car uri-patterns) uri)
   4605                         (and file-uri (string-match-p (car uri-patterns) file-uri)))
   4606             uri-patterns (cdr uri-patterns)))
   4607     match-p))
   4608 
   4609 (defun org--confirm-resource-safe (uri)
   4610   "Ask the user if URI should be considered safe, returning non-nil if so."
   4611   (unless noninteractive
   4612     (let ((current-file (and (buffer-file-name (buffer-base-buffer))
   4613                              (file-truename (buffer-file-name (buffer-base-buffer)))))
   4614           (domain (and (string-match
   4615                         (rx (seq "http" (? "s") "://")
   4616                             (optional (+ (not (any "@/\n"))) "@")
   4617                             (optional "www.")
   4618                             (one-or-more (not (any ":/?\n"))))
   4619                         uri)
   4620                        (match-string 0 uri)))
   4621           (buf (get-buffer-create "*Org Remote Resource*")))
   4622       ;; Set up the contents of the *Org Remote Resource* buffer.
   4623       (with-current-buffer buf
   4624         (erase-buffer)
   4625         (insert "An org-mode document would like to download "
   4626                 (propertize uri 'face '(:inherit org-link :weight normal))
   4627                 ", which is not considered safe.\n\n"
   4628                 "Do you want to download this?  You can type\n "
   4629                 (propertize "!" 'face 'success)
   4630                 " to download this resource, and permanently mark it as safe.\n "
   4631                 (if domain
   4632                     (concat
   4633                      (propertize "d" 'face 'success)
   4634                      " to download this resource, and mark the domain ("
   4635                      (propertize domain 'face '(:inherit org-link :weight normal))
   4636                      ") as safe.\n ")
   4637                   "")
   4638                 (propertize "f" 'face 'success)
   4639                 (if current-file
   4640                     (concat
   4641                      " to download this resource, and permanently mark all resources in "
   4642                      (propertize current-file 'face 'underline)
   4643                      " as safe.\n ")
   4644                   "")
   4645                 (propertize "y" 'face 'warning)
   4646                 " to download this resource, just this once.\n "
   4647                 (propertize "n" 'face 'error)
   4648                 " to skip this resource.\n")
   4649         (setq-local cursor-type nil)
   4650         (set-buffer-modified-p nil)
   4651         (goto-char (point-min)))
   4652       ;; Display the buffer and read a choice.
   4653       (save-window-excursion
   4654         (pop-to-buffer buf)
   4655         (let* ((exit-chars (append '(?y ?n ?! ?d ?\s) (and current-file '(?f))))
   4656                (prompt (format "Please type y, n%s, d, or !%s: "
   4657                                (if current-file ", f" "")
   4658                                (if (< (line-number-at-pos (point-max))
   4659                                       (window-body-height))
   4660                                    ""
   4661                                  ", or C-v/M-v to scroll")))
   4662                char)
   4663           (setq char (read-char-choice prompt exit-chars))
   4664           (when (memq char '(?! ?f ?d))
   4665             (customize-push-and-save
   4666              'org-safe-remote-resources
   4667              (list (if (eq char ?d)
   4668                        (concat "\\`" (regexp-quote domain) "\\(?:/\\|\\'\\)")
   4669                      (concat "\\`"
   4670                              (regexp-quote
   4671                               (if (and (= char ?f) current-file)
   4672                                   (concat "file://" current-file) uri))
   4673                              "\\'")))))
   4674           (prog1 (memq char '(?y ?n ?! ?d ?\s ?f))
   4675             (quit-window t)))))))
   4676 
   4677 (defun org-extract-log-state-settings (x)
   4678   "Extract the log state setting from a TODO keyword string.
   4679 This will extract info from a string like \"WAIT(w@/!)\"."
   4680   (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
   4681     (let ((kw (match-string 1 x))
   4682 	  (log1 (and (match-end 3) (match-string 3 x)))
   4683 	  (log2 (and (match-end 4) (match-string 4 x))))
   4684       (and (or log1 log2)
   4685 	   (list kw
   4686 		 (and log1 (if (equal log1 "!") 'time 'note))
   4687 		 (and log2 (if (equal log2 "!") 'time 'note)))))))
   4688 
   4689 (defun org-remove-keyword-keys (list)
   4690   "Remove a pair of parenthesis at the end of each string in LIST."
   4691   (mapcar (lambda (x)
   4692 	    (if (string-match "(.*)$" x)
   4693 		(substring x 0 (match-beginning 0))
   4694 	      x))
   4695 	  list))
   4696 
   4697 (defun org-assign-fast-keys (alist)
   4698   "Assign fast keys to a keyword-key alist.
   4699 Respect keys that are already there."
   4700   (let (new e (alt ?0))
   4701     (while (setq e (pop alist))
   4702       (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
   4703 	      (cdr e)) ;; Key already assigned.
   4704 	  (push e new)
   4705 	(let ((clist (string-to-list (downcase (car e))))
   4706 	      (used (append new alist)))
   4707 	  (when (= (car clist) ?@)
   4708 	    (pop clist))
   4709 	  (while (and clist (rassoc (car clist) used))
   4710 	    (pop clist))
   4711 	  (unless clist
   4712 	    (while (rassoc alt used)
   4713 	      (cl-incf alt)))
   4714 	  (push (cons (car e) (or (car clist) alt)) new))))
   4715     (nreverse new)))
   4716 
   4717 ;;; Some variables used in various places
   4718 
   4719 (defvar org-window-configuration nil
   4720   "Used in various places to store a window configuration.")
   4721 (defvar org-selected-window nil
   4722   "Used in various places to store a window configuration.")
   4723 (defvar org-finish-function nil
   4724   "Function to be called when `C-c C-c' is used.
   4725 This is for getting out of special buffers like capture.")
   4726 (defvar org-last-state)
   4727 
   4728 ;; Defined somewhere in this file, but used before definition.
   4729 (defvar org-entities)     ;; defined in org-entities.el
   4730 (defvar org-struct-menu)
   4731 (defvar org-org-menu)
   4732 (defvar org-tbl-menu)
   4733 
   4734 ;;;; Define the Org mode
   4735 
   4736 (defun org-before-change-function (_beg _end)
   4737   "Every change indicates that a table might need an update."
   4738   (setq org-table-may-need-update t))
   4739 (defvar org-mode-map)
   4740 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
   4741 (defvar org-agenda-keep-modes nil)      ; Dynamically-scoped param.
   4742 (defvar org-inhibit-logging nil)        ; Dynamically-scoped param.
   4743 (defvar org-inhibit-blocking nil)       ; Dynamically-scoped param.
   4744 
   4745 (defvar bidi-paragraph-direction)
   4746 (defvar buffer-face-mode-face)
   4747 
   4748 (require 'outline)
   4749 
   4750 ;; Other stuff we need.
   4751 (require 'time-date)
   4752 (when (< emacs-major-version 28)  ; preloaded in Emacs 28
   4753   (require 'easymenu))
   4754 
   4755 (require 'org-entities)
   4756 (require 'org-faces)
   4757 (require 'org-list)
   4758 (require 'org-pcomplete)
   4759 (require 'org-src)
   4760 (require 'org-footnote)
   4761 (require 'org-macro)
   4762 
   4763 ;; babel
   4764 (require 'ob)
   4765 
   4766 (defvar org-element-cache-persistent); Defined in org-element.el
   4767 (defvar org-element-use-cache); Defined in org-element.el
   4768 (defvar org-mode-loading nil
   4769   "Non-nil during Org mode initialization.")
   4770 
   4771 (defvar org-agenda-file-menu-enabled t
   4772   "When non-nil, refresh Agenda files in Org menu when loading Org.")
   4773 
   4774 ;;;###autoload
   4775 (define-derived-mode org-mode outline-mode "Org"
   4776   "Outline-based notes management and organizer, alias
   4777 \"Carsten's outline-mode for keeping track of everything.\"
   4778 
   4779 Org mode develops organizational tasks around a NOTES file which
   4780 contains information about projects as plain text.  Org mode is
   4781 implemented on top of Outline mode, which is ideal to keep the content
   4782 of large files well structured.  It supports ToDo items, deadlines and
   4783 time stamps, which magically appear in the diary listing of the Emacs
   4784 calendar.  Tables are easily created with a built-in table editor.
   4785 Plain text URL-like links connect to websites, emails (VM), Usenet
   4786 messages (Gnus), BBDB entries, and any files related to the project.
   4787 For printing and sharing of notes, an Org file (or a part of it)
   4788 can be exported as a structured ASCII or HTML file.
   4789 
   4790 The following commands are available:
   4791 
   4792 \\{org-mode-map}"
   4793   (setq-local org-mode-loading t)
   4794   (org-load-modules-maybe)
   4795   (when org-agenda-file-menu-enabled
   4796     (org-install-agenda-files-menu))
   4797   (when (and org-link-descriptive
   4798              (eq org-fold-core-style 'overlays))
   4799     (add-to-invisibility-spec '(org-link)))
   4800   (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
   4801                         "..."))
   4802   (make-local-variable 'org-link-descriptive)
   4803   (when (eq org-fold-core-style 'overlays) (add-to-invisibility-spec '(org-hide-block . t)))
   4804   (if org-link-descriptive
   4805       (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible nil)
   4806     (org-fold-core-set-folding-spec-property (car org-link--link-folding-spec) :visible t))
   4807   (setq-local outline-regexp org-outline-regexp)
   4808   (setq-local outline-level 'org-outline-level)
   4809   (when (and (stringp org-ellipsis) (not (equal "" org-ellipsis)))
   4810     (unless org-display-table
   4811       (setq org-display-table (make-display-table)))
   4812     (set-display-table-slot
   4813      org-display-table 4
   4814      (vconcat (mapcar (lambda (c) (make-glyph-code c 'org-ellipsis))
   4815 		      org-ellipsis)))
   4816     (setq buffer-display-table org-display-table))
   4817   (org-set-regexps-and-options)
   4818   (org-set-font-lock-defaults)
   4819   (when (and org-tag-faces (not org-tags-special-faces-re))
   4820     ;; tag faces set outside customize.... force initialization.
   4821     (org-set-tag-faces 'org-tag-faces org-tag-faces))
   4822   ;; Calc embedded
   4823   (setq-local calc-embedded-open-mode "# ")
   4824   ;; Modify a few syntax entries
   4825   (modify-syntax-entry ?\" "\"")
   4826   (modify-syntax-entry ?\\ "_")
   4827   (modify-syntax-entry ?~ "_")
   4828   (modify-syntax-entry ?< "(>")
   4829   (modify-syntax-entry ?> ")<")
   4830   (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
   4831   ;; Activate before-change-function
   4832   (setq-local org-table-may-need-update t)
   4833   (add-hook 'before-change-functions 'org-before-change-function nil 'local)
   4834   ;; Check for running clock before killing a buffer
   4835   (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
   4836   ;; Initialize cache.
   4837   (org-element-cache-reset)
   4838   (when (and org-element-cache-persistent
   4839              org-element-use-cache)
   4840     (org-persist-load 'org-element--cache (current-buffer) t))
   4841   ;; Initialize macros templates.
   4842   (org-macro-initialize-templates)
   4843   ;; Initialize radio targets.
   4844   (org-update-radio-target-regexp)
   4845   ;; Indentation.
   4846   (setq-local indent-line-function 'org-indent-line)
   4847   (setq-local indent-region-function 'org-indent-region)
   4848   ;; Filling and auto-filling.
   4849   (org-setup-filling)
   4850   ;; Comments.
   4851   (org-setup-comments-handling)
   4852   ;; Beginning/end of defun
   4853   (setq-local beginning-of-defun-function 'org-backward-element)
   4854   (setq-local end-of-defun-function
   4855 	      (lambda ()
   4856 		(if (not (org-at-heading-p))
   4857 		    (org-forward-element)
   4858 		  (org-forward-element)
   4859 		  (forward-char -1))))
   4860   ;; Next error for sparse trees
   4861   (setq-local next-error-function 'org-occur-next-match)
   4862   ;; Make commit log messages from Org documents easier.
   4863   (setq-local add-log-current-defun-function #'org-add-log-current-headline)
   4864   ;; Make sure dependence stuff works reliably, even for users who set it
   4865   ;; too late :-(
   4866   (if org-enforce-todo-dependencies
   4867       (add-hook 'org-blocker-hook
   4868 		'org-block-todo-from-children-or-siblings-or-parent)
   4869     (remove-hook 'org-blocker-hook
   4870 		 'org-block-todo-from-children-or-siblings-or-parent))
   4871   (if org-enforce-todo-checkbox-dependencies
   4872       (add-hook 'org-blocker-hook
   4873 		'org-block-todo-from-checkboxes)
   4874     (remove-hook 'org-blocker-hook
   4875 		 'org-block-todo-from-checkboxes))
   4876 
   4877   ;; Align options lines
   4878   (setq-local
   4879    align-mode-rules-list
   4880    '((org-in-buffer-settings
   4881       (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
   4882       (modes . '(org-mode)))))
   4883 
   4884   ;; Setup the pcomplete hooks
   4885   (setq-local pcomplete-command-completion-function #'org-pcomplete-initial)
   4886   (setq-local pcomplete-command-name-function #'org-command-at-point)
   4887   (setq-local pcomplete-default-completion-function #'ignore)
   4888   (setq-local pcomplete-parse-arguments-function #'org-parse-arguments)
   4889   (setq-local pcomplete-termination-string "")
   4890   (add-hook 'completion-at-point-functions
   4891             #'pcomplete-completions-at-point nil t)
   4892   (setq-local buffer-face-mode-face 'org-default)
   4893 
   4894   ;; If empty file that did not turn on Org mode automatically, make
   4895   ;; it to.
   4896   (when (and org-insert-mode-line-in-empty-file
   4897 	     (called-interactively-p 'any)
   4898 	     (= (point-min) (point-max)))
   4899     (insert "#    -*- mode: org -*-\n\n"))
   4900   (unless org-inhibit-startup
   4901     (when (or org-startup-align-all-tables org-startup-shrink-all-tables)
   4902       (org-table-map-tables
   4903        (cond ((and org-startup-align-all-tables
   4904 		   org-startup-shrink-all-tables)
   4905 	      (lambda () (org-table-align) (org-table-shrink)))
   4906 	     (org-startup-align-all-tables #'org-table-align)
   4907 	     (t #'org-table-shrink))
   4908        t))
   4909     ;; Suppress modification hooks to speed up the startup.
   4910     ;; However, do it only when text properties/overlays, but not
   4911     ;; buffer text are actually modified.  We still need to track text
   4912     ;; modifications to make cache updates work reliably.
   4913     (org-unmodified
   4914      (when org-startup-with-beamer-mode (org-beamer-mode))
   4915      (when org-startup-with-inline-images (org-display-inline-images))
   4916      (when org-startup-with-latex-preview (org-latex-preview '(16)))
   4917      (unless org-inhibit-startup-visibility-stuff (org-cycle-set-startup-visibility))
   4918      (when org-startup-truncated (setq truncate-lines t))
   4919      (when org-startup-numerated (require 'org-num) (org-num-mode 1))
   4920      (when org-startup-indented (require 'org-indent) (org-indent-mode 1))))
   4921 
   4922   ;; Add a custom keymap for `visual-line-mode' so that activating
   4923   ;; this minor mode does not override Org's keybindings.
   4924   ;; FIXME: Probably `visual-line-mode' should take care of this.
   4925   (let ((oldmap (cdr (assoc 'visual-line-mode minor-mode-map-alist)))
   4926         (newmap (make-sparse-keymap)))
   4927     (set-keymap-parent newmap oldmap)
   4928     (define-key newmap [remap move-beginning-of-line] nil)
   4929     (define-key newmap [remap move-end-of-line] nil)
   4930     (define-key newmap [remap kill-line] nil)
   4931     (make-local-variable 'minor-mode-overriding-map-alist)
   4932     (push `(visual-line-mode . ,newmap) minor-mode-overriding-map-alist))
   4933 
   4934   ;; Activate `org-table-header-line-mode'
   4935   (when org-table-header-line-p
   4936     (org-table-header-line-mode 1))
   4937   ;; Try to set `org-hide' face correctly.
   4938   (let ((foreground (org-find-invisible-foreground)))
   4939     (when foreground
   4940       (set-face-foreground 'org-hide foreground)))
   4941   ;; Set face extension as requested.
   4942   (org--set-faces-extend '(org-block-begin-line org-block-end-line)
   4943                          org-fontify-whole-block-delimiter-line)
   4944   (org--set-faces-extend org-level-faces org-fontify-whole-heading-line)
   4945   (setq-local org-mode-loading nil))
   4946 
   4947 ;; Update `customize-package-emacs-version-alist'
   4948 (add-to-list 'customize-package-emacs-version-alist
   4949 	     '(Org ("8.0" . "24.4")
   4950 		   ("8.1" . "24.4")
   4951 		   ("8.2" . "24.4")
   4952 		   ("8.2.7" . "24.4")
   4953 		   ("8.3" . "26.1")
   4954 		   ("9.0" . "26.1")
   4955 		   ("9.1" . "26.1")
   4956 		   ("9.2" . "27.1")
   4957 		   ("9.3" . "27.1")
   4958 		   ("9.4" . "27.2")
   4959 		   ("9.5" . "28.1")
   4960 		   ("9.6" . "29.1")))
   4961 
   4962 (defvar org-mode-transpose-word-syntax-table
   4963   (let ((st (make-syntax-table text-mode-syntax-table)))
   4964     (dolist (c org-emphasis-alist st)
   4965       (modify-syntax-entry (string-to-char (car c)) "w p" st))))
   4966 
   4967 (when (fboundp 'abbrev-table-put)
   4968   (abbrev-table-put org-mode-abbrev-table
   4969 		    :parents (list text-mode-abbrev-table)))
   4970 
   4971 (defun org-find-invisible-foreground ()
   4972   (let ((candidates (remove
   4973 		     "unspecified-bg"
   4974 		     (nconc
   4975 		      (list (face-background 'default)
   4976 			    (face-background 'org-default))
   4977 		      (mapcar
   4978 		       (lambda (alist)
   4979 			 (when (boundp alist)
   4980 			   (cdr (assq 'background-color (symbol-value alist)))))
   4981 		       '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
   4982 		      (list (face-foreground 'org-hide))))))
   4983     (car (remove nil candidates))))
   4984 
   4985 (defun org-current-time (&optional rounding-minutes past)
   4986   "Current time, possibly rounded to ROUNDING-MINUTES.
   4987 When ROUNDING-MINUTES is not an integer, fall back on the car of
   4988 `org-time-stamp-rounding-minutes'.  When PAST is non-nil, ensure
   4989 the rounding returns a past time."
   4990   (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
   4991 	       (car org-time-stamp-rounding-minutes)))
   4992 	(now (current-time)))
   4993     (if (< r 1)
   4994 	now
   4995       (let* ((time (decode-time now))
   4996 	     (res (org-encode-time
   4997                    (apply #'list
   4998                           0 (* r (round (nth 1 time) r))
   4999                           (nthcdr 2 time)))))
   5000 	(if (or (not past) (time-less-p res now))
   5001 	    res
   5002 	  (time-subtract res (* r 60)))))))
   5003 
   5004 (defun org-today ()
   5005   "Return today date, considering `org-extend-today-until'."
   5006   (time-to-days
   5007    (time-since (* 3600 org-extend-today-until))))
   5008 
   5009 ;;;; Font-Lock stuff, including the activators
   5010 
   5011 (defconst org-match-sexp-depth 3
   5012   "Number of stacked braces for sub/superscript matching.")
   5013 
   5014 (defun org-create-multibrace-regexp (left right n)
   5015   "Create a regular expression which will match a balanced sexp.
   5016 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
   5017 as single character strings.
   5018 The regexp returned will match the entire expression including the
   5019 delimiters.  It will also define a single group which contains the
   5020 match except for the outermost delimiters.  The maximum depth of
   5021 stacked delimiters is N.  Escaping delimiters is not possible."
   5022   (let* ((nothing (concat "[^" left right "]*?"))
   5023 	 (or "\\|")
   5024 	 (re nothing)
   5025 	 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
   5026     (while (> n 1)
   5027       (setq n (1- n)
   5028 	    re (concat re or next)
   5029 	    next (concat "\\(?:" nothing left next right "\\)+" nothing)))
   5030     (concat left "\\(" re "\\)" right)))
   5031 
   5032 (defconst org-match-substring-regexp
   5033   (concat
   5034    "\\(\\S-\\)\\([_^]\\)\\("
   5035    "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
   5036    "\\|"
   5037    "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
   5038    "\\|"
   5039    "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
   5040   "The regular expression matching a sub- or superscript.")
   5041 
   5042 (defconst org-match-substring-with-braces-regexp
   5043   (concat
   5044    "\\(\\S-\\)\\([_^]\\)"
   5045    "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
   5046   "The regular expression matching a sub- or superscript, forcing braces.")
   5047 
   5048 (defvar org-emph-face nil)
   5049 
   5050 (defun org-do-emphasis-faces (limit)
   5051   "Run through the buffer and emphasize strings."
   5052   (let ((quick-re (format "\\([%s]\\|^\\)\\([~=*/_+]\\)"
   5053 			  (car org-emphasis-regexp-components))))
   5054     (catch :exit
   5055       (while (re-search-forward quick-re limit t)
   5056 	(let* ((marker (match-string 2))
   5057 	       (verbatim? (member marker '("~" "="))))
   5058 	  (when (save-excursion
   5059 		  (goto-char (match-beginning 0))
   5060 		  (and
   5061 		   ;; Do not match table hlines.
   5062 		   (not (and (equal marker "+")
   5063 			     (org-match-line
   5064 			      "[ \t]*\\(|[-+]+|?\\|\\+[-+]+\\+\\)[ \t]*$")))
   5065 		   ;; Do not match headline stars.  Do not consider
   5066 		   ;; stars of a headline as closing marker for bold
   5067 		   ;; markup either.
   5068 		   (not (and (equal marker "*")
   5069 			     (save-excursion
   5070 			       (forward-char)
   5071 			       (skip-chars-backward "*")
   5072 			       (looking-at-p org-outline-regexp-bol))))
   5073 		   ;; Match full emphasis markup regexp.
   5074 		   (looking-at (if verbatim? org-verbatim-re org-emph-re))
   5075 		   ;; Do not span over paragraph boundaries.
   5076 		   (not (string-match-p org-element-paragraph-separate
   5077 					(match-string 2)))
   5078 		   ;; Do not span over cells in table rows.
   5079 		   (not (and (save-match-data (org-match-line "[ \t]*|"))
   5080 			     (string-match-p "|" (match-string 4))))))
   5081 	    (pcase-let ((`(,_ ,face ,_) (assoc marker org-emphasis-alist))
   5082 			(m (if org-hide-emphasis-markers 4 2)))
   5083 	      (font-lock-prepend-text-property
   5084 	       (match-beginning m) (match-end m) 'face face)
   5085 	      (when verbatim?
   5086 		(org-remove-flyspell-overlays-in
   5087 		 (match-beginning 0) (match-end 0))
   5088                 (when (and (org-fold-core-folding-spec-p 'org-link)
   5089                            (org-fold-core-folding-spec-p 'org-link-description))
   5090                   (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link)
   5091                   (org-fold-region (match-beginning 0) (match-end 0) nil 'org-link-description))
   5092 		(remove-text-properties (match-beginning 2) (match-end 2)
   5093 					'(display t invisible t intangible t)))
   5094 	      (add-text-properties (match-beginning 2) (match-end 2)
   5095 				   '(font-lock-multiline t org-emphasis t))
   5096 	      (when (and org-hide-emphasis-markers
   5097 			 (not (org-at-comment-p)))
   5098 		(add-text-properties (match-end 4) (match-beginning 5)
   5099 				     '(invisible t))
   5100 		(add-text-properties (match-beginning 3) (match-end 3)
   5101 				     '(invisible t)))
   5102 	      (throw :exit t))))))))
   5103 
   5104 (defun org-emphasize (&optional char)
   5105   "Insert or change an emphasis, i.e. a font like bold or italic.
   5106 If there is an active region, change that region to a new emphasis.
   5107 If there is no region, just insert the marker characters and position
   5108 the cursor between them.
   5109 CHAR should be the marker character.  If it is a space, it means to
   5110 remove the emphasis of the selected region.
   5111 If CHAR is not given (for example in an interactive call) it will be
   5112 prompted for."
   5113   (interactive)
   5114   (let ((erc org-emphasis-regexp-components)
   5115 	(string "") beg end move s)
   5116     (if (org-region-active-p)
   5117 	(setq beg (region-beginning)
   5118 	      end (region-end)
   5119 	      string (buffer-substring beg end))
   5120       (setq move t))
   5121 
   5122     (unless char
   5123       (message "Emphasis marker or tag: [%s]"
   5124 	       (mapconcat #'car org-emphasis-alist ""))
   5125       (setq char (read-char-exclusive)))
   5126     (if (equal char ?\s)
   5127 	(setq s ""
   5128 	      move nil)
   5129       (unless (assoc (char-to-string char) org-emphasis-alist)
   5130 	(user-error "No such emphasis marker: \"%c\"" char))
   5131       (setq s (char-to-string char)))
   5132     (while (and (> (length string) 1)
   5133 		(equal (substring string 0 1) (substring string -1))
   5134 		(assoc (substring string 0 1) org-emphasis-alist))
   5135       (setq string (substring string 1 -1)))
   5136     (setq string (concat s string s))
   5137     (when beg (delete-region beg end))
   5138     (unless (or (bolp)
   5139 		(string-match (concat "[" (nth 0 erc) "\n]")
   5140 			      (char-to-string (char-before (point)))))
   5141       (insert " "))
   5142     (unless (or (eobp)
   5143 		(string-match (concat "[" (nth 1 erc) "\n]")
   5144 			      (char-to-string (char-after (point)))))
   5145       (insert " ") (backward-char 1))
   5146     (insert string)
   5147     (and move (backward-char 1))))
   5148 
   5149 (defconst org-nonsticky-props
   5150   '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
   5151 
   5152 (defsubst org-rear-nonsticky-at (pos)
   5153   (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
   5154 
   5155 (defun org-activate-links--overlays (limit)
   5156   "Add link properties to links.
   5157 This includes angle, plain, and bracket links."
   5158   (catch :exit
   5159     (while (re-search-forward org-link-any-re limit t)
   5160       (let* ((start (match-beginning 0))
   5161 	     (end (match-end 0))
   5162 	     (visible-start (or (match-beginning 3) (match-beginning 2)))
   5163 	     (visible-end (or (match-end 3) (match-end 2)))
   5164 	     (style (cond ((eq ?< (char-after start)) 'angle)
   5165 			  ((eq ?\[ (char-after (1+ start))) 'bracket)
   5166 			  (t 'plain))))
   5167 	(when (and (memq style org-highlight-links)
   5168 		   ;; Do not span over paragraph boundaries.
   5169 		   (not (string-match-p org-element-paragraph-separate
   5170 				      (match-string 0)))
   5171 		   ;; Do not confuse plain links with tags.
   5172 		   (not (and (eq style 'plain)
   5173 			   (let ((face (get-text-property
   5174 					(max (1- start) (point-min)) 'face)))
   5175 			     (if (consp face) (memq 'org-tag face)
   5176 			       (eq 'org-tag face))))))
   5177 	  (let* ((link-object (save-excursion
   5178 				(goto-char start)
   5179 				(save-match-data (org-element-link-parser))))
   5180 		 (link (org-element-property :raw-link link-object))
   5181 		 (type (org-element-property :type link-object))
   5182 		 (path (org-element-property :path link-object))
   5183                  (face-property (pcase (org-link-get-parameter type :face)
   5184 				  ((and (pred functionp) face) (funcall face path))
   5185 				  ((and (pred facep) face) face)
   5186 				  ((and (pred consp) face) face) ;anonymous
   5187 				  (_ 'org-link)))
   5188 		 (properties		;for link's visible part
   5189 		  (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
   5190 					'highlight)
   5191 			'keymap (or (org-link-get-parameter type :keymap)
   5192 				    org-mouse-map)
   5193 			'help-echo (pcase (org-link-get-parameter type :help-echo)
   5194 				     ((and (pred stringp) echo) echo)
   5195 				     ((and (pred functionp) echo) echo)
   5196 				     (_ (concat "LINK: " link)))
   5197 			'htmlize-link (pcase (org-link-get-parameter type
   5198 								     :htmlize-link)
   5199 					((and (pred functionp) f) (funcall f))
   5200 					(_ `(:uri ,link)))
   5201 			'font-lock-multiline t)))
   5202 	    (org-remove-flyspell-overlays-in start end)
   5203 	    (org-rear-nonsticky-at end)
   5204 	    (if (not (eq 'bracket style))
   5205 		(progn
   5206                   (add-face-text-property start end face-property)
   5207 		  (add-text-properties start end properties))
   5208 	      ;; Handle invisible parts in bracket links.
   5209 	      (remove-text-properties start end '(invisible nil))
   5210 	      (let ((hidden
   5211 		     (append `(invisible
   5212 			       ,(or (org-link-get-parameter type :display)
   5213 				    'org-link))
   5214 			     properties)))
   5215 		(add-text-properties start visible-start hidden)
   5216                 (add-face-text-property start end face-property)
   5217 		(add-text-properties visible-start visible-end properties)
   5218 		(add-text-properties visible-end end hidden)
   5219 		(org-rear-nonsticky-at visible-start)
   5220 		(org-rear-nonsticky-at visible-end)))
   5221 	    (let ((f (org-link-get-parameter type :activate-func)))
   5222 	      (when (functionp f)
   5223 		(funcall f start end path (eq style 'bracket))))
   5224 	    (throw :exit t)))))		;signal success
   5225     nil))
   5226 (defun org-activate-links--text-properties (limit)
   5227   "Add link properties to links.
   5228 This includes angle, plain, and bracket links."
   5229   (catch :exit
   5230     (while (re-search-forward org-link-any-re limit t)
   5231       (let* ((start (match-beginning 0))
   5232 	     (end (match-end 0))
   5233 	     (visible-start (or (match-beginning 3) (match-beginning 2)))
   5234 	     (visible-end (or (match-end 3) (match-end 2)))
   5235 	     (style (cond ((eq ?< (char-after start)) 'angle)
   5236 			  ((eq ?\[ (char-after (1+ start))) 'bracket)
   5237 			  (t 'plain))))
   5238 	(when (and (memq style org-highlight-links)
   5239 		   ;; Do not span over paragraph boundaries.
   5240 		   (not (string-match-p org-element-paragraph-separate
   5241 					(match-string 0)))
   5242 		   ;; Do not confuse plain links with tags.
   5243 		   (not (and (eq style 'plain)
   5244 			     (let ((face (get-text-property
   5245 					  (max (1- start) (point-min)) 'face)))
   5246 			       (if (consp face) (memq 'org-tag face)
   5247 				 (eq 'org-tag face))))))
   5248 	  (let* ((link-object (save-excursion
   5249 				(goto-char start)
   5250 				(save-match-data (org-element-link-parser))))
   5251 		 (link (org-element-property :raw-link link-object))
   5252 		 (type (org-element-property :type link-object))
   5253 		 (path (org-element-property :path link-object))
   5254                  (face-property (pcase (org-link-get-parameter type :face)
   5255 				  ((and (pred functionp) face) (funcall face path))
   5256 				  ((and (pred facep) face) face)
   5257 				  ((and (pred consp) face) face) ;anonymous
   5258 				  (_ 'org-link)))
   5259 		 (properties		;for link's visible part
   5260 		  (list 'mouse-face (or (org-link-get-parameter type :mouse-face)
   5261 					'highlight)
   5262 			'keymap (or (org-link-get-parameter type :keymap)
   5263 				    org-mouse-map)
   5264 			'help-echo (pcase (org-link-get-parameter type :help-echo)
   5265 				     ((and (pred stringp) echo) echo)
   5266 				     ((and (pred functionp) echo) echo)
   5267 				     (_ (concat "LINK: " link)))
   5268 			'htmlize-link (pcase (org-link-get-parameter type
   5269 								  :htmlize-link)
   5270 					((and (pred functionp) f) (funcall f))
   5271 					(_ `(:uri ,link)))
   5272 			'font-lock-multiline t)))
   5273 	    (org-remove-flyspell-overlays-in start end)
   5274 	    (org-rear-nonsticky-at end)
   5275 	    (if (not (eq 'bracket style))
   5276 		(progn
   5277                   (add-face-text-property start end face-property)
   5278 		  (add-text-properties start end properties))
   5279               ;; Initialize folding when used outside org-mode.
   5280               (unless (or (derived-mode-p 'org-mode)
   5281 			  (and (org-fold-folding-spec-p 'org-link-description)
   5282                                (org-fold-folding-spec-p 'org-link)))
   5283                 (org-fold-initialize (or (and (stringp org-ellipsis) (not (equal "" org-ellipsis)) org-ellipsis)
   5284                                       "...")))
   5285 	      ;; Handle invisible parts in bracket links.
   5286 	      (let ((spec (or (org-link-get-parameter type :display)
   5287 			      'org-link)))
   5288                 (unless (org-fold-folding-spec-p spec)
   5289                   (org-fold-add-folding-spec spec
   5290                                           (cdr org-link--link-folding-spec)
   5291                                           nil
   5292                                           'append)
   5293                   (org-fold-core-set-folding-spec-property spec :visible t))
   5294                 (org-fold-region start end nil 'org-link)
   5295                 (org-fold-region start end nil 'org-link-description)
   5296                 ;; We are folding the whole emphasized text with SPEC
   5297                 ;; first.  It makes everything invisible (or whatever
   5298                 ;; the user wants).
   5299                 (org-fold-region start end t spec)
   5300                 ;; The visible part of the text is folded using
   5301                 ;; 'org-link-description, which is forcing this part of
   5302                 ;; the text to be visible.
   5303                 (org-fold-region visible-start visible-end t 'org-link-description)
   5304 		(add-text-properties start end properties)
   5305                 (add-face-text-property start end face-property)
   5306 		(org-rear-nonsticky-at visible-start)
   5307 		(org-rear-nonsticky-at visible-end)))
   5308 	    (let ((f (org-link-get-parameter type :activate-func)))
   5309 	      (when (functionp f)
   5310 		(funcall f start end path (eq style 'bracket))))
   5311 	    (throw :exit t)))))		;signal success
   5312     nil))
   5313 (defsubst org-activate-links (limit)
   5314   "Add link properties to links.
   5315 This includes angle, plain, and bracket links."
   5316   (if (eq org-fold-core-style 'text-properties)
   5317       (org-activate-links--text-properties limit)
   5318     (org-activate-links--overlays limit)))
   5319 
   5320 (defun org-activate-code (limit)
   5321   (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
   5322     (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
   5323     (remove-text-properties (match-beginning 0) (match-end 0)
   5324 			    '(display t invisible t intangible t))
   5325     t))
   5326 
   5327 (defcustom org-src-fontify-natively t
   5328   "When non-nil, fontify code in code blocks.
   5329 See also the `org-block' face."
   5330   :type 'boolean
   5331   :version "26.1"
   5332   :package-version '(Org . "8.3")
   5333   :group 'org-appearance
   5334   :group 'org-babel)
   5335 
   5336 (defcustom org-allow-promoting-top-level-subtree nil
   5337   "When non-nil, allow promoting a top level subtree.
   5338 The leading star of the top level headline will be replaced
   5339 by a #."
   5340   :type 'boolean
   5341   :version "24.1"
   5342   :group 'org-appearance)
   5343 
   5344 (defun org-fontify-meta-lines-and-blocks (limit)
   5345   (condition-case nil
   5346       (org-fontify-meta-lines-and-blocks-1 limit)
   5347     (error (message "Org mode fontification error in %S at %d"
   5348 		    (current-buffer)
   5349 		    (line-number-at-pos)))))
   5350 
   5351 (defun org-fontify-meta-lines-and-blocks-1 (limit)
   5352   "Fontify #+ lines and blocks."
   5353   (let ((case-fold-search t))
   5354     (when (re-search-forward
   5355 	   (rx bol (group (zero-or-more (any " \t")) "#"
   5356 			  (group (group (or (seq "+" (one-or-more (any "a-zA-Z")) (optional ":"))
   5357 					    (any " \t")
   5358 					    eol))
   5359 				 (optional (group "_" (group (one-or-more (any "a-zA-Z"))))))
   5360 			  (zero-or-more (any " \t"))
   5361 			  (group (group (zero-or-more (not (any " \t\n"))))
   5362 				 (zero-or-more (any " \t"))
   5363 				 (group (zero-or-more any)))))
   5364 	   limit t)
   5365       (let ((beg (match-beginning 0))
   5366 	    (end-of-beginline (match-end 0))
   5367 	    ;; Including \n at end of #+begin line will include \n
   5368 	    ;; after the end of block content.
   5369 	    (block-start (match-end 0))
   5370 	    (block-end nil)
   5371 	    (lang (match-string 7)) ; The language, if it is a source block.
   5372 	    (bol-after-beginline (line-beginning-position 2))
   5373 	    (dc1 (downcase (match-string 2)))
   5374 	    (dc3 (downcase (match-string 3)))
   5375 	    (whole-blockline org-fontify-whole-block-delimiter-line)
   5376 	    beg-of-endline end-of-endline nl-before-endline quoting block-type)
   5377 	(cond
   5378 	 ((and (match-end 4) (equal dc3 "+begin"))
   5379 	  ;; Truly a block
   5380 	  (setq block-type (downcase (match-string 5))
   5381 		;; Src, example, export, maybe more.
   5382 		quoting (member block-type org-protecting-blocks))
   5383 	  (when (re-search-forward
   5384 		 (rx-to-string `(group bol (or (seq (one-or-more "*") space)
   5385 					       (seq (zero-or-more (any " \t"))
   5386 						    "#+end"
   5387 						    ,(match-string 4)
   5388 						    word-end
   5389 						    (zero-or-more any)))))
   5390 		 ;; We look further than LIMIT on purpose.
   5391 		 nil t)
   5392 	    ;; We do have a matching #+end line.
   5393 	    (setq beg-of-endline (match-beginning 0)
   5394 		  end-of-endline (match-end 0)
   5395 		  nl-before-endline (1- (match-beginning 0)))
   5396 	    (setq block-end (match-beginning 0)) ; Include the final newline.
   5397 	    (when quoting
   5398 	      (org-remove-flyspell-overlays-in bol-after-beginline nl-before-endline)
   5399 	      (remove-text-properties beg end-of-endline
   5400 				      '(display t invisible t intangible t)))
   5401 	    (add-text-properties
   5402 	     beg end-of-endline '(font-lock-fontified t font-lock-multiline t))
   5403 	    (org-remove-flyspell-overlays-in beg bol-after-beginline)
   5404 	    (org-remove-flyspell-overlays-in nl-before-endline end-of-endline)
   5405 	    (cond
   5406 	     ((and lang (not (string= lang "")) org-src-fontify-natively)
   5407 	      (save-match-data
   5408                 (org-src-font-lock-fontify-block lang block-start block-end))
   5409 	      (add-text-properties bol-after-beginline block-end '(src-block t)))
   5410 	     (quoting
   5411 	      (add-text-properties
   5412 	       bol-after-beginline beg-of-endline
   5413 	       (list 'face
   5414 		     (list :inherit
   5415 			   (let ((face-name
   5416 				  (intern (format "org-block-%s" lang))))
   5417 			     (append (and (facep face-name) (list face-name))
   5418 				     '(org-block)))))))
   5419 	     ((not org-fontify-quote-and-verse-blocks))
   5420 	     ((string= block-type "quote")
   5421 	      (add-face-text-property
   5422 	       bol-after-beginline beg-of-endline 'org-quote t))
   5423 	     ((string= block-type "verse")
   5424 	      (add-face-text-property
   5425 	       bol-after-beginline beg-of-endline 'org-verse t)))
   5426 	    ;; Fontify the #+begin and #+end lines of the blocks
   5427 	    (add-text-properties
   5428 	     beg (if whole-blockline bol-after-beginline end-of-beginline)
   5429 	     '(face org-block-begin-line))
   5430 	    (unless (eq (char-after beg-of-endline) ?*)
   5431 	      (add-text-properties
   5432 	       beg-of-endline
   5433 	       (if whole-blockline
   5434 		   (let ((beg-of-next-line (1+ end-of-endline)))
   5435 		     (min (point-max) beg-of-next-line))
   5436 		 (min (point-max) end-of-endline))
   5437 	       '(face org-block-end-line)))
   5438 	    t))
   5439 	 ((member dc1 '("+title:" "+subtitle:" "+author:" "+email:" "+date:"))
   5440 	  (org-remove-flyspell-overlays-in
   5441 	   (match-beginning 0)
   5442 	   (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
   5443 	  (add-text-properties
   5444 	   beg (match-end 3)
   5445 	   (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
   5446 	       '(font-lock-fontified t invisible t)
   5447 	     '(font-lock-fontified t face org-document-info-keyword)))
   5448 	  (add-text-properties
   5449 	   (match-beginning 6) (min (point-max) (1+ (match-end 6)))
   5450 	   (if (string-equal dc1 "+title:")
   5451 	       '(font-lock-fontified t face org-document-title)
   5452 	     '(font-lock-fontified t face org-document-info))))
   5453 	 ((string-prefix-p "+caption" dc1)
   5454 	  (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
   5455 	  (remove-text-properties (match-beginning 0) (match-end 0)
   5456 				  '(display t invisible t intangible t))
   5457 	  ;; Handle short captions
   5458 	  (save-excursion
   5459 	    (beginning-of-line)
   5460 	    (looking-at (rx (group (zero-or-more (any " \t"))
   5461 				   "#+caption"
   5462 				   (optional "[" (zero-or-more any) "]")
   5463 				   ":")
   5464 			    (zero-or-more (any " \t")))))
   5465 	  (add-text-properties (line-beginning-position) (match-end 1)
   5466 			       '(font-lock-fontified t face org-meta-line))
   5467 	  (add-text-properties (match-end 0) (line-end-position)
   5468 			       '(font-lock-fontified t face org-block))
   5469 	  t)
   5470 	 ((member dc3 '(" " ""))
   5471 	  ;; Just a comment, the plus was not there
   5472 	  (org-remove-flyspell-overlays-in beg (match-end 0))
   5473 	  (add-text-properties
   5474 	   beg (match-end 0)
   5475 	   '(font-lock-fontified t face font-lock-comment-face)))
   5476 	 (t ;; Just any other in-buffer setting, but not indented
   5477 	  (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
   5478 	  (remove-text-properties (match-beginning 0) (match-end 0)
   5479 				  '(display t invisible t intangible t))
   5480 	  (add-text-properties beg (match-end 0)
   5481 			       '(font-lock-fontified t face org-meta-line))
   5482 	  t))))))
   5483 
   5484 (defun org-fontify-drawers (limit)
   5485   "Fontify drawers."
   5486   (when (re-search-forward org-drawer-regexp limit t)
   5487     (add-text-properties (1- (match-beginning 1)) (1+ (match-end 1))
   5488 			 '(font-lock-fontified t face org-drawer))
   5489     (org-remove-flyspell-overlays-in
   5490      (line-beginning-position) (line-beginning-position 2))
   5491     t))
   5492 
   5493 (defun org-fontify-macros (limit)
   5494   "Fontify macros."
   5495   (when (re-search-forward "{{{\\([a-zA-Z][-a-zA-Z0-9_]*\\)" limit t)
   5496     (let ((begin (match-beginning 0))
   5497 	  (opening-end (match-beginning 1)))
   5498       (when (and (re-search-forward "\n[ \t]*\n\\|\\(}}}\\)" limit t)
   5499 		 (match-string 1))
   5500 	(let ((end (match-end 1))
   5501 	      (closing-start (match-beginning 1)))
   5502 	  (add-text-properties
   5503 	   begin end
   5504 	   '(font-lock-multiline t font-lock-fontified t face org-macro))
   5505 	  (org-remove-flyspell-overlays-in begin end)
   5506 	  (when org-hide-macro-markers
   5507 	    (add-text-properties begin opening-end '(invisible t))
   5508 	    (add-text-properties closing-start end '(invisible t)))
   5509 	  t)))))
   5510 
   5511 (defun org-fontify-extend-region (beg end _old-len)
   5512   (let ((end (if (progn (goto-char end) (looking-at-p "^[*#]"))
   5513                  (1+ end) end))
   5514         (begin-re "\\(\\\\\\[\\|\\(#\\+begin_\\|\\\\begin{\\)\\S-+\\)")
   5515 	(end-re "\\(\\\\\\]\\|\\(#\\+end_\\|\\\\end{\\)\\S-+\\)")
   5516 	(extend
   5517          (lambda (r1 r2 dir)
   5518 	   (let ((re (replace-regexp-in-string
   5519                       "\\(begin\\|end\\)" r1
   5520 		      (replace-regexp-in-string
   5521                        "[][]" r2
   5522 		       (match-string-no-properties 0)))))
   5523 	     (re-search-forward (regexp-quote re) nil t dir)))))
   5524     (goto-char beg)
   5525     (back-to-indentation)
   5526     (save-match-data
   5527       (cond ((looking-at end-re)
   5528 	     (cons (or (funcall extend "begin" "[" -1) beg) end))
   5529 	    ((looking-at begin-re)
   5530 	     (cons beg (or (funcall extend "end" "]" 1) end)))
   5531 	    (t (cons beg end))))))
   5532 
   5533 (defun org-activate-footnote-links (limit)
   5534   "Add text properties for footnotes."
   5535   (let ((fn (org-footnote-next-reference-or-definition limit)))
   5536     (when fn
   5537       (let* ((beg (nth 1 fn))
   5538 	     (end (nth 2 fn))
   5539 	     (label (car fn))
   5540 	     (referencep (/= (line-beginning-position) beg)))
   5541 	(when (and referencep (nth 3 fn))
   5542 	  (save-excursion
   5543 	    (goto-char beg)
   5544 	    (search-forward (or label "fn:"))
   5545 	    (org-remove-flyspell-overlays-in beg (match-end 0))))
   5546 	(add-text-properties beg end
   5547 			     (list 'mouse-face 'highlight
   5548 				   'keymap org-mouse-map
   5549 				   'help-echo
   5550 				   (if referencep "Footnote reference"
   5551 				     "Footnote definition")
   5552 				   'font-lock-fontified t
   5553 				   'font-lock-multiline t
   5554 				   'face 'org-footnote))))))
   5555 
   5556 (defun org-activate-dates (limit)
   5557   "Add text properties for dates."
   5558   (when (and (re-search-forward org-tsr-regexp-both limit t)
   5559 	     (not (equal (char-before (match-beginning 0)) 91)))
   5560     (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
   5561     (add-text-properties (match-beginning 0) (match-end 0)
   5562 			 (list 'mouse-face 'highlight
   5563 			       'keymap org-mouse-map))
   5564     (org-rear-nonsticky-at (match-end 0))
   5565     (when org-display-custom-times
   5566       ;; If it's a date range, activate custom time for second date.
   5567       (when (match-end 3)
   5568 	(org-display-custom-time (match-beginning 3) (match-end 3)))
   5569       (org-display-custom-time (match-beginning 1) (match-end 1)))
   5570     t))
   5571 
   5572 (defun org-activate-target-links (limit)
   5573   "Add text properties for target matches."
   5574   (when org-target-link-regexp
   5575     (let ((case-fold-search t))
   5576       ;; `org-target-link-regexp' matches one character before the
   5577       ;; actual target.
   5578       (unless (bolp) (forward-char -1))
   5579       (when (re-search-forward org-target-link-regexp limit t)
   5580 	(org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
   5581 	(add-text-properties (match-beginning 1) (match-end 1)
   5582 			     (list 'mouse-face 'highlight
   5583 				   'keymap org-mouse-map
   5584 				   'help-echo "Radio target link"
   5585 				   'org-linked-text t))
   5586 	(org-rear-nonsticky-at (match-end 1))
   5587 	t))))
   5588 
   5589 (defvar org-latex-and-related-regexp nil
   5590   "Regular expression for highlighting LaTeX, entities and sub/superscript.")
   5591 
   5592 (defun org-compute-latex-and-related-regexp ()
   5593   "Compute regular expression for LaTeX, entities and sub/superscript.
   5594 Result depends on variable `org-highlight-latex-and-related'."
   5595   (let ((re-sub
   5596 	 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
   5597 	       ((eq org-use-sub-superscripts '{})
   5598 		(list org-match-substring-with-braces-regexp))
   5599 	       (org-use-sub-superscripts (list org-match-substring-regexp))))
   5600 	(re-latex
   5601 	 (when (or (memq 'latex org-highlight-latex-and-related)
   5602 		   (memq 'native org-highlight-latex-and-related))
   5603 	   (let ((matchers (plist-get org-format-latex-options :matchers)))
   5604 	     (delq nil
   5605 		   (mapcar (lambda (x)
   5606 			     (and (member (car x) matchers) (nth 1 x)))
   5607 			   org-latex-regexps)))))
   5608 	(re-entities
   5609 	 (when (memq 'entities org-highlight-latex-and-related)
   5610 	   (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\
   5611 \\($\\|{}\\|[^[:alpha:]]\\)"))))
   5612     (setq-local org-latex-and-related-regexp
   5613 		(mapconcat #'identity
   5614 			   (append re-latex re-entities re-sub)
   5615 			   "\\|"))))
   5616 
   5617 (defun org-do-latex-and-related (limit)
   5618   "Highlight LaTeX snippets and environments, entities and sub/superscript.
   5619 Stop at first highlighted object, if any.  Return t if some
   5620 highlighting was done, nil otherwise."
   5621   (when (org-string-nw-p org-latex-and-related-regexp)
   5622     (let ((latex-prefix-re (rx (or "$" "\\(" "\\[")))
   5623 	  (blank-line-re (rx (and "\n" (zero-or-more (or " " "\t")) "\n"))))
   5624       (catch 'found
   5625 	(while (and (< (point) limit)
   5626 		    (re-search-forward org-latex-and-related-regexp nil t))
   5627 	  (cond
   5628            ((>= (match-beginning 0) limit)
   5629 	    (throw 'found nil))
   5630 	   ((cl-some (lambda (f)
   5631 		       (memq f '(org-code org-verbatim underline
   5632 					  org-special-keyword)))
   5633 		     (save-excursion
   5634 		       (goto-char (1+ (match-beginning 0)))
   5635 		       (face-at-point nil t))))
   5636 	   ;; Try to limit false positives.  In this case, ignore
   5637 	   ;; $$...$$, \(...\), and \[...\] LaTeX constructs if they
   5638 	   ;; contain an empty line.
   5639 	   ((save-excursion
   5640 	      (goto-char (match-beginning 0))
   5641 	      (and (looking-at-p latex-prefix-re)
   5642 		   (save-match-data
   5643 		     (re-search-forward blank-line-re (1- (match-end 0)) t)))))
   5644 	   (t
   5645 	    (let* ((offset (if (memq (char-after (1+ (match-beginning 0)))
   5646 				     '(?_ ?^))
   5647 			       1
   5648 			     0))
   5649 		   (start (+ offset (match-beginning 0)))
   5650 		   (end (match-end 0)))
   5651 	      (if (memq 'native org-highlight-latex-and-related)
   5652 		  (org-src-font-lock-fontify-block "latex" start end)
   5653 		(font-lock-prepend-text-property start end
   5654 						 'face 'org-latex-and-related))
   5655 	      (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
   5656 				   '(font-lock-multiline t))
   5657 	      (throw 'found t)))))
   5658 	nil))))
   5659 
   5660 (defun org-restart-font-lock ()
   5661   "Restart `font-lock-mode', to force refontification."
   5662   (when font-lock-mode
   5663     (font-lock-mode -1)
   5664     (font-lock-mode 1)))
   5665 
   5666 (defun org-activate-tags (limit)
   5667   (when (re-search-forward org-tag-line-re limit t)
   5668     (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
   5669     (add-text-properties (match-beginning 1) (match-end 1)
   5670 			 (list 'mouse-face 'highlight
   5671 			       'keymap org-mouse-map))
   5672     (org-rear-nonsticky-at (match-end 1))
   5673     t))
   5674 
   5675 (defun org-outline-level ()
   5676   "Compute the outline level of the heading at point.
   5677 
   5678 If this is called at a normal headline, the level is the number
   5679 of stars.  Use `org-reduced-level' to remove the effect of
   5680 `org-odd-levels'.  Unlike to `org-current-level', this function
   5681 takes into consideration inlinetasks."
   5682   (org-with-wide-buffer
   5683    (end-of-line)
   5684    (if (re-search-backward org-outline-regexp-bol nil t)
   5685        (1- (- (match-end 0) (match-beginning 0)))
   5686      0)))
   5687 
   5688 (defvar org-font-lock-keywords nil)
   5689 
   5690 (defsubst org-re-property (property &optional literal allow-null value)
   5691   "Return a regexp matching a PROPERTY line.
   5692 
   5693 When optional argument LITERAL is non-nil, do not quote PROPERTY.
   5694 This is useful when PROPERTY is a regexp.  When ALLOW-NULL is
   5695 non-nil, match properties even without a value.
   5696 
   5697 Match group 3 is set to the value when it exists.  If there is no
   5698 value and ALLOW-NULL is non-nil, it is set to the empty string.
   5699 
   5700 With optional argument VALUE, match only property lines with
   5701 that value; in this case, ALLOW-NULL is ignored.  VALUE is quoted
   5702 unless LITERAL is non-nil."
   5703   (concat
   5704    "^\\(?4:[ \t]*\\)"
   5705    (format "\\(?1::\\(?2:%s\\):\\)"
   5706 	   (if literal property (regexp-quote property)))
   5707    (cond (value
   5708 	  (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
   5709 		  (if literal value (regexp-quote value))))
   5710 	 (allow-null
   5711 	  "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
   5712 	 (t
   5713 	  "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
   5714 
   5715 (defconst org-property-re
   5716   (org-re-property "\\S-+" 'literal t)
   5717   "Regular expression matching a property line.
   5718 There are four matching groups:
   5719 1: :PROPKEY: including the leading and trailing colon,
   5720 2: PROPKEY without the leading and trailing colon,
   5721 3: PROPVAL without leading or trailing spaces,
   5722 4: the indentation of the current line,
   5723 5: trailing whitespace.")
   5724 
   5725 (defvar org-font-lock-hook nil
   5726   "Functions to be called for special font lock stuff.")
   5727 
   5728 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
   5729 
   5730 (defvar org-font-lock-set-keywords-hook nil
   5731   "Functions that can manipulate `org-font-lock-extra-keywords'.
   5732 This is called after `org-font-lock-extra-keywords' is defined, but before
   5733 it is installed to be used by font lock.  This can be useful if something
   5734 needs to be inserted at a specific position in the font-lock sequence.")
   5735 
   5736 (defun org-font-lock-hook (limit)
   5737   "Run `org-font-lock-hook' within LIMIT."
   5738   (run-hook-with-args 'org-font-lock-hook limit))
   5739 
   5740 (defun org-set-font-lock-defaults ()
   5741   "Set font lock defaults for the current buffer."
   5742   (let ((org-font-lock-extra-keywords
   5743 	 (list
   5744 	  ;; Call the hook
   5745 	  '(org-font-lock-hook)
   5746 	  ;; Headlines
   5747 	  `(,(if org-fontify-whole-heading-line
   5748 		 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
   5749 	       "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
   5750 	    (1 (org-get-level-face 1))
   5751 	    (2 (org-get-level-face 2))
   5752 	    (3 (org-get-level-face 3)))
   5753 	  ;; Table lines
   5754 	  '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
   5755 	    (1 'org-table t))
   5756 	  ;; Table internals
   5757 	  '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
   5758 	  '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
   5759 	  '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
   5760 	  '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
   5761 	  ;; Properties
   5762 	  (list org-property-re
   5763 		'(1 'org-special-keyword t)
   5764 		'(3 'org-property-value t))
   5765 	  ;; Drawers
   5766 	  '(org-fontify-drawers)
   5767 	  ;; Link related fontification.
   5768 	  '(org-activate-links)
   5769 	  (when (memq 'tag org-highlight-links) '(org-activate-tags (1 'org-tag prepend)))
   5770 	  (when (memq 'radio org-highlight-links) '(org-activate-target-links (1 'org-link t)))
   5771 	  (when (memq 'date org-highlight-links) '(org-activate-dates (0 'org-date t)))
   5772 	  (when (memq 'footnote org-highlight-links) '(org-activate-footnote-links))
   5773           ;; Targets.
   5774           (list org-radio-target-regexp '(0 'org-target t))
   5775 	  (list org-target-regexp '(0 'org-target t))
   5776 	  ;; Diary sexps.
   5777 	  '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
   5778 	  ;; Macro
   5779 	  '(org-fontify-macros)
   5780 	  ;; TODO keyword
   5781 	  (list (format org-heading-keyword-regexp-format
   5782 			org-todo-regexp)
   5783 		'(2 (org-get-todo-face 2) prepend))
   5784 	  ;; TODO
   5785 	  (when org-fontify-todo-headline
   5786 	    (list (format org-heading-keyword-regexp-format
   5787 			  (concat
   5788 			   "\\(?:"
   5789 			   (mapconcat 'regexp-quote org-not-done-keywords "\\|")
   5790 			   "\\)"))
   5791 		  '(2 'org-headline-todo prepend)))
   5792 	  ;; DONE
   5793 	  (when org-fontify-done-headline
   5794 	    (list (format org-heading-keyword-regexp-format
   5795 			  (concat
   5796 			   "\\(?:"
   5797 			   (mapconcat 'regexp-quote org-done-keywords "\\|")
   5798 			   "\\)"))
   5799 		  '(2 'org-headline-done prepend)))
   5800 	  ;; Priorities
   5801 	  '(org-font-lock-add-priority-faces)
   5802 	  ;; Tags
   5803 	  '(org-font-lock-add-tag-faces)
   5804 	  ;; Tags groups
   5805 	  (when (and org-group-tags org-tag-groups-alist)
   5806 	    (list (concat org-outline-regexp-bol ".+\\(:"
   5807 			  (regexp-opt (mapcar 'car org-tag-groups-alist))
   5808 			  ":\\).*$")
   5809 		  '(1 'org-tag-group prepend)))
   5810 	  ;; Special keywords
   5811 	  (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
   5812 	  (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
   5813 	  (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
   5814 	  (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
   5815 	  ;; Emphasis
   5816 	  (when org-fontify-emphasized-text '(org-do-emphasis-faces))
   5817 	  ;; Checkboxes
   5818 	  '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
   5819 	    1 'org-checkbox prepend)
   5820 	  (when (cdr (assq 'checkbox org-list-automatic-rules))
   5821 	    '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
   5822 	      (0 (org-get-checkbox-statistics-face) prepend)))
   5823 	  ;; Description list items
   5824           '("\\(?:^[ \t]*[-+]\\|^[ \t]+[*]\\)[ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
   5825 	    1 'org-list-dt prepend)
   5826           ;; Inline export snippets
   5827           '("\\(@@\\)\\([a-z-]+:\\).*?\\(@@\\)"
   5828             (1 'font-lock-comment-face t)
   5829             (2 'org-tag t)
   5830             (3 'font-lock-comment-face t))
   5831 	  ;; ARCHIVEd headings
   5832 	  (list (concat
   5833 		 org-outline-regexp-bol
   5834 		 "\\(.*:" org-archive-tag ":.*\\)")
   5835 		'(1 'org-archived prepend))
   5836 	  ;; Specials
   5837 	  '(org-do-latex-and-related)
   5838 	  '(org-fontify-entities)
   5839 	  '(org-raise-scripts)
   5840 	  ;; Code
   5841 	  '(org-activate-code (1 'org-code t))
   5842 	  ;; COMMENT
   5843 	  (list (format
   5844 		 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
   5845 		 org-todo-regexp
   5846 		 org-comment-string)
   5847 		'(9 'org-special-keyword t))
   5848 	  ;; Blocks and meta lines
   5849 	  '(org-fontify-meta-lines-and-blocks)
   5850           '(org-fontify-inline-src-blocks)
   5851           ;; Citations.  When an activate processor is specified, if
   5852           ;; specified, try loading it beforehand.
   5853           (progn
   5854             (unless (null org-cite-activate-processor)
   5855               (org-cite-try-load-processor org-cite-activate-processor))
   5856             '(org-cite-activate)))))
   5857     (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
   5858     (run-hooks 'org-font-lock-set-keywords-hook)
   5859     ;; Now set the full font-lock-keywords
   5860     (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
   5861     (setq-local font-lock-defaults
   5862 		'(org-font-lock-keywords t nil nil backward-paragraph))
   5863     (setq-local font-lock-extend-after-change-region-function
   5864 		#'org-fontify-extend-region)
   5865     (kill-local-variable 'font-lock-keywords)
   5866     nil))
   5867 
   5868 (defun org-toggle-pretty-entities ()
   5869   "Toggle the composition display of entities as UTF8 characters."
   5870   (interactive)
   5871   (setq-local org-pretty-entities (not org-pretty-entities))
   5872   (org-restart-font-lock)
   5873   (if org-pretty-entities
   5874       (message "Entities are now displayed as UTF8 characters")
   5875     (save-restriction
   5876       (widen)
   5877       (decompose-region (point-min) (point-max))
   5878       (message "Entities are now displayed as plain text"))))
   5879 
   5880 (defvar-local org-custom-properties-overlays nil
   5881   "List of overlays used for custom properties.")
   5882 
   5883 (defun org-toggle-custom-properties-visibility ()
   5884   "Display or hide properties in `org-custom-properties'."
   5885   (interactive)
   5886   (if org-custom-properties-overlays
   5887       (progn (mapc #'delete-overlay org-custom-properties-overlays)
   5888 	     (setq org-custom-properties-overlays nil))
   5889     (when org-custom-properties
   5890       (org-with-wide-buffer
   5891        (goto-char (point-min))
   5892        (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
   5893 	 (while (re-search-forward regexp nil t)
   5894 	   (let ((end (cdr (save-match-data (org-get-property-block)))))
   5895 	     (when (and end (< (point) end))
   5896 	       ;; Hide first custom property in current drawer.
   5897 	       (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
   5898 		 (overlay-put o 'invisible t)
   5899 		 (overlay-put o 'org-custom-property t)
   5900 		 (push o org-custom-properties-overlays))
   5901 	       ;; Hide additional custom properties in the same drawer.
   5902 	       (while (re-search-forward regexp end t)
   5903 		 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
   5904 		   (overlay-put o 'invisible t)
   5905 		   (overlay-put o 'org-custom-property t)
   5906 		   (push o org-custom-properties-overlays)))))
   5907 	   ;; Each entry is limited to a single property drawer.
   5908 	   (outline-next-heading)))))))
   5909 
   5910 (defun org-fontify-entities (limit)
   5911   "Find an entity to fontify."
   5912   (let (ee)
   5913     (when org-pretty-entities
   5914       (catch 'match
   5915 	;; "\_ "-family is left out on purpose.  Only the first one,
   5916 	;; i.e., "\_ ", could be fontified anyway, and it would be
   5917 	;; confusing when adding a second white space character.
   5918 	(while (re-search-forward
   5919 		"\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
   5920 		limit t)
   5921 	  (when (and (not (org-at-comment-p))
   5922 		     (setq ee (org-entity-get (match-string 1)))
   5923 		     (= (length (nth 6 ee)) 1))
   5924 	    (let* ((end (if (equal (match-string 2) "{}")
   5925 			    (match-end 2)
   5926 			  (match-end 1))))
   5927 	      (add-text-properties
   5928 	       (match-beginning 0) end
   5929 	       (list 'font-lock-fontified t))
   5930 	      (compose-region (match-beginning 0) end
   5931 			      (nth 6 ee) nil)
   5932 	      (backward-char 1)
   5933 	      (throw 'match t))))
   5934 	nil))))
   5935 
   5936 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
   5937   "Fontify string S like in Org mode."
   5938   (with-temp-buffer
   5939     (insert s)
   5940     (let ((org-odd-levels-only odd-levels))
   5941       (org-mode)
   5942       (font-lock-ensure)
   5943       (if org-link-descriptive
   5944           (org-link-display-format
   5945            (buffer-string))
   5946         (buffer-string)))))
   5947 
   5948 (defun org-get-level-face (n)
   5949   "Get the right face for match N in font-lock matching of headlines."
   5950   (let* ((org-l0 (- (match-end 2) (match-beginning 1) 1))
   5951 	 (org-l (if org-odd-levels-only (1+ (/ org-l0 2)) org-l0))
   5952 	 (org-f (if org-cycle-level-faces
   5953 		    (nth (% (1- org-l) org-n-level-faces) org-level-faces)
   5954 		  (nth (1- (min org-l org-n-level-faces)) org-level-faces))))
   5955     (cond
   5956      ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
   5957      ((eq n 2) org-f)
   5958      (t (unless org-level-color-stars-only org-f)))))
   5959 
   5960 (defun org-face-from-face-or-color (context inherit face-or-color)
   5961   "Create a face list that inherits INHERIT, but sets the foreground color.
   5962 When FACE-OR-COLOR is not a string, just return it."
   5963   (if (stringp face-or-color)
   5964       (list :inherit inherit
   5965 	    (cdr (assoc context org-faces-easy-properties))
   5966 	    face-or-color)
   5967     face-or-color))
   5968 
   5969 (defun org-get-todo-face (kwd)
   5970   "Get the right face for a TODO keyword KWD.
   5971 If KWD is a number, get the corresponding match group."
   5972   (when (numberp kwd) (setq kwd (match-string kwd)))
   5973   (or (org-face-from-face-or-color
   5974        'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
   5975       (and (member kwd org-done-keywords) 'org-done)
   5976       'org-todo))
   5977 
   5978 (defun org-get-priority-face (priority)
   5979   "Get the right face for PRIORITY.
   5980 PRIORITY is a character."
   5981   (or (org-face-from-face-or-color
   5982        'priority 'org-priority (cdr (assq priority org-priority-faces)))
   5983       'org-priority))
   5984 
   5985 (defun org-get-tag-face (tag)
   5986   "Get the right face for TAG.
   5987 If TAG is a number, get the corresponding match group."
   5988   (let ((tag (if (wholenump tag) (match-string tag) tag)))
   5989     (or (org-face-from-face-or-color
   5990 	 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
   5991 	'org-tag)))
   5992 
   5993 (defvar org-priority-regexp) ; defined later in the file
   5994 
   5995 (defun org-font-lock-add-priority-faces (limit)
   5996   "Add the special priority faces."
   5997   (while (re-search-forward (concat "^\\*+" org-priority-regexp) limit t)
   5998     (let ((beg (match-beginning 1))
   5999 	  (end (1+ (match-end 2))))
   6000       (add-face-text-property
   6001        beg end
   6002        (org-get-priority-face (string-to-char (match-string 2))))
   6003       (add-text-properties
   6004        beg end
   6005        (list 'font-lock-fontified t)))))
   6006 
   6007 (defun org-font-lock-add-tag-faces (limit)
   6008   "Add the special tag faces."
   6009   (when (and org-tag-faces org-tags-special-faces-re)
   6010     (while (re-search-forward org-tags-special-faces-re limit t)
   6011       (add-face-text-property
   6012        (match-beginning 1)
   6013        (match-end 1)
   6014        (org-get-tag-face 1))
   6015       (add-text-properties (match-beginning 1) (match-end 1)
   6016 			   (list 'font-lock-fontified t))
   6017       (backward-char 1))))
   6018 
   6019 (defun org-unfontify-region (beg end &optional _maybe_loudly)
   6020   "Remove fontification and activation overlays from links."
   6021   (font-lock-default-unfontify-region beg end)
   6022   (with-silent-modifications
   6023     (decompose-region beg end)
   6024     (remove-text-properties beg end
   6025 			    '(mouse-face t keymap t org-linked-text t
   6026 					 invisible t intangible t
   6027 					 org-emphasis t))
   6028     (org-fold-region beg end nil 'org-link)
   6029     (org-fold-region beg end nil 'org-link-description)
   6030     (org-fold-core-update-optimisation beg end)
   6031     (org-remove-font-lock-display-properties beg end)))
   6032 
   6033 (defconst org-script-display  '(((raise -0.3) (height 0.7))
   6034 				((raise 0.3)  (height 0.7))
   6035 				((raise -0.5))
   6036 				((raise 0.5)))
   6037   "Display properties for showing superscripts and subscripts.")
   6038 
   6039 (defun org-remove-font-lock-display-properties (beg end)
   6040   "Remove specific display properties that have been added by font lock.
   6041 The will remove the raise properties that are used to show superscripts
   6042 and subscripts."
   6043   (let (next prop)
   6044     (while (< beg end)
   6045       (setq next (next-single-property-change beg 'display nil end)
   6046 	    prop (get-text-property beg 'display))
   6047       (when (member prop org-script-display)
   6048 	(put-text-property beg next 'display nil))
   6049       (setq beg next))))
   6050 
   6051 (defun org-raise-scripts (limit)
   6052   "Add raise properties to sub/superscripts."
   6053   (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
   6054 	     (re-search-forward
   6055 	      (if (eq org-use-sub-superscripts t)
   6056 		  org-match-substring-regexp
   6057 		org-match-substring-with-braces-regexp)
   6058 	      limit t))
   6059     (let* ((pos (point)) table-p comment-p
   6060 	   (mpos (match-beginning 3))
   6061 	   (emph-p (get-text-property mpos 'org-emphasis))
   6062 	   (link-p (get-text-property mpos 'mouse-face))
   6063 	   (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
   6064       (goto-char (line-beginning-position))
   6065       (setq table-p (looking-at-p org-table-dataline-regexp)
   6066 	    comment-p (looking-at-p "^[ \t]*#[ +]"))
   6067       (goto-char pos)
   6068       ;; Handle a_b^c
   6069       (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
   6070       (unless (or comment-p emph-p link-p keyw-p)
   6071 	(put-text-property (match-beginning 3) (match-end 0)
   6072 			   'display
   6073 			   (if (equal (char-after (match-beginning 2)) ?^)
   6074 			       (nth (if table-p 3 1) org-script-display)
   6075 			     (nth (if table-p 2 0) org-script-display)))
   6076         (put-text-property (match-beginning 2) (match-end 3)
   6077                            'org-emphasis t)
   6078 	(add-text-properties (match-beginning 2) (match-end 2)
   6079 			     (list 'invisible t))
   6080 	(when (and (eq (char-after (match-beginning 3)) ?{)
   6081 		   (eq (char-before (match-end 3)) ?}))
   6082 	  (add-text-properties (match-beginning 3) (1+ (match-beginning 3))
   6083 			       (list 'invisible t))
   6084 	  (add-text-properties (1- (match-end 3)) (match-end 3)
   6085 			       (list 'invisible t))))
   6086       t)))
   6087 
   6088 (defun org-remove-empty-overlays-at (pos)
   6089   "Remove outline overlays that do not contain non-white stuff."
   6090   (dolist (o (overlays-at pos))
   6091     (and (eq 'outline (overlay-get o 'invisible))
   6092 	 (not (string-match-p
   6093                "\\S-" (buffer-substring (overlay-start o)
   6094 					(overlay-end o))))
   6095 	 (delete-overlay o))))
   6096 
   6097 ;; FIXME: This function is unused.
   6098 (defun org-show-empty-lines-in-parent ()
   6099   "Move to the parent and re-show empty lines before visible headlines."
   6100   (save-excursion
   6101     (let ((context (if (org-up-heading-safe) 'children 'overview)))
   6102       (org-cycle-show-empty-lines context))))
   6103 
   6104 (defun org-files-list ()
   6105   "Return `org-agenda-files' list, plus all open Org files.
   6106 This is useful for operations that need to scan all of a user's
   6107 open and agenda-wise Org files."
   6108   (let ((files (mapcar #'expand-file-name (org-agenda-files))))
   6109     (dolist (buf (buffer-list))
   6110       (with-current-buffer buf
   6111 	(when (and (derived-mode-p 'org-mode) (buffer-file-name))
   6112 	  (cl-pushnew (expand-file-name (buffer-file-name)) files
   6113 		      :test #'equal))))
   6114     files))
   6115 
   6116 (defsubst org-entry-beginning-position ()
   6117   "Return the beginning position of the current entry."
   6118   (save-excursion (org-back-to-heading t) (point)))
   6119 
   6120 (defsubst org-entry-end-position ()
   6121   "Return the end position of the current entry."
   6122   (save-excursion (outline-next-heading) (point)))
   6123 
   6124 (defun org-subtree-end-visible-p ()
   6125   "Is the end of the current subtree visible?"
   6126   (pos-visible-in-window-p
   6127    (save-excursion (org-end-of-subtree t) (point))))
   6128 
   6129 (defun org-first-headline-recenter ()
   6130   "Move cursor to the first headline and recenter the headline."
   6131   (let ((window (get-buffer-window)))
   6132     (when window
   6133       (goto-char (point-min))
   6134       (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
   6135 	(set-window-start window (line-beginning-position))))))
   6136 
   6137 
   6138 
   6139 ;; FIXME: It was in the middle of visibility section. Where should it go to?
   6140 (defvar org-called-with-limited-levels nil
   6141   "Non-nil when `org-with-limited-levels' is currently active.")
   6142 
   6143 
   6144 ;;; Indirect buffer display of subtrees
   6145 
   6146 (defvar org-indirect-dedicated-frame nil
   6147   "This is the frame being used for indirect tree display.")
   6148 (defvar org-last-indirect-buffer nil)
   6149 
   6150 (defun org-tree-to-indirect-buffer (&optional arg)
   6151   "Create indirect buffer and narrow it to current subtree.
   6152 
   6153 With a numerical prefix ARG, go up to this level and then take that tree.
   6154 If ARG is negative, go up that many levels.
   6155 
   6156 If `org-indirect-buffer-display' is not `new-frame', the command removes the
   6157 indirect buffer previously made with this command, to avoid proliferation of
   6158 indirect buffers.  However, when you call the command with a \
   6159 `\\[universal-argument]' prefix, or
   6160 when `org-indirect-buffer-display' is `new-frame', the last buffer is kept
   6161 so that you can work with several indirect buffers at the same time.  If
   6162 `org-indirect-buffer-display' is `dedicated-frame', the \
   6163 `\\[universal-argument]' prefix also
   6164 requests that a new frame be made for the new buffer, so that the dedicated
   6165 frame is not changed."
   6166   (interactive "P")
   6167   (let ((cbuf (current-buffer))
   6168 	(cwin (selected-window))
   6169 	(pos (point))
   6170 	beg end level heading ibuf)
   6171     (save-excursion
   6172       (org-back-to-heading t)
   6173       (when (numberp arg)
   6174 	(setq level (org-outline-level))
   6175 	(when (< arg 0) (setq arg (+ level arg)))
   6176 	(while (> (setq level (org-outline-level)) arg)
   6177 	  (org-up-heading-safe)))
   6178       (setq beg (point)
   6179 	    heading (org-get-heading 'no-tags))
   6180       (org-end-of-subtree t t)
   6181       (when (and (not (eobp)) (org-at-heading-p)) (backward-char 1))
   6182       (setq end (point)))
   6183     (when (and (buffer-live-p org-last-indirect-buffer)
   6184 	       (not (eq org-indirect-buffer-display 'new-frame))
   6185 	       (not arg))
   6186       (kill-buffer org-last-indirect-buffer))
   6187     (setq ibuf (org-get-indirect-buffer cbuf heading)
   6188 	  org-last-indirect-buffer ibuf)
   6189     (cond
   6190      ((or (eq org-indirect-buffer-display 'new-frame)
   6191 	  (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
   6192       (select-frame (make-frame))
   6193       (delete-other-windows)
   6194       (pop-to-buffer-same-window ibuf)
   6195       (org-set-frame-title heading))
   6196      ((eq org-indirect-buffer-display 'dedicated-frame)
   6197       (raise-frame
   6198        (select-frame (or (and org-indirect-dedicated-frame
   6199 			      (frame-live-p org-indirect-dedicated-frame)
   6200 			      org-indirect-dedicated-frame)
   6201 			 (setq org-indirect-dedicated-frame (make-frame)))))
   6202       (delete-other-windows)
   6203       (pop-to-buffer-same-window ibuf)
   6204       (org-set-frame-title (concat "Indirect: " heading)))
   6205      ((eq org-indirect-buffer-display 'current-window)
   6206       (pop-to-buffer-same-window ibuf))
   6207      ((eq org-indirect-buffer-display 'other-window)
   6208       (pop-to-buffer ibuf))
   6209      (t (error "Invalid value")))
   6210     (narrow-to-region beg end)
   6211     (org-fold-show-all '(headings drawers blocks))
   6212     (goto-char pos)
   6213     (run-hook-with-args 'org-cycle-hook 'all)
   6214     (and (window-live-p cwin) (select-window cwin))))
   6215 
   6216 (cl-defun org-get-indirect-buffer (&optional (buffer (current-buffer)) heading)
   6217   "Return an indirect buffer based on BUFFER.
   6218 If HEADING, append it to the name of the new buffer."
   6219   (let* ((base-buffer (or (buffer-base-buffer buffer) buffer))
   6220          (buffer-name (generate-new-buffer-name
   6221                        (format "%s%s"
   6222                                (buffer-name base-buffer)
   6223                                (if heading
   6224                                    (concat "::" heading)
   6225                                  ""))))
   6226          (indirect-buffer (make-indirect-buffer base-buffer buffer-name 'clone)))
   6227     ;; Decouple folding state.  We need to do it manually since
   6228     ;; `make-indirect-buffer' does not run
   6229     ;; `clone-indirect-buffer-hook'.
   6230     (org-fold-core-decouple-indirect-buffer-folds)
   6231     indirect-buffer))
   6232 
   6233 (defun org-set-frame-title (title)
   6234   "Set the title of the current frame to the string TITLE."
   6235   (modify-frame-parameters (selected-frame) (list (cons 'name title))))
   6236 
   6237 ;;;; Structure editing
   6238 
   6239 ;;; Inserting headlines
   6240 
   6241 (defun org--blank-before-heading-p (&optional parent)
   6242   "Non-nil when an empty line should precede a new heading here.
   6243 When optional argument PARENT is non-nil, consider parent
   6244 headline instead of current one."
   6245   (pcase (assq 'heading org-blank-before-new-entry)
   6246     (`(heading . auto)
   6247      (save-excursion
   6248        (org-with-limited-levels
   6249         (unless (and (org-before-first-heading-p)
   6250                      (not (outline-next-heading)))
   6251           (org-back-to-heading t)
   6252           (when parent (org-up-heading-safe))
   6253           (cond ((not (bobp))
   6254                  (org-previous-line-empty-p))
   6255 		((outline-next-heading)
   6256 		 (org-previous-line-empty-p))
   6257 		;; Ignore trailing spaces on last buffer line.
   6258 		((progn (skip-chars-backward " \t") (bolp))
   6259 		 (org-previous-line-empty-p))
   6260 		(t nil))))))
   6261     (`(heading . ,value) value)
   6262     (_ nil)))
   6263 
   6264 (defun org-insert-heading (&optional arg invisible-ok top)
   6265   "Insert a new heading or an item with the same depth at point.
   6266 
   6267 If point is at the beginning of a heading, insert a new heading
   6268 or a new headline above the current one.  When at the beginning
   6269 of a regular line of text, turn it into a heading.
   6270 
   6271 If point is in the middle of a line, split it and create a new
   6272 headline with the text in the current line after point (see
   6273 `org-M-RET-may-split-line' on how to modify this behavior).  As
   6274 a special case, on a headline, splitting can only happen on the
   6275 title itself.  E.g., this excludes breaking stars or tags.
   6276 
   6277 With a `\\[universal-argument]' prefix, set \
   6278 `org-insert-heading-respect-content' to
   6279 a non-nil value for the duration of the command.  This forces the
   6280 insertion of a heading after the current subtree, independently
   6281 on the location of point.
   6282 
   6283 With a `\\[universal-argument] \\[universal-argument]' prefix, \
   6284 insert the heading at the end of the tree
   6285 above the current heading.  For example, if point is within a
   6286 2nd-level heading, then it will insert a 2nd-level heading at
   6287 the end of the 1st-level parent subtree.
   6288 
   6289 When INVISIBLE-OK is set, stop at invisible headlines when going
   6290 back.  This is important for non-interactive uses of the
   6291 command.
   6292 
   6293 When optional argument TOP is non-nil, insert a level 1 heading,
   6294 unconditionally."
   6295   (interactive "P")
   6296   (let* ((blank? (org--blank-before-heading-p (equal arg '(16))))
   6297 	 (level (org-current-level))
   6298 	 (stars (make-string (if (and level (not top)) level 1) ?*)))
   6299     (cond
   6300      ((or org-insert-heading-respect-content
   6301 	  (member arg '((4) (16)))
   6302 	  (and (not invisible-ok)
   6303 	       (invisible-p (max (1- (point)) (point-min)))))
   6304       ;; Position point at the location of insertion.  Make sure we
   6305       ;; end up on a visible headline if INVISIBLE-OK is nil.
   6306       (org-with-limited-levels
   6307        (if (not level) (outline-next-heading) ;before first headline
   6308 	 (org-back-to-heading invisible-ok)
   6309 	 (when (equal arg '(16)) (org-up-heading-safe))
   6310 	 (org-end-of-subtree)))
   6311       (unless (bolp) (insert "\n"))
   6312       (when (and blank? (save-excursion
   6313                           (backward-char)
   6314                           (org-before-first-heading-p)))
   6315         (insert "\n")
   6316         (backward-char))
   6317       (when (and (not level) (not (eobp)) (not (bobp)))
   6318         (when (org-at-heading-p) (insert "\n"))
   6319         (backward-char))
   6320       (unless (and blank? (org-previous-line-empty-p))
   6321 	(org-N-empty-lines-before-current (if blank? 1 0)))
   6322       (insert stars " ")
   6323       ;; When INVISIBLE-OK is non-nil, ensure newly created headline
   6324       ;; is visible.
   6325       (unless invisible-ok
   6326         (if (eq org-fold-core-style 'text-properties)
   6327 	    (cond
   6328 	     ((org-fold-folded-p
   6329                (max (point-min)
   6330                     (1- (line-beginning-position)))
   6331                'headline)
   6332 	      (org-fold-region (line-end-position 0) (line-end-position) nil 'headline))
   6333 	     (t nil))
   6334           (pcase (get-char-property-and-overlay (point) 'invisible)
   6335 	    (`(outline . ,o)
   6336 	     (move-overlay o (overlay-start o) (line-end-position 0)))
   6337 	    (_ nil)))))
   6338      ;; At a headline...
   6339      ((org-at-heading-p)
   6340       (cond ((bolp)
   6341 	     (when blank? (save-excursion (insert "\n")))
   6342 	     (save-excursion (insert stars " \n"))
   6343 	     (unless (and blank? (org-previous-line-empty-p))
   6344 	       (org-N-empty-lines-before-current (if blank? 1 0)))
   6345 	     (end-of-line))
   6346 	    ((and (org-get-alist-option org-M-RET-may-split-line 'headline)
   6347 		  (org-match-line org-complex-heading-regexp)
   6348 		  (org-pos-in-match-range (point) 4))
   6349 	     ;; Grab the text that should moved to the new headline.
   6350 	     ;; Preserve tags.
   6351 	     (let ((split (delete-and-extract-region (point) (match-end 4))))
   6352 	       (if (looking-at "[ \t]*$") (replace-match "")
   6353 		 (org-align-tags))
   6354 	       (end-of-line)
   6355 	       (when blank? (insert "\n"))
   6356 	       (insert "\n" stars " ")
   6357 	       (when (org-string-nw-p split) (insert split))))
   6358 	    (t
   6359 	     (end-of-line)
   6360 	     (when blank? (insert "\n"))
   6361 	     (insert "\n" stars " "))))
   6362      ;; On regular text, turn line into a headline or split, if
   6363      ;; appropriate.
   6364      ((bolp)
   6365       (insert stars " ")
   6366       (unless (and blank? (org-previous-line-empty-p))
   6367         (org-N-empty-lines-before-current (if blank? 1 0))))
   6368      (t
   6369       (unless (org-get-alist-option org-M-RET-may-split-line 'headline)
   6370         (end-of-line))
   6371       (insert "\n" stars " ")
   6372       (unless (and blank? (org-previous-line-empty-p))
   6373         (org-N-empty-lines-before-current (if blank? 1 0))))))
   6374   (run-hooks 'org-insert-heading-hook))
   6375 
   6376 (defun org-N-empty-lines-before-current (n)
   6377   "Make the number of empty lines before current exactly N.
   6378 So this will delete or add empty lines."
   6379   (let ((column (current-column)))
   6380     (beginning-of-line)
   6381     (unless (bobp)
   6382       (let ((start (save-excursion
   6383 		     (skip-chars-backward " \r\t\n")
   6384 		     (line-end-position))))
   6385 	(delete-region start (line-end-position 0))))
   6386     (insert (make-string n ?\n))
   6387     (move-to-column column)))
   6388 
   6389 (defun org-get-heading (&optional no-tags no-todo no-priority no-comment)
   6390   "Return the heading of the current entry, without the stars.
   6391 When NO-TAGS is non-nil, don't include tags.
   6392 When NO-TODO is non-nil, don't include TODO keywords.
   6393 When NO-PRIORITY is non-nil, don't include priority cookie.
   6394 When NO-COMMENT is non-nil, don't include COMMENT string.
   6395 Return nil before first heading."
   6396   (unless (org-before-first-heading-p)
   6397     (save-excursion
   6398       (org-back-to-heading t)
   6399       (let ((case-fold-search nil))
   6400 	(looking-at org-complex-heading-regexp)
   6401         ;; When using `org-fold-core--optimise-for-huge-buffers',
   6402         ;; returned text will be invisible.  Clear it up.
   6403         (save-match-data
   6404           (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0)))
   6405         (let ((todo (and (not no-todo) (match-string 2)))
   6406 	      (priority (and (not no-priority) (match-string 3)))
   6407 	      (headline (pcase (match-string 4)
   6408 			  (`nil "")
   6409 			  ((and (guard no-comment) h)
   6410 			   (replace-regexp-in-string
   6411 			    (eval-when-compile
   6412 			      (format "\\`%s[ \t]+" org-comment-string))
   6413 			    "" h))
   6414 			  (h h)))
   6415 	      (tags (and (not no-tags) (match-string 5))))
   6416           ;; Restore cleared optimization.
   6417           (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))
   6418 	  (mapconcat #'identity
   6419 		     (delq nil (list todo priority headline tags))
   6420 		     " "))))))
   6421 
   6422 (defun org-heading-components ()
   6423   "Return the components of the current heading.
   6424 This is a list with the following elements:
   6425 - the level as an integer
   6426 - the reduced level, different if `org-odd-levels-only' is set.
   6427 - the TODO keyword, or nil
   6428 - the priority character, like ?A, or nil if no priority is given
   6429 - the headline text itself, or the tags string if no headline text
   6430 - the tags string, or nil."
   6431   (save-excursion
   6432     (org-back-to-heading t)
   6433     (when (let (case-fold-search) (looking-at org-complex-heading-regexp))
   6434       (org-fold-core-remove-optimisation (match-beginning 0) (match-end 0))
   6435       (prog1
   6436           (list (length (match-string 1))
   6437 	        (org-reduced-level (length (match-string 1)))
   6438 	        (match-string-no-properties 2)
   6439 	        (and (match-end 3) (aref (match-string 3) 2))
   6440 	        (match-string-no-properties 4)
   6441 	        (match-string-no-properties 5))
   6442         (org-fold-core-update-optimisation (match-beginning 0) (match-end 0))))))
   6443 
   6444 (defun org-get-entry ()
   6445   "Get the entry text, after heading, entire subtree."
   6446   (save-excursion
   6447     (org-back-to-heading t)
   6448     (filter-buffer-substring (line-beginning-position 2) (org-end-of-subtree t))))
   6449 
   6450 (defun org-edit-headline (&optional heading)
   6451   "Edit the current headline.
   6452 Set it to HEADING when provided."
   6453   (interactive)
   6454   (org-with-wide-buffer
   6455    (org-back-to-heading t)
   6456    (let ((case-fold-search nil))
   6457      (when (looking-at org-complex-heading-regexp)
   6458        (let* ((old (match-string-no-properties 4))
   6459 	      (new (save-match-data
   6460 		     (org-trim (or heading (read-string "Edit: " old))))))
   6461 	 (unless (equal old new)
   6462 	   (if old (replace-match new t t nil 4)
   6463 	     (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
   6464 	     (insert " " new))
   6465 	   (org-align-tags)
   6466 	   (when (looking-at "[ \t]*$") (replace-match ""))))))))
   6467 
   6468 (defun org-insert-heading-after-current ()
   6469   "Insert a new heading with same level as current, after current subtree."
   6470   (interactive)
   6471   (org-back-to-heading)
   6472   (org-insert-heading)
   6473   (org-move-subtree-down)
   6474   (end-of-line 1))
   6475 
   6476 (defun org-insert-heading-respect-content (&optional invisible-ok)
   6477   "Insert heading with `org-insert-heading-respect-content' set to t."
   6478   (interactive)
   6479   (org-insert-heading '(4) invisible-ok))
   6480 
   6481 (defun org-insert-todo-heading-respect-content (&optional _)
   6482   "Insert TODO heading with `org-insert-heading-respect-content' set to t."
   6483   (interactive)
   6484   (let ((org-insert-heading-respect-content t))
   6485     (org-insert-todo-heading '(4) t)))
   6486 
   6487 (defun org-insert-todo-heading (arg &optional force-heading)
   6488   "Insert a new heading with the same level and TODO state as current heading.
   6489 
   6490 If the heading has no TODO state, or if the state is DONE, use
   6491 the first state (TODO by default).  Also with one prefix arg,
   6492 force first state.  With two prefix args, force inserting at the
   6493 end of the parent subtree.
   6494 
   6495 When called at a plain list item, insert a new item with an
   6496 unchecked check box."
   6497   (interactive "P")
   6498   (when (or force-heading (not (org-insert-item 'checkbox)))
   6499     (org-insert-heading (or (and (equal arg '(16)) '(16))
   6500 			    force-heading))
   6501     (save-excursion
   6502       (org-forward-heading-same-level -1)
   6503       (let ((case-fold-search nil)) (looking-at org-todo-line-regexp)))
   6504     (let* ((new-mark-x
   6505 	    (if (or (equal arg '(4))
   6506 		    (not (match-beginning 2))
   6507 		    (member (match-string 2) org-done-keywords))
   6508 		(car org-todo-keywords-1)
   6509 	      (match-string 2)))
   6510 	   (new-mark
   6511 	    (or
   6512 	     (run-hook-with-args-until-success
   6513 	      'org-todo-get-default-hook new-mark-x nil)
   6514 	     new-mark-x)))
   6515       (beginning-of-line 1)
   6516       (and (looking-at org-outline-regexp) (goto-char (match-end 0))
   6517 	   (if org-treat-insert-todo-heading-as-state-change
   6518 	       (org-todo new-mark)
   6519 	     (insert new-mark " "))))
   6520     (when org-provide-todo-statistics
   6521       (org-update-parent-todo-statistics))))
   6522 
   6523 (defun org-insert-subheading (arg)
   6524   "Insert a new subheading and demote it.
   6525 Works for outline headings and for plain lists alike."
   6526   (interactive "P")
   6527   (org-insert-heading arg)
   6528   (cond
   6529    ((org-at-heading-p) (org-do-demote))
   6530    ((org-at-item-p) (org-indent-item))))
   6531 
   6532 (defun org-insert-todo-subheading (arg)
   6533   "Insert a new subheading with TODO keyword or checkbox and demote it.
   6534 Works for outline headings and for plain lists alike."
   6535   (interactive "P")
   6536   (org-insert-todo-heading arg)
   6537   (cond
   6538    ((org-at-heading-p) (org-do-demote))
   6539    ((org-at-item-p) (org-indent-item))))
   6540 
   6541 ;;; Promotion and Demotion
   6542 
   6543 (defvar org-after-demote-entry-hook nil
   6544   "Hook run after an entry has been demoted.
   6545 The cursor will be at the beginning of the entry.
   6546 When a subtree is being demoted, the hook will be called for each node.")
   6547 
   6548 (defvar org-after-promote-entry-hook nil
   6549   "Hook run after an entry has been promoted.
   6550 The cursor will be at the beginning of the entry.
   6551 When a subtree is being promoted, the hook will be called for each node.")
   6552 
   6553 (defun org-promote-subtree ()
   6554   "Promote the entire subtree.
   6555 See also `org-promote'."
   6556   (interactive)
   6557   (save-excursion
   6558     (org-back-to-heading t)
   6559     (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
   6560       (org-with-limited-levels (org-map-tree 'org-promote))))
   6561   (org-fix-position-after-promote))
   6562 
   6563 (defun org-demote-subtree ()
   6564   "Demote the entire subtree.
   6565 See `org-demote' and `org-promote'."
   6566   (interactive)
   6567   (save-excursion
   6568     (org-back-to-heading t)
   6569     (combine-change-calls (point) (save-excursion (org-end-of-subtree t))
   6570       (org-with-limited-levels (org-map-tree 'org-demote))))
   6571   (org-fix-position-after-promote))
   6572 
   6573 (defun org-do-promote ()
   6574   "Promote the current heading higher up the tree.
   6575 If the region is active in `transient-mark-mode', promote all
   6576 headings in the region."
   6577   (interactive)
   6578   (save-excursion
   6579     (if (org-region-active-p)
   6580 	(org-map-region 'org-promote (region-beginning) (region-end))
   6581       (org-promote)))
   6582   (org-fix-position-after-promote))
   6583 
   6584 (defun org-do-demote ()
   6585   "Demote the current heading lower down the tree.
   6586 If the region is active in `transient-mark-mode', demote all
   6587 headings in the region."
   6588   (interactive)
   6589   (save-excursion
   6590     (if (org-region-active-p)
   6591 	(org-map-region 'org-demote (region-beginning) (region-end))
   6592       (org-demote)))
   6593   (org-fix-position-after-promote))
   6594 
   6595 (defun org-fix-position-after-promote ()
   6596   "Fix cursor position and indentation after demoting/promoting."
   6597   (let ((pos (point)))
   6598     (when (save-excursion
   6599 	    (beginning-of-line)
   6600 	    (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
   6601 	    (or (eq pos (match-end 1)) (eq pos (match-end 2))))
   6602       (cond ((eobp) (insert " "))
   6603 	    ((eolp) (insert " "))
   6604 	    ((equal (char-after) ?\s) (forward-char 1))))))
   6605 
   6606 (defun org-current-level ()
   6607   "Return the level of the current entry, or nil if before the first headline.
   6608 The level is the number of stars at the beginning of the
   6609 headline.  Use `org-reduced-level' to remove the effect of
   6610 `org-odd-levels'.  Unlike to `org-outline-level', this function
   6611 ignores inlinetasks."
   6612   (let ((level (org-with-limited-levels (org-outline-level))))
   6613     (and (> level 0) level)))
   6614 
   6615 (defun org-get-previous-line-level ()
   6616   "Return the outline depth of the last headline before the current line.
   6617 Returns 0 for the first headline in the buffer, and nil if before the
   6618 first headline."
   6619   (and (org-current-level)
   6620        (or (and (/= (line-beginning-position) (point-min))
   6621 		(save-excursion (beginning-of-line 0) (org-current-level)))
   6622 	   0)))
   6623 
   6624 (defun org-reduced-level (l)
   6625   "Compute the effective level of a heading.
   6626 This takes into account the setting of `org-odd-levels-only'."
   6627   (cond
   6628    ((zerop l) 0)
   6629    (org-odd-levels-only (1+ (floor (/ l 2))))
   6630    (t l)))
   6631 
   6632 (defun org-level-increment ()
   6633   "Return the number of stars that will be added or removed at a
   6634 time to headlines when structure editing, based on the value of
   6635 `org-odd-levels-only'."
   6636   (if org-odd-levels-only 2 1))
   6637 
   6638 (defun org-get-valid-level (level &optional change)
   6639   "Rectify a level change under the influence of `org-odd-levels-only'.
   6640 LEVEL is a current level, CHANGE is by how much the level should
   6641 be modified.  Even if CHANGE is nil, LEVEL may be returned
   6642 modified because even level numbers will become the next higher
   6643 odd number.  Returns values greater than 0."
   6644   (if org-odd-levels-only
   6645       (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
   6646 	    ((> change 0) (1+ (* 2 (/ (+ (1- level) (* 2 change)) 2))))
   6647 	    ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
   6648     (max 1 (+ level (or change 0)))))
   6649 
   6650 (defun org-promote ()
   6651   "Promote the current heading higher up the tree."
   6652   (org-with-wide-buffer
   6653    (org-back-to-heading t)
   6654    (let* ((after-change-functions (remq 'flyspell-after-change-function
   6655 					after-change-functions))
   6656 	  (level (save-match-data (funcall outline-level)))
   6657 	  (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
   6658 	  (diff (abs (- level (length up-head) -1))))
   6659      (cond
   6660       ((and (= level 1) org-allow-promoting-top-level-subtree)
   6661        (replace-match "# " nil t))
   6662       ((= level 1)
   6663        (user-error "Cannot promote to level 0.  UNDO to recover if necessary"))
   6664       (t (replace-match (apply #'propertize up-head (text-properties-at (match-beginning 0))) t)))
   6665      (unless (= level 1)
   6666        (when org-auto-align-tags (org-align-tags))
   6667        (when org-adapt-indentation (org-fixup-indentation (- diff))))
   6668      (run-hooks 'org-after-promote-entry-hook))))
   6669 
   6670 (defun org-demote ()
   6671   "Demote the current heading lower down the tree."
   6672   (org-with-wide-buffer
   6673    (org-back-to-heading t)
   6674    (let* ((after-change-functions (remq 'flyspell-after-change-function
   6675 					after-change-functions))
   6676 	  (level (save-match-data (funcall outline-level)))
   6677 	  (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
   6678 	  (diff (abs (- level (length down-head) -1))))
   6679      (org-fold-core-ignore-fragility-checks
   6680        (replace-match (apply #'propertize down-head (text-properties-at (match-beginning 0))) t)
   6681        (when org-auto-align-tags (org-align-tags))
   6682        (when org-adapt-indentation (org-fixup-indentation diff)))
   6683      (run-hooks 'org-after-demote-entry-hook))))
   6684 
   6685 (defun org-cycle-level ()
   6686   "Cycle the level of an empty headline through possible states.
   6687 This goes first to child, then to parent, level, then up the hierarchy.
   6688 After top level, it switches back to sibling level."
   6689   (interactive)
   6690   (let ((org-adapt-indentation nil))
   6691     (when (org-point-at-end-of-empty-headline)
   6692       (setq this-command 'org-cycle-level) ; Only needed for caching
   6693       (let ((cur-level (org-current-level))
   6694             (prev-level (org-get-previous-line-level)))
   6695         (cond
   6696          ;; If first headline in file, promote to top-level.
   6697          ((= prev-level 0)
   6698           (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
   6699 		   do (org-do-promote)))
   6700          ;; If same level as prev, demote one.
   6701          ((= prev-level cur-level)
   6702           (org-do-demote))
   6703          ;; If parent is top-level, promote to top level if not already.
   6704          ((= prev-level 1)
   6705           (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
   6706 		   do (org-do-promote)))
   6707          ;; If top-level, return to prev-level.
   6708          ((= cur-level 1)
   6709           (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
   6710 		   do (org-do-demote)))
   6711          ;; If less than prev-level, promote one.
   6712          ((< cur-level prev-level)
   6713           (org-do-promote))
   6714          ;; If deeper than prev-level, promote until higher than
   6715          ;; prev-level.
   6716          ((> cur-level prev-level)
   6717           (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
   6718 		   do (org-do-promote))))
   6719         t))))
   6720 
   6721 (defun org-map-tree (fun)
   6722   "Call FUN for every heading underneath the current one."
   6723   (org-back-to-heading t)
   6724   (let ((level (funcall outline-level)))
   6725     (save-excursion
   6726       (funcall fun)
   6727       (while (and (progn
   6728 		    (outline-next-heading)
   6729 		    (> (funcall outline-level) level))
   6730 		  (not (eobp)))
   6731 	(funcall fun)))))
   6732 
   6733 (defun org-map-region (fun beg end)
   6734   "Call FUN for every heading between BEG and END."
   6735   (let ((org-ignore-region t))
   6736     (save-excursion
   6737       (setq end (copy-marker end))
   6738       (goto-char beg)
   6739       (when (and (re-search-forward org-outline-regexp-bol nil t)
   6740 		 (< (point) end))
   6741 	(funcall fun))
   6742       (while (and (progn
   6743 		    (outline-next-heading)
   6744 		    (< (point) end))
   6745 		  (not (eobp)))
   6746 	(funcall fun)))))
   6747 
   6748 (defun org-fixup-indentation (diff)
   6749   "Change the indentation in the current entry by DIFF.
   6750 
   6751 DIFF is an integer.  Indentation is done according to the
   6752 following rules:
   6753 
   6754   - Planning information and property drawers are always indented
   6755     according to the new level of the headline;
   6756 
   6757   - Footnote definitions and their contents are ignored;
   6758 
   6759   - Inlinetasks' boundaries are not shifted;
   6760 
   6761   - Empty lines are ignored;
   6762 
   6763   - Other lines' indentation are shifted by DIFF columns, unless
   6764     it would introduce a structural change in the document, in
   6765     which case no shifting is done at all.
   6766 
   6767 Assume point is at a heading or an inlinetask beginning."
   6768   (org-with-wide-buffer
   6769    (narrow-to-region (line-beginning-position)
   6770 		     (save-excursion
   6771 		       (if (org-with-limited-levels (org-at-heading-p))
   6772 			   (org-with-limited-levels (outline-next-heading))
   6773 			 (org-inlinetask-goto-end))
   6774 		       (point)))
   6775    (forward-line)
   6776    ;; Indent properly planning info and property drawer.
   6777    (when (looking-at-p org-planning-line-re)
   6778      (org-indent-line)
   6779      (forward-line))
   6780    (when (looking-at org-property-drawer-re)
   6781      (goto-char (match-end 0))
   6782      (forward-line)
   6783      (org-indent-region (match-beginning 0) (match-end 0)))
   6784    (when (looking-at org-logbook-drawer-re)
   6785      (let ((end-marker  (move-marker (make-marker) (match-end 0)))
   6786 	   (col (+ (current-indentation) diff)))
   6787        (when (wholenump col)
   6788 	 (while (< (point) end-marker)
   6789            (if (natnump diff)
   6790 	       (insert (make-string diff 32))
   6791              (delete-char (abs diff)))
   6792 	   (forward-line)))))
   6793    (catch 'no-shift
   6794      (when (or (zerop diff) (not (eq org-adapt-indentation t)))
   6795        (throw 'no-shift nil))
   6796      ;; If DIFF is negative, first check if a shift is possible at all
   6797      ;; (e.g., it doesn't break structure).  This can only happen if
   6798      ;; some contents are not properly indented.
   6799      (let ((case-fold-search t))
   6800        (when (< diff 0)
   6801 	 (let ((diff (- diff))
   6802 	       (forbidden-re (concat org-outline-regexp
   6803 				     "\\|"
   6804 				     (substring org-footnote-definition-re 1))))
   6805 	   (save-excursion
   6806 	     (while (not (eobp))
   6807 	       (cond
   6808 		((looking-at-p "[ \t]*$") (forward-line))
   6809 		((and (looking-at-p org-footnote-definition-re)
   6810 		      (let ((e (org-element-at-point)))
   6811 			(and (eq (org-element-type e) 'footnote-definition)
   6812 			     (goto-char (org-element-property :end e))))))
   6813 		((looking-at-p org-outline-regexp) (forward-line))
   6814 		;; Give up if shifting would move before column 0 or
   6815 		;; if it would introduce a headline or a footnote
   6816 		;; definition.
   6817 		(t
   6818 		 (skip-chars-forward " \t")
   6819 		 (let ((ind (current-column)))
   6820 		   (when (or (< ind diff)
   6821 			     (and (= ind diff) (looking-at-p forbidden-re)))
   6822 		     (throw 'no-shift nil)))
   6823 		 ;; Ignore contents of example blocks and source
   6824 		 ;; blocks if their indentation is meant to be
   6825 		 ;; preserved.  Jump to block's closing line.
   6826 		 (beginning-of-line)
   6827 		 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
   6828 			  (let ((e (org-element-at-point)))
   6829 			    (and (memq (org-element-type e)
   6830 				       '(example-block src-block))
   6831 				 (or org-src-preserve-indentation
   6832 				     (org-element-property :preserve-indent e))
   6833 				 (goto-char (org-element-property :end e))
   6834 				 (progn (skip-chars-backward " \r\t\n")
   6835 					(beginning-of-line)
   6836 					t))))
   6837 		     (forward-line))))))))
   6838        ;; Shift lines but footnote definitions, inlinetasks boundaries
   6839        ;; by DIFF.  Also skip contents of source or example blocks
   6840        ;; when indentation is meant to be preserved.
   6841        (while (not (eobp))
   6842 	 (cond
   6843 	  ((and (looking-at-p org-footnote-definition-re)
   6844 		(let ((e (org-element-at-point)))
   6845 		  (and (eq (org-element-type e) 'footnote-definition)
   6846 		       (goto-char (org-element-property :end e))))))
   6847 	  ((looking-at-p org-outline-regexp) (forward-line))
   6848 	  ((looking-at-p "[ \t]*$") (forward-line))
   6849 	  (t
   6850 	   (indent-line-to (+ (current-indentation) diff))
   6851 	   (beginning-of-line)
   6852 	   (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
   6853 		    (let ((e (org-element-at-point)))
   6854 		      (and (memq (org-element-type e)
   6855 				 '(example-block src-block))
   6856 			   (or org-src-preserve-indentation
   6857 			       (org-element-property :preserve-indent e))
   6858 			   (goto-char (org-element-property :end e))
   6859 			   (progn (skip-chars-backward " \r\t\n")
   6860 				  (beginning-of-line)
   6861 				  t))))
   6862 	       (forward-line)))))))))
   6863 
   6864 (defun org-convert-to-odd-levels ()
   6865   "Convert an Org file with all levels allowed to one with odd levels.
   6866 This will leave level 1 alone, convert level 2 to level 3, level 3 to
   6867 level 5 etc."
   6868   (interactive)
   6869   (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
   6870     (let ((outline-level 'org-outline-level)
   6871 	  (org-odd-levels-only nil) n)
   6872       (save-excursion
   6873 	(goto-char (point-min))
   6874 	(while (re-search-forward "^\\*\\*+ " nil t)
   6875 	  (setq n (- (length (match-string 0)) 2))
   6876 	  (while (>= (setq n (1- n)) 0)
   6877 	    (org-demote))
   6878 	  (end-of-line 1))))))
   6879 
   6880 (defun org-convert-to-oddeven-levels ()
   6881   "Convert an Org file with only odd levels to one with odd/even levels.
   6882 This promotes level 3 to level 2, level 5 to level 3 etc.  If the
   6883 file contains a section with an even level, conversion would
   6884 destroy the structure of the file.  An error is signaled in this
   6885 case."
   6886   (interactive)
   6887   (goto-char (point-min))
   6888   ;; First check if there are no even levels
   6889   (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
   6890     (org-fold-show-set-visibility 'canonical)
   6891     (error "Not all levels are odd in this file.  Conversion not possible"))
   6892   (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
   6893     (let ((outline-regexp org-outline-regexp)
   6894 	  (outline-level 'org-outline-level)
   6895 	  (org-odd-levels-only nil) n)
   6896       (save-excursion
   6897 	(goto-char (point-min))
   6898 	(while (re-search-forward "^\\*\\*+ " nil t)
   6899 	  (setq n (/ (1- (length (match-string 0))) 2))
   6900 	  (while (>= (setq n (1- n)) 0)
   6901 	    (org-promote))
   6902 	  (end-of-line 1))))))
   6903 
   6904 (defun org-tr-level (n)
   6905   "Make N odd if required."
   6906   (if org-odd-levels-only (1+ (/ n 2)) n))
   6907 
   6908 ;;; Vertical tree motion, cutting and pasting of subtrees
   6909 
   6910 (defun org-move-subtree-up (&optional arg)
   6911   "Move the current subtree up past ARG headlines of the same level."
   6912   (interactive "p")
   6913   (org-move-subtree-down (- (prefix-numeric-value arg))))
   6914 
   6915 (defun org-clean-visibility-after-subtree-move ()
   6916   "Fix visibility issues after moving a subtree."
   6917   ;; First, find a reasonable region to look at:
   6918   ;; Start two siblings above, end three below
   6919   (let* ((beg (save-excursion
   6920 		(and (org-get-previous-sibling)
   6921 		     (org-get-previous-sibling))
   6922 		(point)))
   6923 	 (end (save-excursion
   6924 		(and (org-get-next-sibling)
   6925 		     (org-get-next-sibling)
   6926 		     (org-get-next-sibling))
   6927 		(if (org-at-heading-p)
   6928 		    (line-end-position)
   6929 		  (point))))
   6930 	 (level (looking-at "\\*+"))
   6931 	 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
   6932     (save-excursion
   6933       (save-restriction
   6934 	(narrow-to-region beg end)
   6935 	(when re
   6936 	  ;; Properly fold already folded siblings
   6937 	  (goto-char (point-min))
   6938 	  (while (re-search-forward re nil t)
   6939 	    (when (and (not (org-invisible-p))
   6940 		       (org-invisible-p (line-end-position)))
   6941 	      (org-fold-heading nil))))
   6942 	(org-cycle-hide-drawers 'all)
   6943 	(org-cycle-show-empty-lines 'overview)))))
   6944 
   6945 (defun org-move-subtree-down (&optional arg)
   6946   "Move the current subtree down past ARG headlines of the same level."
   6947   (interactive "p")
   6948   (setq arg (prefix-numeric-value arg))
   6949   (org-preserve-local-variables
   6950    (let ((movfunc (if (> arg 0) 'org-get-next-sibling
   6951 		    'org-get-previous-sibling))
   6952 	 (ins-point (make-marker))
   6953 	 (cnt (abs arg))
   6954 	 (col (current-column))
   6955 	 beg end txt folded)
   6956      ;; Select the tree
   6957      (org-back-to-heading)
   6958      (setq beg (point))
   6959      (save-match-data
   6960        (save-excursion (outline-end-of-heading)
   6961 		       (setq folded (org-invisible-p)))
   6962        (progn (org-end-of-subtree nil t)
   6963 	      (unless (eobp) (backward-char))))
   6964      (outline-next-heading)
   6965      (setq end (point))
   6966      (goto-char beg)
   6967      ;; Find insertion point, with error handling
   6968      (while (> cnt 0)
   6969        (unless (and (funcall movfunc) (looking-at org-outline-regexp))
   6970 	 (goto-char beg)
   6971 	 (user-error "Cannot move past superior level or buffer limit"))
   6972        (setq cnt (1- cnt)))
   6973      (when (> arg 0)
   6974        ;; Moving forward - still need to move over subtree
   6975        (org-end-of-subtree t t)
   6976        (save-excursion
   6977 	 (org-back-over-empty-lines)
   6978 	 (or (bolp) (newline))))
   6979      (move-marker ins-point (point))
   6980      (setq txt (buffer-substring beg end))
   6981      (org-save-markers-in-region beg end)
   6982      (delete-region beg end)
   6983      (when (eq org-fold-core-style 'overlays) (org-remove-empty-overlays-at beg))
   6984      (unless (= beg (point-min)) (org-fold-region (1- beg) beg nil 'outline))
   6985      (unless (bobp) (org-fold-region (1- (point)) (point) nil 'outline))
   6986      (and (not (bolp)) (looking-at "\n") (forward-char 1))
   6987      (let ((bbb (point)))
   6988        (insert-before-markers txt)
   6989        (org-reinstall-markers-in-region bbb)
   6990        (move-marker ins-point bbb))
   6991      (or (bolp) (insert "\n"))
   6992      (goto-char ins-point)
   6993      (org-skip-whitespace)
   6994      (move-marker ins-point nil)
   6995      (if folded
   6996 	 (org-fold-subtree t)
   6997        (org-fold-show-entry 'hide-drawers)
   6998        (org-fold-show-children))
   6999      (org-clean-visibility-after-subtree-move)
   7000      ;; move back to the initial column we were at
   7001      (move-to-column col))))
   7002 
   7003 (defvar org-subtree-clip ""
   7004   "Clipboard for cut and paste of subtrees.
   7005 This is actually only a copy of the kill, because we use the normal kill
   7006 ring.  We need it to check if the kill was created by `org-copy-subtree'.")
   7007 
   7008 (defvar org-subtree-clip-folded nil
   7009   "Was the last copied subtree folded?
   7010 This is used to fold the tree back after pasting.")
   7011 
   7012 (defun org-cut-subtree (&optional n)
   7013   "Cut the current subtree into the clipboard.
   7014 With prefix arg N, cut this many sequential subtrees.
   7015 This is a short-hand for marking the subtree and then cutting it."
   7016   (interactive "p")
   7017   (org-copy-subtree n 'cut))
   7018 
   7019 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
   7020   "Copy the current subtree into the clipboard.
   7021 With prefix arg N, copy this many sequential subtrees.
   7022 This is a short-hand for marking the subtree and then copying it.
   7023 If CUT is non-nil, actually cut the subtree.
   7024 If FORCE-STORE-MARKERS is non-nil, store the relative locations
   7025 of some markers in the region, even if CUT is non-nil.  This is
   7026 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
   7027   (interactive "p")
   7028   (org-preserve-local-variables
   7029    (let (beg end folded (beg0 (point)))
   7030      (if (called-interactively-p 'any)
   7031 	 (org-back-to-heading nil)    ; take what looks like a subtree
   7032        (org-back-to-heading t))	      ; take what is really there
   7033      (setq beg (point))
   7034      (skip-chars-forward " \t\r\n")
   7035      (save-match-data
   7036        (if nosubtrees
   7037 	   (outline-next-heading)
   7038 	 (save-excursion (outline-end-of-heading)
   7039 			 (setq folded (org-invisible-p)))
   7040 	 (ignore-errors (org-forward-heading-same-level (1- n) t))
   7041 	 (org-end-of-subtree t t)))
   7042      ;; Include the end of an inlinetask
   7043      (when (and (featurep 'org-inlinetask)
   7044 		(looking-at-p (concat (org-inlinetask-outline-regexp)
   7045 				      "END[ \t]*$")))
   7046        (end-of-line))
   7047      (setq end (point))
   7048      (goto-char beg0)
   7049      (when (> end beg)
   7050        (setq org-subtree-clip-folded folded)
   7051        (when (or cut force-store-markers)
   7052 	 (org-save-markers-in-region beg end))
   7053        (if cut (kill-region beg end) (copy-region-as-kill beg end))
   7054        (setq org-subtree-clip (current-kill 0))
   7055        (message "%s: Subtree(s) with %d characters"
   7056 		(if cut "Cut" "Copied")
   7057 		(length org-subtree-clip))))))
   7058 
   7059 (defun org-paste-subtree (&optional level tree for-yank remove)
   7060   "Paste the clipboard as a subtree, with modification of headline level.
   7061 
   7062 The entire subtree is promoted or demoted in order to match a new headline
   7063 level.
   7064 
   7065 If the cursor is at the beginning of a headline, the same level as
   7066 that headline is used to paste the tree.
   7067 
   7068 If not, the new level is derived from the *visible* headings
   7069 before and after the insertion point, and taken to be the inferior headline
   7070 level of the two.  So if the previous visible heading is level 3 and the
   7071 next is level 4 (or vice versa), level 4 will be used for insertion.
   7072 This makes sure that the subtree remains an independent subtree and does
   7073 not swallow low level entries.
   7074 
   7075 You can also force a different level, either by using a numeric prefix
   7076 argument, or by inserting the heading marker by hand.  For example, if the
   7077 cursor is after \"*****\", then the tree will be shifted to level 5.
   7078 
   7079 If optional TREE is given, use this text instead of the kill ring.
   7080 
   7081 When FOR-YANK is set, this is called by `org-yank'.  In this case, do not
   7082 move back over whitespace before inserting, and move point to the end of
   7083 the inserted text when done.
   7084 
   7085 When REMOVE is non-nil, remove the subtree from the clipboard."
   7086   (interactive "P")
   7087   (setq tree (or tree (current-kill 0)))
   7088   (unless (org-kill-is-subtree-p tree)
   7089     (user-error
   7090      (substitute-command-keys
   7091       "The kill is not a (set of) tree(s).  Use `\\[yank]' to yank anyway")))
   7092   (org-with-limited-levels
   7093    (org-fold-core-ignore-fragility-checks
   7094      (let* ((visp (not (org-invisible-p)))
   7095 	    (txt tree)
   7096 	    (old-level (if (string-match org-outline-regexp-bol txt)
   7097 			   (- (match-end 0) (match-beginning 0) 1)
   7098 		         -1))
   7099 	    (force-level
   7100 	     (cond
   7101 	      (level (prefix-numeric-value level))
   7102 	      ;; When point is after the stars in an otherwise empty
   7103 	      ;; headline, use the number of stars as the forced level.
   7104 	      ((and (org-match-line "^\\*+[ \t]*$")
   7105 		    (not (eq ?* (char-after))))
   7106 	       (org-outline-level))
   7107 	      ((looking-at-p org-outline-regexp-bol) (org-outline-level))))
   7108 	    (previous-level
   7109 	     (save-excursion
   7110 	       (org-previous-visible-heading 1)
   7111 	       (if (org-at-heading-p) (org-outline-level) 1)))
   7112 	    (next-level
   7113 	     (save-excursion
   7114 	       (if (org-at-heading-p) (org-outline-level)
   7115 	         (org-next-visible-heading 1)
   7116 	         (if (org-at-heading-p) (org-outline-level) 1))))
   7117 	    (new-level (or force-level (max previous-level next-level)))
   7118 	    (shift (if (or (= old-level -1)
   7119 			   (= new-level -1)
   7120 			   (= old-level new-level))
   7121 		       0
   7122 		     (- new-level old-level)))
   7123 	    (delta (if (> shift 0) -1 1))
   7124 	    (func (if (> shift 0) #'org-demote #'org-promote))
   7125 	    (org-odd-levels-only nil)
   7126 	    beg end newend)
   7127        ;; Remove the forced level indicator.
   7128        (when (and force-level (not level))
   7129          (delete-region (line-beginning-position) (point)))
   7130        ;; Paste before the next visible heading or at end of buffer,
   7131        ;; unless point is at the beginning of a headline.
   7132        (unless (and (bolp) (org-at-heading-p))
   7133          (org-next-visible-heading 1)
   7134          (unless (bolp) (insert "\n")))
   7135        (setq beg (point))
   7136        ;; Avoid re-parsing cache elements when i.e. level 1 heading
   7137        ;; is inserted and then promoted.
   7138        (combine-change-calls beg beg
   7139          (when (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
   7140          (insert txt)
   7141          (unless (string-suffix-p "\n" txt) (insert "\n"))
   7142          (setq newend (point))
   7143          (org-reinstall-markers-in-region beg)
   7144          (setq end (point))
   7145          (goto-char beg)
   7146          (skip-chars-forward " \t\n\r")
   7147          (setq beg (point))
   7148          (when (and (org-invisible-p) visp)
   7149            (save-excursion (org-fold-heading nil)))
   7150          ;; Shift if necessary.
   7151          (unless (= shift 0)
   7152            (save-restriction
   7153 	     (narrow-to-region beg end)
   7154 	     (while (not (= shift 0))
   7155 	       (org-map-region func (point-min) (point-max))
   7156 	       (setq shift (+ delta shift)))
   7157 	     (goto-char (point-min))
   7158 	     (setq newend (point-max)))))
   7159        (when (or for-yank (called-interactively-p 'interactive))
   7160          (message "Clipboard pasted as level %d subtree" new-level))
   7161        (when (and (not for-yank) ; in this case, org-yank will decide about folding
   7162 		  (equal org-subtree-clip tree)
   7163 		  org-subtree-clip-folded)
   7164          ;; The tree was folded before it was killed/copied
   7165          (org-fold-subtree t))
   7166        (when for-yank (goto-char newend))
   7167        (when remove (pop kill-ring))))))
   7168 
   7169 (defun org-kill-is-subtree-p (&optional txt)
   7170   "Check if the current kill is an outline subtree, or a set of trees.
   7171 Returns nil if kill does not start with a headline, or if the first
   7172 headline level is not the largest headline level in the tree.
   7173 So this will actually accept several entries of equal levels as well,
   7174 which is OK for `org-paste-subtree'.
   7175 If optional TXT is given, check this string instead of the current kill."
   7176   (let* ((kill (or txt (ignore-errors (current-kill 0))))
   7177 	 (re (org-get-limited-outline-regexp))
   7178 	 (^re (concat "^" re))
   7179 	 (start-level (and kill
   7180 			   (string-match
   7181 			    (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
   7182 			    kill)
   7183 			   (- (match-end 2) (match-beginning 2) 1)))
   7184 	 (start (1+ (or (match-beginning 2) -1))))
   7185     (if (not start-level)
   7186 	(progn
   7187 	  nil)  ;; does not even start with a heading
   7188       (catch 'exit
   7189 	(while (setq start (string-match ^re kill (1+ start)))
   7190 	  (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
   7191 	    (throw 'exit nil)))
   7192 	t))))
   7193 
   7194 (defvar org-markers-to-move nil
   7195   "Markers that should be moved with a cut-and-paste operation.
   7196 Those markers are stored together with their positions relative to
   7197 the start of the region.")
   7198 
   7199 (defun org-save-markers-in-region (beg end)
   7200   "Check markers in region.
   7201 If these markers are between BEG and END, record their position relative
   7202 to BEG, so that after moving the block of text, we can put the markers back
   7203 into place.
   7204 This function gets called just before an entry or tree gets cut from the
   7205 buffer.  After re-insertion, `org-reinstall-markers-in-region' must be
   7206 called immediately, to move the markers with the entries."
   7207   (setq org-markers-to-move nil)
   7208   (when (featurep 'org-clock)
   7209     (org-clock-save-markers-for-cut-and-paste beg end))
   7210   (when (featurep 'org-agenda)
   7211     (org-agenda-save-markers-for-cut-and-paste beg end)))
   7212 
   7213 (defun org-check-and-save-marker (marker beg end)
   7214   "Check if MARKER is between BEG and END.
   7215 If yes, remember the marker and the distance to BEG."
   7216   (when (and (marker-buffer marker)
   7217 	     (or (equal (marker-buffer marker) (current-buffer))
   7218                  (equal (marker-buffer marker) (buffer-base-buffer (current-buffer))))
   7219 	     (>= marker beg) (< marker end))
   7220     (push (cons marker (- marker beg)) org-markers-to-move)))
   7221 
   7222 (defun org-reinstall-markers-in-region (beg)
   7223   "Move all remembered markers to their position relative to BEG."
   7224   (dolist (x org-markers-to-move)
   7225     (move-marker (car x) (+ beg (cdr x))))
   7226   (setq org-markers-to-move nil))
   7227 
   7228 (defun org-narrow-to-subtree (&optional element)
   7229   "Narrow buffer to the current subtree."
   7230   (interactive)
   7231   (if (org-element--cache-active-p)
   7232       (let* ((heading (org-element-lineage
   7233                        (or element (org-element-at-point))
   7234                        '(headline) t))
   7235              (end (org-element-property :end heading)))
   7236         (if (and heading end)
   7237             (narrow-to-region (org-element-property :begin heading)
   7238                               (if (= end (point-max))
   7239                                   end (1- end)))
   7240           (signal 'outline-before-first-heading nil)))
   7241     (save-excursion
   7242       (save-match-data
   7243         (org-with-limited-levels
   7244          (narrow-to-region
   7245 	  (progn (org-back-to-heading t) (point))
   7246 	  (progn (org-end-of-subtree t t)
   7247 	         (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
   7248 	         (point))))))))
   7249 
   7250 (defun org-toggle-narrow-to-subtree ()
   7251   "Narrow to the subtree at point or widen a narrowed buffer."
   7252   (interactive)
   7253   (if (buffer-narrowed-p)
   7254       (progn (widen) (message "Buffer widen"))
   7255     (org-narrow-to-subtree)
   7256     (message "Buffer narrowed to current subtree")))
   7257 
   7258 (defun org-narrow-to-block ()
   7259   "Narrow buffer to the current block."
   7260   (interactive)
   7261   (let* ((case-fold-search t)
   7262 	 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
   7263 					"^[ \t]*#\\+end_.*")))
   7264     (if blockp
   7265 	(narrow-to-region (car blockp) (cdr blockp))
   7266       (user-error "Not in a block"))))
   7267 
   7268 (defun org-clone-subtree-with-time-shift (n &optional shift)
   7269   "Clone the task (subtree) at point N times.
   7270 The clones will be inserted as siblings.
   7271 
   7272 In interactive use, the user will be prompted for the number of
   7273 clones to be produced.  If the entry has a timestamp, the user
   7274 will also be prompted for a time shift, which may be a repeater
   7275 as used in time stamps, for example `+3d'.  To disable this,
   7276 you can call the function with a universal prefix argument.
   7277 
   7278 When a valid repeater is given and the entry contains any time
   7279 stamps, the clones will become a sequence in time, with time
   7280 stamps in the subtree shifted for each clone produced.  If SHIFT
   7281 is nil or the empty string, time stamps will be left alone.  The
   7282 ID property of the original subtree is removed.
   7283 
   7284 In each clone, all the CLOCK entries will be removed.  This
   7285 prevents Org from considering that the clocked times overlap.
   7286 
   7287 If the original subtree did contain time stamps with a repeater,
   7288 the following will happen:
   7289 - the repeater will be removed in each clone
   7290 - an additional clone will be produced, with the current, unshifted
   7291   date(s) in the entry.
   7292 - the original entry will be placed *after* all the clones, with
   7293   repeater intact.
   7294 - the start days in the repeater in the original entry will be shifted
   7295   to past the last clone.
   7296 In this way you can spell out a number of instances of a repeating task,
   7297 and still retain the repeater to cover future instances of the task.
   7298 
   7299 As described above, N+1 clones are produced when the original
   7300 subtree has a repeater.  Setting N to 0, then, can be used to
   7301 remove the repeater from a subtree and create a shifted clone
   7302 with the original repeater."
   7303   (interactive "nNumber of clones to produce: ")
   7304   (unless (wholenump n) (user-error "Invalid number of replications %s" n))
   7305   (when (org-before-first-heading-p) (user-error "No subtree to clone"))
   7306   (let* ((beg (save-excursion (org-back-to-heading t) (point)))
   7307 	 (end-of-tree (save-excursion (org-end-of-subtree t t) (point)))
   7308 	 (shift
   7309 	  (or shift
   7310 	      (if (and (not (equal current-prefix-arg '(4)))
   7311 		       (save-excursion
   7312 			 (goto-char beg)
   7313 			 (re-search-forward org-ts-regexp-both end-of-tree t)))
   7314 		  (read-from-minibuffer
   7315 		   "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
   7316 		"")))			;No time shift
   7317 	 (doshift
   7318 	  (and (org-string-nw-p shift)
   7319 	       (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
   7320 				 shift)
   7321 		   (user-error "Invalid shift specification %s" shift)))))
   7322     (goto-char end-of-tree)
   7323     (unless (bolp) (insert "\n"))
   7324     (let* ((end (point))
   7325 	   (template (buffer-substring beg end))
   7326 	   (shift-n (and doshift (string-to-number (match-string 1 shift))))
   7327 	   (shift-what (pcase (and doshift (match-string 2 shift))
   7328 			 (`nil nil)
   7329 			 ("h" 'hour)
   7330 			 ("d" 'day)
   7331 			 ("w" (setq shift-n (* 7 shift-n)) 'day)
   7332 			 ("m" 'month)
   7333 			 ("y" 'year)
   7334 			 (_ (error "Unsupported time unit"))))
   7335 	   (nmin 1)
   7336 	   (nmax n)
   7337 	   (n-no-remove -1)
   7338 	   (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer)))
   7339 	   (idprop (org-entry-get beg "ID")))
   7340       (when (and doshift
   7341 		 (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>"
   7342 				 template))
   7343 	(delete-region beg end)
   7344 	(setq end beg)
   7345 	(setq nmin 0)
   7346 	(setq nmax (1+ nmax))
   7347 	(setq n-no-remove nmax))
   7348       (goto-char end)
   7349       (cl-loop for n from nmin to nmax do
   7350 	       (insert
   7351 		;; Prepare clone.
   7352 		(with-temp-buffer
   7353 		  (insert template)
   7354 		  (org-mode)
   7355 		  (goto-char (point-min))
   7356 		  (org-fold-show-subtree)
   7357 		  (and idprop (if org-clone-delete-id
   7358 				  (org-entry-delete nil "ID")
   7359 				(org-id-get-create t)))
   7360 		  (unless (= n 0)
   7361 		    (while (re-search-forward org-clock-line-re nil t)
   7362 		      (delete-region (line-beginning-position)
   7363 				     (line-beginning-position 2)))
   7364 		    (goto-char (point-min))
   7365 		    (while (re-search-forward org-drawer-regexp nil t)
   7366 		      (org-remove-empty-drawer-at (point))))
   7367 		  (goto-char (point-min))
   7368 		  (when doshift
   7369 		    (while (re-search-forward org-ts-regexp-both nil t)
   7370 		      (org-timestamp-change (* n shift-n) shift-what))
   7371 		    (unless (= n n-no-remove)
   7372 		      (goto-char (point-min))
   7373 		      (while (re-search-forward org-ts-regexp nil t)
   7374 			(save-excursion
   7375 			  (goto-char (match-beginning 0))
   7376 			  (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
   7377 			    (delete-region (match-beginning 1) (match-end 1)))))))
   7378 		  (buffer-string)))))
   7379     (goto-char beg)))
   7380 
   7381 ;;; Outline path
   7382 
   7383 (defvar org-outline-path-cache nil
   7384   "Alist between buffer positions and outline paths.
   7385 It value is an alist (POSITION . PATH) where POSITION is the
   7386 buffer position at the beginning of an entry and PATH is a list
   7387 of strings describing the outline path for that entry, in reverse
   7388 order.")
   7389 
   7390 (defun org--get-outline-path-1 (&optional use-cache)
   7391   "Return outline path to current headline.
   7392 
   7393 Outline path is a list of strings, in reverse order.  When
   7394 optional argument USE-CACHE is non-nil, make use of a cache.  See
   7395 `org-get-outline-path' for details.
   7396 
   7397 Assume buffer is widened and point is on a headline."
   7398   (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
   7399       (let ((p (point))
   7400 	    (heading (let ((case-fold-search nil))
   7401 		       (looking-at org-complex-heading-regexp)
   7402 		       (if (not (match-end 4)) ""
   7403 			 ;; Remove statistics cookies.
   7404 			 (org-trim
   7405 			  (org-link-display-format
   7406 			   (replace-regexp-in-string
   7407 			    "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
   7408 			    (match-string-no-properties 4))))))))
   7409 	(if (org-up-heading-safe)
   7410 	    (let ((path (cons heading (org--get-outline-path-1 use-cache))))
   7411 	      (when use-cache
   7412 		(push (cons p path) org-outline-path-cache))
   7413 	      path)
   7414 	  ;; This is a new root node.  Since we assume we are moving
   7415 	  ;; forward, we can drop previous cache so as to limit number
   7416 	  ;; of associations there.
   7417 	  (let ((path (list heading)))
   7418 	    (when use-cache (setq org-outline-path-cache (list (cons p path))))
   7419 	    path)))))
   7420 
   7421 (defun org-get-outline-path (&optional with-self use-cache)
   7422   "Return the outline path to the current entry.
   7423 
   7424 An outline path is a list of ancestors for current headline, as
   7425 a list of strings.  Statistics cookies are removed and links are
   7426 replaced with their description, if any, or their path otherwise.
   7427 
   7428 When optional argument WITH-SELF is non-nil, the path also
   7429 includes the current headline.
   7430 
   7431 When optional argument USE-CACHE is non-nil, cache outline paths
   7432 between calls to this function so as to avoid backtracking.  This
   7433 argument is useful when planning to find more than one outline
   7434 path in the same document.  In that case, there are two
   7435 conditions to satisfy:
   7436   - `org-outline-path-cache' is set to nil before starting the
   7437     process;
   7438   - outline paths are computed by increasing buffer positions."
   7439   (org-with-wide-buffer
   7440    (and (or (and with-self (org-back-to-heading t))
   7441 	    (org-up-heading-safe))
   7442 	(reverse (org--get-outline-path-1 use-cache)))))
   7443 
   7444 (defun org-format-outline-path (path &optional width prefix separator)
   7445   "Format the outline path PATH for display.
   7446 WIDTH is the maximum number of characters that is available.
   7447 PREFIX is a prefix to be included in the returned string,
   7448 such as the file name.
   7449 SEPARATOR is inserted between the different parts of the path,
   7450 the default is \"/\"."
   7451   (setq width (or width 79))
   7452   (setq path (delq nil path))
   7453   (unless (> width 0)
   7454     (user-error "Argument `width' must be positive"))
   7455   (setq separator (or separator "/"))
   7456   (let* ((org-odd-levels-only nil)
   7457 	 (fpath (concat
   7458 		 prefix (and prefix path separator)
   7459 		 (mapconcat
   7460 		  (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
   7461 		  (cl-loop for head in path
   7462 			   for n from 0
   7463 			   collect (org-add-props
   7464 				       head nil 'face
   7465 				       (nth (% n org-n-level-faces) org-level-faces)))
   7466 		  separator))))
   7467     (when (> (length fpath) width)
   7468       (if (< width 7)
   7469 	  ;; It's unlikely that `width' will be this small, but don't
   7470 	  ;; waste characters by adding ".." if it is.
   7471 	  (setq fpath (substring fpath 0 width))
   7472 	(setf (substring fpath (- width 2)) "..")))
   7473     fpath))
   7474 
   7475 (defun org-get-title (&optional buffer-or-file)
   7476   "Collect title from the provided `org-mode' BUFFER-OR-FILE.
   7477 
   7478 Returns nil if there are no #+TITLE property."
   7479   (let ((buffer (cond ((bufferp buffer-or-file) buffer-or-file)
   7480                       ((stringp buffer-or-file) (find-file-noselect
   7481                                                  buffer-or-file))
   7482                       (t (current-buffer)))))
   7483     (with-current-buffer buffer
   7484       (org-macro-initialize-templates)
   7485       (let ((title (assoc-default "title" org-macro-templates)))
   7486         (unless (string= "" title)
   7487           title)))))
   7488 
   7489 (defun org-display-outline-path (&optional file-or-title current separator just-return-string)
   7490   "Display the current outline path in the echo area.
   7491 
   7492 If FILE-OR-TITLE is `title', prepend outline with file title.  If
   7493 it is non-nil or title is not present in document, prepend
   7494 outline path with the file name.
   7495 If CURRENT is non-nil, append the current heading to the output.
   7496 SEPARATOR is passed through to `org-format-outline-path'.  It separates
   7497 the different parts of the path and defaults to \"/\".
   7498 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
   7499   (interactive "P")
   7500   (let* (case-fold-search
   7501 	 (bfn (buffer-file-name (buffer-base-buffer)))
   7502          (title-prop (when (eq file-or-title 'title) (org-get-title)))
   7503 	 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
   7504 	 res)
   7505     (when current (setq path (append path
   7506 				     (save-excursion
   7507 				       (org-back-to-heading t)
   7508 				       (when (looking-at org-complex-heading-regexp)
   7509 					 (list (match-string 4)))))))
   7510     (setq res
   7511 	  (org-format-outline-path
   7512 	   path
   7513 	   (1- (frame-width))
   7514 	   (and file-or-title bfn (concat (if (and (eq file-or-title 'title) title-prop)
   7515 					      title-prop
   7516 					    (file-name-nondirectory bfn))
   7517 				 separator))
   7518 	   separator))
   7519     (add-face-text-property 0 (length res)
   7520 			    `(:height ,(face-attribute 'default :height))
   7521 			    nil res)
   7522     (if just-return-string
   7523 	res
   7524       (org-unlogged-message "%s" res))))
   7525 
   7526 ;;; Outline Sorting
   7527 
   7528 (defun org-sort (&optional with-case)
   7529   "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
   7530 Optional argument WITH-CASE means sort case-sensitively."
   7531   (interactive "P")
   7532   (org-call-with-arg
   7533    (cond ((org-at-table-p) #'org-table-sort-lines)
   7534 	 ((org-at-item-p) #'org-sort-list)
   7535 	 (t #'org-sort-entries))
   7536    with-case))
   7537 
   7538 (defun org-sort-remove-invisible (s)
   7539   "Remove emphasis markers and any invisible property from string S.
   7540 Assume S may contain only objects."
   7541   ;; org-element-interpret-data clears any text property, including
   7542   ;; invisible part.
   7543   (org-element-interpret-data
   7544    (let ((tree (org-element-parse-secondary-string
   7545                 s (org-element-restriction 'paragraph))))
   7546      (org-element-map tree '(bold code italic link strike-through underline verbatim)
   7547        (lambda (o)
   7548          (pcase (org-element-type o)
   7549            ;; Terminal object.  Replace it with its value.
   7550            ((or `code `verbatim)
   7551             (let ((new (org-element-property :value o)))
   7552               (org-element-insert-before new o)
   7553               (org-element-put-property
   7554                new :post-blank (org-element-property :post-blank o))))
   7555            ;; Non-terminal objects.  Splice contents.
   7556            (type
   7557             (let ((contents
   7558                    (or (org-element-contents o)
   7559                        (and (eq type 'link)
   7560                             (list (org-element-property :raw-link o)))))
   7561                   (c nil))
   7562               (while contents
   7563                 (setq c (pop contents))
   7564                 (org-element-insert-before c o))
   7565               (org-element-put-property
   7566                c :post-blank (org-element-property :post-blank o)))))
   7567          (org-element-extract-element o)))
   7568      ;; Return modified tree.
   7569      tree)))
   7570 
   7571 (defvar org-after-sorting-entries-or-items-hook nil
   7572   "Hook that is run after a bunch of entries or items have been sorted.
   7573 When children are sorted, the cursor is in the parent line when this
   7574 hook gets called.  When a region or a plain list is sorted, the cursor
   7575 will be in the first entry of the sorted region/list.")
   7576 
   7577 (defun org-sort-entries
   7578     (&optional with-case sorting-type getkey-func compare-func property
   7579 	       interactive?)
   7580   "Sort entries on a certain level of an outline tree.
   7581 If there is an active region, the entries in the region are sorted.
   7582 Else, if the cursor is before the first entry, sort the top-level items.
   7583 Else, the children of the entry at point are sorted.
   7584 
   7585 Sorting can be alphabetically, numerically, by date/time as given by
   7586 a time stamp, by a property, by priority order, or by a custom function.
   7587 
   7588 The command prompts for the sorting type unless it has been given to the
   7589 function through the SORTING-TYPE argument, which needs to be a character,
   7590 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K).  Here is
   7591 the precise meaning of each character:
   7592 
   7593 a   Alphabetically, ignoring the TODO keyword and the priority, if any.
   7594 c   By creation time, which is assumed to be the first inactive time stamp
   7595     at the beginning of a line.
   7596 d   By deadline date/time.
   7597 k   By clocking time.
   7598 n   Numerically, by converting the beginning of the entry/item to a number.
   7599 o   By order of TODO keywords.
   7600 p   By priority according to the cookie.
   7601 r   By the value of a property.
   7602 s   By scheduled date/time.
   7603 t   By date/time, either the first active time stamp in the entry, or, if
   7604     none exist, by the first inactive one.
   7605 
   7606 Capital letters will reverse the sort order.
   7607 
   7608 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
   7609 called with point at the beginning of the record.  It must return a
   7610 value that is compatible with COMPARE-FUNC, the function used to
   7611 compare entries.
   7612 
   7613 Comparing entries ignores case by default.  However, with an optional argument
   7614 WITH-CASE, the sorting considers case as well.
   7615 
   7616 Sorting is done against the visible part of the headlines, it ignores hidden
   7617 links.
   7618 
   7619 When sorting is done, call `org-after-sorting-entries-or-items-hook'.
   7620 
   7621 A non-nil value for INTERACTIVE? is used to signal that this
   7622 function is being called interactively."
   7623   (interactive (list current-prefix-arg nil nil nil nil t))
   7624   (let ((case-func (if with-case 'identity 'downcase))
   7625         start beg end stars re re2
   7626         txt what tmp)
   7627     ;; Find beginning and end of region to sort
   7628     (cond
   7629      ((org-region-active-p)
   7630       ;; we will sort the region
   7631       (setq end (region-end)
   7632             what "region")
   7633       (goto-char (region-beginning))
   7634       (unless (org-at-heading-p) (outline-next-heading))
   7635       (setq start (point)))
   7636      ((or (org-at-heading-p)
   7637           (ignore-errors (progn (org-back-to-heading) t)))
   7638       ;; we will sort the children of the current headline
   7639       (org-back-to-heading)
   7640       (setq start (point)
   7641 	    end (progn (org-end-of-subtree t t)
   7642 		       (or (bolp) (insert "\n"))
   7643 		       (when (>= (org-back-over-empty-lines) 1)
   7644 			 (forward-line 1))
   7645 		       (point))
   7646 	    what "children")
   7647       (goto-char start)
   7648       (org-fold-show-subtree)
   7649       (outline-next-heading))
   7650      (t
   7651       ;; we will sort the top-level entries in this file
   7652       (goto-char (point-min))
   7653       (or (org-at-heading-p) (outline-next-heading))
   7654       (setq start (point))
   7655       (goto-char (point-max))
   7656       (beginning-of-line 1)
   7657       (when (looking-at ".*?\\S-")
   7658 	;; File ends in a non-white line
   7659 	(end-of-line 1)
   7660 	(insert "\n"))
   7661       (setq end (point-max))
   7662       (setq what "top-level")
   7663       (goto-char start)
   7664       (org-fold-show-all '(headings drawers blocks))))
   7665 
   7666     (setq beg (point))
   7667     (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
   7668 
   7669     (looking-at "\\(\\*+\\)")
   7670     (setq stars (match-string 1)
   7671 	  re (concat "^" (regexp-quote stars) " +")
   7672 	  re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
   7673 	  txt (buffer-substring beg end))
   7674     (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
   7675     (when (and (not (equal stars "*")) (string-match re2 txt))
   7676       (user-error "Region to sort contains a level above the first entry"))
   7677 
   7678     (unless sorting-type
   7679       (message
   7680        "Sort %s: [a]lpha  [n]umeric  [p]riority  p[r]operty  todo[o]rder  [f]unc
   7681                [t]ime [s]cheduled  [d]eadline  [c]reated  cloc[k]ing
   7682                A/N/P/R/O/F/T/S/D/C/K means reversed:"
   7683        what)
   7684       (setq sorting-type (read-char-exclusive)))
   7685 
   7686     (unless getkey-func
   7687       (and (= (downcase sorting-type) ?f)
   7688 	   (setq getkey-func
   7689 		 (or (and interactive?
   7690 			  (org-read-function
   7691 			   "Function for extracting keys: "))
   7692 		     (error "Missing key extractor")))))
   7693 
   7694     (and (= (downcase sorting-type) ?r)
   7695 	 (not property)
   7696 	 (setq property
   7697 	       (completing-read "Property: "
   7698 				(mapcar #'list (org-buffer-property-keys t))
   7699 				nil t)))
   7700 
   7701     (when (member sorting-type '(?k ?K)) (org-clock-sum))
   7702     (message "Sorting entries...")
   7703 
   7704     (save-restriction
   7705       (narrow-to-region start end)
   7706       (let ((restore-clock?
   7707 	     ;; The clock marker is lost when using `sort-subr'; mark
   7708 	     ;; the clock with temporary `:org-clock-marker-backup'
   7709 	     ;; text property.
   7710 	     (when (and (eq (org-clocking-buffer) (current-buffer))
   7711 			(<= start (marker-position org-clock-marker))
   7712 			(>= end (marker-position org-clock-marker)))
   7713 	       (with-silent-modifications
   7714 		 (put-text-property (1- org-clock-marker) org-clock-marker
   7715 				    :org-clock-marker-backup t))
   7716 	       t))
   7717 	    (dcst (downcase sorting-type))
   7718 	    (case-fold-search nil)
   7719 	    (now (current-time)))
   7720         (org-preserve-local-variables
   7721 	 (sort-subr
   7722 	  (/= dcst sorting-type)
   7723 	  ;; This function moves to the beginning character of the
   7724 	  ;; "record" to be sorted.
   7725 	  (lambda nil
   7726 	    (if (re-search-forward re nil t)
   7727 		(goto-char (match-beginning 0))
   7728 	      (goto-char (point-max))))
   7729 	  ;; This function moves to the last character of the "record" being
   7730 	  ;; sorted.
   7731 	  (lambda nil
   7732 	    (save-match-data
   7733 	      (condition-case nil
   7734 		  (outline-forward-same-level 1)
   7735 		(error
   7736 		 (goto-char (point-max))))))
   7737 	  ;; This function returns the value that gets sorted against.
   7738 	  (lambda ()
   7739 	    (cond
   7740 	     ((= dcst ?n)
   7741 	      (string-to-number
   7742 	       (org-sort-remove-invisible (org-get-heading t t t t))))
   7743 	     ((= dcst ?a)
   7744 	      (funcall case-func
   7745 		       (org-sort-remove-invisible (org-get-heading t t t t))))
   7746 	     ((= dcst ?k)
   7747 	      (or (get-text-property (point) :org-clock-minutes) 0))
   7748 	     ((= dcst ?t)
   7749 	      (let ((end (save-excursion (outline-next-heading) (point))))
   7750 		(if (or (re-search-forward org-ts-regexp end t)
   7751 			(re-search-forward org-ts-regexp-both end t))
   7752 		    (org-time-string-to-seconds (match-string 0))
   7753 		  (float-time now))))
   7754 	     ((= dcst ?c)
   7755 	      (let ((end (save-excursion (outline-next-heading) (point))))
   7756 		(if (re-search-forward
   7757 		     (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
   7758 		     end t)
   7759 		    (org-time-string-to-seconds (match-string 0))
   7760 		  (float-time now))))
   7761 	     ((= dcst ?s)
   7762 	      (let ((end (save-excursion (outline-next-heading) (point))))
   7763 		(if (re-search-forward org-scheduled-time-regexp end t)
   7764 		    (org-time-string-to-seconds (match-string 1))
   7765 		  (float-time now))))
   7766 	     ((= dcst ?d)
   7767 	      (let ((end (save-excursion (outline-next-heading) (point))))
   7768 		(if (re-search-forward org-deadline-time-regexp end t)
   7769 		    (org-time-string-to-seconds (match-string 1))
   7770 		  (float-time now))))
   7771 	     ((= dcst ?p)
   7772               (if (re-search-forward org-priority-regexp (line-end-position) t)
   7773 		  (string-to-char (match-string 2))
   7774 		org-priority-default))
   7775 	     ((= dcst ?r)
   7776 	      (or (org-entry-get nil property) ""))
   7777 	     ((= dcst ?o)
   7778 	      (when (looking-at org-complex-heading-regexp)
   7779 		(let* ((m (match-string 2))
   7780 		       (s (if (member m org-done-keywords) '- '+)))
   7781 		  (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
   7782 	     ((= dcst ?f)
   7783 	      (if getkey-func
   7784 		  (progn
   7785 		    (setq tmp (funcall getkey-func))
   7786 		    (when (stringp tmp) (setq tmp (funcall case-func tmp)))
   7787 		    tmp)
   7788 		(error "Invalid key function `%s'" getkey-func)))
   7789 	     (t (error "Invalid sorting type `%c'" sorting-type))))
   7790 	  nil
   7791 	  (cond
   7792 	   ((= dcst ?a) 'string-collate-lessp)
   7793 	   ((= dcst ?f)
   7794 	    (or compare-func
   7795 		(and interactive?
   7796 		     (org-read-function
   7797 		      (concat "Function for comparing keys "
   7798 			      "(empty for default `sort-subr' predicate): ")
   7799 		      'allow-empty))))
   7800 	   ((member dcst '(?p ?t ?s ?d ?c ?k)) '<))))
   7801 	(org-cycle-hide-drawers 'all)
   7802 	(when restore-clock?
   7803 	  (move-marker org-clock-marker
   7804 		       (1+ (next-single-property-change
   7805 			    start :org-clock-marker-backup)))
   7806 	  (remove-text-properties (1- org-clock-marker) org-clock-marker
   7807 				  '(:org-clock-marker-backup t)))))
   7808     (run-hooks 'org-after-sorting-entries-or-items-hook)
   7809     (message "Sorting entries...done")))
   7810 
   7811 (defun org-contextualize-keys (alist contexts)
   7812   "Return valid elements in ALIST depending on CONTEXTS.
   7813 
   7814 `org-agenda-custom-commands' or `org-capture-templates' are the
   7815 values used for ALIST, and `org-agenda-custom-commands-contexts'
   7816 or `org-capture-templates-contexts' are the associated contexts
   7817 definitions."
   7818   (let ((contexts
   7819 	 ;; normalize contexts
   7820 	 (mapcar
   7821 	  (lambda(c) (cond ((listp (cadr c))
   7822 			    (list (car c) (car c) (nth 1 c)))
   7823 			   ((string= "" (cadr c))
   7824 			    (list (car c) (car c) (nth 2 c)))
   7825 			   (t c)))
   7826           contexts))
   7827 	(a alist) r s)
   7828     ;; loop over all commands or templates
   7829     (dolist (c a)
   7830       (let (vrules repl)
   7831 	(cond
   7832 	 ((not (assoc (car c) contexts))
   7833 	  (push c r))
   7834 	 ((and (assoc (car c) contexts)
   7835 	       (setq vrules (org-contextualize-validate-key
   7836 			     (car c) contexts)))
   7837 	  (mapc (lambda (vr)
   7838 		  (unless (equal (car vr) (cadr vr))
   7839 		    (setq repl vr)))
   7840                 vrules)
   7841 	  (if (not repl) (push c r)
   7842 	    (push (cadr repl) s)
   7843 	    (push
   7844 	     (cons (car c)
   7845 		   (cdr (or (assoc (cadr repl) alist)
   7846 			    (error "Undefined key `%s' as contextual replacement for `%s'"
   7847 				   (cadr repl) (car c)))))
   7848 	     r))))))
   7849     ;; Return limited ALIST, possibly with keys modified, and deduplicated
   7850     (delq
   7851      nil
   7852      (delete-dups
   7853       (mapcar (lambda (x)
   7854 		(let ((tpl (car x)))
   7855 		  (unless (delq
   7856 			   nil
   7857 			   (mapcar (lambda (y)
   7858 				     (equal y tpl))
   7859 				   s))
   7860                     x)))
   7861 	      (reverse r))))))
   7862 
   7863 (defun org-contextualize-validate-key (key contexts)
   7864   "Check CONTEXTS for agenda or capture KEY."
   7865   (let (res)
   7866     (dolist (r contexts)
   7867       (dolist (rr (car (last r)))
   7868 	(when
   7869 	    (and (equal key (car r))
   7870 		 (if (functionp rr) (funcall rr)
   7871 		   (or (and (eq (car rr) 'in-file)
   7872 			    (buffer-file-name)
   7873 			    (string-match (cdr rr) (buffer-file-name)))
   7874 		       (and (eq (car rr) 'in-mode)
   7875 			    (string-match (cdr rr) (symbol-name major-mode)))
   7876 		       (and (eq (car rr) 'in-buffer)
   7877 			    (string-match (cdr rr) (buffer-name)))
   7878 		       (when (and (eq (car rr) 'not-in-file)
   7879 				  (buffer-file-name))
   7880 			 (not (string-match (cdr rr) (buffer-file-name))))
   7881 		       (when (eq (car rr) 'not-in-mode)
   7882 			 (not (string-match (cdr rr) (symbol-name major-mode))))
   7883 		       (when (eq (car rr) 'not-in-buffer)
   7884 			 (not (string-match (cdr rr) (buffer-name)))))))
   7885 	  (push r res))))
   7886     (delete-dups (delq nil res))))
   7887 
   7888 ;; Defined to provide a value for defcustom, since there is no
   7889 ;; string-collate-greaterp in Emacs.
   7890 (defun org-string-collate-greaterp (s1 s2)
   7891   "Return non-nil if S1 is greater than S2 in collation order."
   7892   (not (string-collate-lessp s1 s2)))
   7893 
   7894 ;;;###autoload
   7895 (defun org-run-like-in-org-mode (cmd)
   7896   "Run a command, pretending that the current buffer is in Org mode.
   7897 This will temporarily bind local variables that are typically bound in
   7898 Org mode to the values they have in Org mode, and then interactively
   7899 call CMD."
   7900   (org-load-modules-maybe)
   7901   (let (vars vals)
   7902     (dolist (var (org-get-local-variables))
   7903       (when (or (not (boundp (car var)))
   7904 		(eq (symbol-value (car var))
   7905 		    (default-value (car var))))
   7906 	(push (car var) vars)
   7907 	(push (cadr var) vals)))
   7908     (cl-progv vars vals
   7909       (call-interactively cmd))))
   7910 
   7911 (defun org-get-category (&optional pos force-refresh)
   7912   "Get the category applying to position POS."
   7913   (save-match-data
   7914     (when force-refresh (org-refresh-category-properties))
   7915     (let ((pos (or pos (point))))
   7916       (if (org-element--cache-active-p)
   7917           ;; Sync cache.
   7918           (org-with-point-at (org-element-property :begin (org-element-at-point pos))
   7919             (or (org-entry-get-with-inheritance "CATEGORY")
   7920                 "???"))
   7921         (or (get-text-property pos 'org-category)
   7922             (progn
   7923               (org-refresh-category-properties)
   7924               (get-text-property pos 'org-category)))))))
   7925 
   7926 ;;; Refresh properties
   7927 
   7928 (defun org-refresh-properties (dprop tprop)
   7929   "Refresh buffer text properties.
   7930 DPROP is the drawer property and TPROP is either the
   7931 corresponding text property to set, or an alist with each element
   7932 being a text property (as a symbol) and a function to apply to
   7933 the value of the drawer property."
   7934   (let* ((case-fold-search t)
   7935 	 (inhibit-read-only t)
   7936 	 (inherit? (org-property-inherit-p dprop))
   7937 	 (property-re (org-re-property (concat (regexp-quote dprop) "\\+?") t))
   7938 	 (global-or-keyword (and inherit?
   7939 				 (org--property-global-or-keyword-value dprop nil))))
   7940     (with-silent-modifications
   7941       (org-with-point-at 1
   7942 	;; Set global and keyword based values to the whole buffer.
   7943 	(when global-or-keyword
   7944 	  (put-text-property (point-min) (point-max) tprop global-or-keyword))
   7945 	;; Set values based on property-drawers throughout the document.
   7946 	(while (re-search-forward property-re nil t)
   7947 	  (when (org-at-property-p)
   7948 	    (org-refresh-property tprop (org-entry-get (point) dprop) inherit?))
   7949 	  (outline-next-heading))))))
   7950 
   7951 (defun org-refresh-property (tprop p &optional inherit)
   7952   "Refresh the buffer text property TPROP from the drawer property P.
   7953 
   7954 The refresh happens only for the current entry, or the whole
   7955 sub-tree if optional argument INHERIT is non-nil.
   7956 
   7957 If point is before first headline, the function applies to the
   7958 part before the first headline.  In that particular case, when
   7959 optional argument INHERIT is non-nil, it refreshes properties for
   7960 the whole buffer."
   7961   (save-excursion
   7962     (org-back-to-heading-or-point-min t)
   7963     (let ((start (point))
   7964 	  (end (save-excursion
   7965 		 (cond ((and inherit (org-before-first-heading-p))
   7966 			(point-max))
   7967 		       (inherit
   7968 			(org-end-of-subtree t t))
   7969 		       ((outline-next-heading))
   7970 		       ((point-max))))))
   7971       (with-silent-modifications
   7972 	(if (symbolp tprop)
   7973 	    ;; TPROP is a text property symbol.
   7974 	    (put-text-property start end tprop p)
   7975 	  ;; TPROP is an alist with (property . function) elements.
   7976 	  (pcase-dolist (`(,prop . ,f) tprop)
   7977 	    (put-text-property start end prop (funcall f p))))))))
   7978 
   7979 (defun org-refresh-category-properties ()
   7980   "Refresh category text properties in the buffer."
   7981   (unless (org-element--cache-active-p)
   7982     (let ((case-fold-search t)
   7983 	  (inhibit-read-only t)
   7984 	  (default-category
   7985 	    (cond ((null org-category)
   7986 		   (if buffer-file-name
   7987 		       (file-name-sans-extension
   7988 		        (file-name-nondirectory buffer-file-name))
   7989 		     "???"))
   7990 		  ((symbolp org-category) (symbol-name org-category))
   7991 		  (t org-category))))
   7992       (let ((category (catch 'buffer-category
   7993                         (org-with-wide-buffer
   7994 	                 (goto-char (point-max))
   7995 	                 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
   7996 	                   (let ((element (org-element-at-point-no-context)))
   7997 	                     (when (eq (org-element-type element) 'keyword)
   7998 		               (throw 'buffer-category
   7999 		                      (org-element-property :value element))))))
   8000 	                default-category)))
   8001         (with-silent-modifications
   8002           (org-with-wide-buffer
   8003            ;; Set buffer-wide property from keyword.  Search last #+CATEGORY
   8004            ;; keyword.  If none is found, fall-back to `org-category' or
   8005            ;; buffer file name, or set it by the document property drawer.
   8006            (put-text-property (point-min) (point-max)
   8007                               'org-category category)
   8008            ;; Set categories from the document property drawer or
   8009            ;; property drawers in the outline.  If category is found in
   8010            ;; the property drawer for the whole buffer that value
   8011            ;; overrides the keyword-based value set above.
   8012            (goto-char (point-min))
   8013            (let ((regexp (org-re-property "CATEGORY")))
   8014              (while (re-search-forward regexp nil t)
   8015                (let ((value (match-string-no-properties 3)))
   8016                  (when (org-at-property-p)
   8017                    (put-text-property
   8018                     (save-excursion (org-back-to-heading-or-point-min t))
   8019                     (save-excursion (if (org-before-first-heading-p)
   8020                                         (point-max)
   8021                                       (org-end-of-subtree t t)))
   8022                     'org-category
   8023                     value)))))))))))
   8024 
   8025 (defun org-refresh-stats-properties ()
   8026   "Refresh stats text properties in the buffer."
   8027   (with-silent-modifications
   8028     (org-with-point-at 1
   8029       (let ((regexp (concat org-outline-regexp-bol
   8030 			    ".*\\[\\([0-9]*\\)\\(?:%\\|/\\([0-9]*\\)\\)\\]")))
   8031 	(while (re-search-forward regexp nil t)
   8032 	  (let* ((numerator (string-to-number (match-string 1)))
   8033 		 (denominator (and (match-end 2)
   8034 				   (string-to-number (match-string 2))))
   8035 		 (stats (cond ((not denominator) numerator) ;percent
   8036 			      ((= denominator 0) 0)
   8037 			      (t (/ (* numerator 100) denominator)))))
   8038 	    (put-text-property (point) (progn (org-end-of-subtree t t) (point))
   8039 			       'org-stats stats)))))))
   8040 
   8041 (defun org-refresh-effort-properties ()
   8042   "Refresh effort properties."
   8043   (org-refresh-properties
   8044    org-effort-property
   8045    '((effort . identity)
   8046      (effort-minutes . org-duration-to-minutes))))
   8047 
   8048 (defun org-find-file-at-mouse (ev)
   8049   "Open file link or URL at mouse."
   8050   (interactive "e")
   8051   (mouse-set-point ev)
   8052   (org-open-at-point 'in-emacs))
   8053 
   8054 (defun org-open-at-mouse (ev)
   8055   "Open file link or URL at mouse.
   8056 See the docstring of `org-open-file' for details."
   8057   (interactive "e")
   8058   (mouse-set-point ev)
   8059   (when (eq major-mode 'org-agenda-mode)
   8060     (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
   8061   (org-open-at-point))
   8062 
   8063 (defvar org-window-config-before-follow-link nil
   8064   "The window configuration before following a link.
   8065 This is saved in case the need arises to restore it.")
   8066 
   8067 (defun org--file-default-apps ()
   8068   "Return the default applications for this operating system."
   8069   (pcase system-type
   8070     (`darwin org-file-apps-macos)
   8071     (`windows-nt org-file-apps-windowsnt)
   8072     (_ org-file-apps-gnu)))
   8073 
   8074 (defun org--file-apps-entry-locator-p (entry)
   8075   "Non-nil if ENTRY should be matched against the link by `org-open-file'.
   8076 
   8077 It assumes that is the case when the entry uses a regular
   8078 expression which has at least one grouping construct and the
   8079 action is either a Lisp form or a command string containing
   8080 \"%1\", i.e., using at least one subexpression match as
   8081 a parameter."
   8082   (pcase entry
   8083     (`(,selector . ,action)
   8084      (and (stringp selector)
   8085 	  (> (regexp-opt-depth selector) 0)
   8086 	  (or (and (stringp action)
   8087 		   (string-match "%[0-9]" action))
   8088 	      (functionp action))))
   8089     (_ nil)))
   8090 
   8091 (defun org--file-apps-regexp-alist (list &optional add-auto-mode)
   8092   "Convert extensions to regular expressions in the cars of LIST.
   8093 
   8094 Also, weed out any non-string entries, because the return value
   8095 is used only for regexp matching.
   8096 
   8097 When ADD-AUTO-MODE is non-nil, make all matches in `auto-mode-alist'
   8098 point to the symbol `emacs', indicating that the file should be
   8099 opened in Emacs."
   8100   (append
   8101    (delq nil
   8102 	 (mapcar (lambda (x)
   8103 		   (unless (not (stringp (car x)))
   8104 		     (if (string-match "\\W" (car x))
   8105 			 x
   8106 		       (cons (concat "\\." (car x) "\\'") (cdr x)))))
   8107 		 list))
   8108    (when add-auto-mode
   8109      (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
   8110 
   8111 (defun org--open-file-format-command
   8112     (mailcap-command file link match-data)
   8113   "Format MAILCAP-COMMAND to launch viewer for the FILE.
   8114 
   8115 MAILCAP-COMMAND may be an entry from the `org-file-apps' list or viewer
   8116 field from mailcap file loaded to `mailcap-mime-data'.  See \"RFC
   8117 1524.  A User Agent Configuration Mechanism For Multimedia Mail Format
   8118 Information\" (URL `https://www.rfc-editor.org/rfc/rfc1524.html') for
   8119 details, man page `mailcap(5)' for brief summary, and Info node
   8120 `(emacs-mime) mailcap' for specific related to Emacs.  Only a part of
   8121 mailcap specification is supported.
   8122 
   8123 The following substitutions are interpolated in the MAILCAP-COMMAND
   8124 string:
   8125 
   8126 - \"%s\" to FILE name passed through
   8127   `convert-standard-filename', so it must be absolute path.
   8128 
   8129 - \"%1\" to \"%9\" groups from MATCH-DATA found in the LINK string by
   8130   the regular expression in the key part of the `org-file-apps' entry.
   8131   (performed by caller).  Not recommended, consider a lisp function
   8132   instead of a shell command.  For example, the following link in an
   8133   Org file
   8134 
   8135        <file:///usr/share/doc/bash/bashref.pdf::#Redirections::allocate a file>
   8136 
   8137    may be handled by an `org-file-apps' entry like
   8138 
   8139        (\"\\\\.pdf\\\\(?:\\\\.[gx]z\\\\|\\\\.bz2\\\\)?::\\\\(#[^:]+\\\\)::\\\\(.+\\\\)\\\\\\='\"
   8140         . \"okular --find %2 %s%1\")
   8141 
   8142 Use backslash \"\\\" to quote percent \"%\" or any other character
   8143 including backslash itself.
   8144 
   8145 In addition, each argument is passed through `shell-quote-argument',
   8146 so quotes around substitutions should not be used.  For compliance
   8147 with mailcap files shipped e.g. in Debian GNU/Linux, single or double
   8148 quotes around substitutions are stripped.  It deviates from mailcap
   8149 specification that requires file name to be safe for shell and for the
   8150 application."
   8151   (let ((spec (list (cons ?s  (convert-standard-filename file))))
   8152         (ngroups (min 9 (- (/ (length match-data) 2) 1))))
   8153     (when (> ngroups 0)
   8154       (set-match-data match-data)
   8155       (dolist (i (number-sequence 1 ngroups))
   8156         (push (cons (+ ?0 i) (match-string-no-properties i link)) spec)))
   8157     (replace-regexp-in-string
   8158      (rx (or (and "\\" (or (group anything) string-end))
   8159              (and (optional (group (any "'\"")))
   8160                   "%"
   8161                   (or (group anything) string-end)
   8162                   (optional (group (backref 2))))))
   8163      (lambda (fmt)
   8164        (let* ((backslash (match-string-no-properties 1 fmt))
   8165               (key (match-string 3 fmt))
   8166               (value (and key (alist-get (string-to-char key) spec))))
   8167          (cond
   8168           (backslash)
   8169           (value (let ((quot (match-string 2 fmt))
   8170                        (subst (shell-quote-argument value)))
   8171                    ;; Remove quotes around the file name - we use
   8172                    ;; `shell-quote-argument'.
   8173                    (if (match-string 4 fmt)
   8174                        subst
   8175                      (concat quot subst))))
   8176           (t (error "Invalid format `%s'" fmt)))))
   8177      mailcap-command nil 'literal)))
   8178 
   8179 ;;;###autoload
   8180 (defun org-open-file (path &optional in-emacs line search)
   8181   "Open the file at PATH.
   8182 First, this expands any special file name abbreviations.  Then the
   8183 configuration variable `org-file-apps' is checked if it contains an
   8184 entry for this file type, and if yes, the corresponding command is launched.
   8185 
   8186 If no application is found, Emacs simply visits the file.
   8187 
   8188 With optional prefix argument IN-EMACS, Emacs will visit the file.
   8189 With a double \\[universal-argument] \\[universal-argument] \
   8190 prefix arg, Org tries to avoid opening in Emacs
   8191 and to use an external application to visit the file.
   8192 
   8193 Optional LINE specifies a line to go to, optional SEARCH a string
   8194 to search for.  If LINE or SEARCH is given, the file will be
   8195 opened in Emacs, unless an entry from `org-file-apps' that makes
   8196 use of groups in a regexp matches.
   8197 
   8198 If you want to change the way frames are used when following a
   8199 link, please customize `org-link-frame-setup'.
   8200 
   8201 If the file does not exist, throw an error."
   8202   (let* ((file (if (equal path "") buffer-file-name
   8203 		 (substitute-in-file-name (expand-file-name path))))
   8204 	 (file-apps (append org-file-apps (org--file-default-apps)))
   8205 	 (apps (cl-remove-if #'org--file-apps-entry-locator-p file-apps))
   8206 	 (apps-locator (cl-remove-if-not #'org--file-apps-entry-locator-p
   8207                                          file-apps))
   8208 	 (remp (and (assq 'remote apps) (file-remote-p file)))
   8209 	 (dirp (unless remp (file-directory-p file)))
   8210 	 (file (if (and dirp org-open-directory-means-index-dot-org)
   8211 		   (concat (file-name-as-directory file) "index.org")
   8212 		 file))
   8213 	 (a-m-a-p (assq 'auto-mode apps))
   8214 	 (dfile (downcase file))
   8215 	 ;; Reconstruct the original link from the PATH, LINE and
   8216 	 ;; SEARCH args.
   8217 	 (link (cond (line (concat file "::" (number-to-string line)))
   8218 		     (search (concat file "::" search))
   8219 		     (t file)))
   8220 	 (ext
   8221 	  (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
   8222 	       (match-string 1 dfile)))
   8223 	 (save-position-maybe
   8224 	  (let ((old-buffer (current-buffer))
   8225 		(old-pos (point))
   8226 		(old-mode major-mode))
   8227 	    (lambda ()
   8228 	      (and (derived-mode-p 'org-mode)
   8229 		   (eq old-mode 'org-mode)
   8230 		   (or (not (eq old-buffer (current-buffer)))
   8231 		       (not (eq old-pos (point))))
   8232 		   (org-mark-ring-push old-pos old-buffer)))))
   8233 	 cmd link-match-data)
   8234     (cond
   8235      ((member in-emacs '((16) system))
   8236       (setq cmd (cdr (assq 'system apps))))
   8237      (in-emacs (setq cmd 'emacs))
   8238      (t
   8239       (setq cmd (or (and remp (cdr (assq 'remote apps)))
   8240 		    (and dirp (cdr (assq 'directory apps)))
   8241 		    ;; First, try matching against apps-locator if we
   8242 		    ;; get a match here, store the match data for
   8243 		    ;; later.
   8244 		    (let* ((case-fold-search t)
   8245                            (match (assoc-default link apps-locator
   8246                                                  'string-match)))
   8247 		      (if match
   8248 			  (progn (setq link-match-data (match-data))
   8249 				 match)
   8250 			(progn (setq in-emacs (or in-emacs line search))
   8251 			       nil))) ; if we have no match in apps-locator,
   8252 					; always open the file in emacs if line or search
   8253 					; is given (for backwards compatibility)
   8254 		    (assoc-default dfile
   8255 				   (org--file-apps-regexp-alist apps a-m-a-p)
   8256 				   'string-match)
   8257 		    (cdr (assoc ext apps))
   8258 		    (cdr (assq t apps))))))
   8259     (when (eq cmd 'system)
   8260       (setq cmd (cdr (assq 'system apps))))
   8261     (when (eq cmd 'default)
   8262       (setq cmd (cdr (assoc t apps))))
   8263     (when (eq cmd 'mailcap)
   8264       (require 'mailcap)
   8265       (mailcap-parse-mailcaps)
   8266       (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
   8267 	     (command (mailcap-mime-info mime-type)))
   8268 	(if (stringp command)
   8269 	    (setq cmd command)
   8270 	  (setq cmd 'emacs))))
   8271     (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
   8272 	       (not (file-exists-p file))
   8273 	       (not org-open-non-existing-files))
   8274       (user-error "No such file: %s" file))
   8275     (cond
   8276      ((org-string-nw-p cmd)
   8277       (setq cmd (org--open-file-format-command cmd file link link-match-data))
   8278 
   8279       (save-window-excursion
   8280 	(message "Running %s...done" cmd)
   8281         ;; Handlers such as "gio open" and kde-open5 start viewer in background
   8282         ;; and exit immediately.  Use pipe connection type instead of pty to
   8283         ;; avoid killing children processes with SIGHUP when temporary terminal
   8284         ;; session is finished.
   8285         ;;
   8286         ;; TODO: Once minimum Emacs version is 25.1 or above, consider using
   8287         ;; the `make-process' invocation from 5db61eb0f929 to get more helpful
   8288         ;; error messages.
   8289         (let ((process-connection-type nil))
   8290 	  (start-process-shell-command cmd nil cmd))
   8291 	(and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
   8292      ((or (stringp cmd)
   8293 	  (eq cmd 'emacs))
   8294       (funcall (cdr (assq 'file org-link-frame-setup)) file)
   8295       (widen)
   8296       (cond (line (org-goto-line line)
   8297 		  (when (derived-mode-p 'org-mode) (org-fold-reveal)))
   8298 	    (search (condition-case err
   8299 			(org-link-search search)
   8300 		      ;; Save position before error-ing out so user
   8301 		      ;; can easily move back to the original buffer.
   8302 		      (error (funcall save-position-maybe)
   8303 			     (error (nth 1 err)))))))
   8304      ((functionp cmd)
   8305       (save-match-data
   8306 	(set-match-data link-match-data)
   8307 	(condition-case nil
   8308 	    (funcall cmd file link)
   8309 	  ;; FIXME: Remove this check when most default installations
   8310 	  ;; of Emacs have at least Org 9.0.
   8311 	  ((debug wrong-number-of-arguments wrong-type-argument
   8312 		  invalid-function)
   8313 	   (user-error "Please see Org News for version 9.0 about \
   8314 `org-file-apps'--Lisp error: %S" cmd)))))
   8315      ((consp cmd)
   8316       ;; FIXME: Remove this check when most default installations of
   8317       ;; Emacs have at least Org 9.0.  Heads-up instead of silently
   8318       ;; fall back to `org-link-frame-setup' for an old usage of
   8319       ;; `org-file-apps' with sexp instead of a function for `cmd'.
   8320       (user-error "Please see Org News for version 9.0 about \
   8321 `org-file-apps'--Error: Deprecated usage of %S" cmd))
   8322      (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
   8323     (funcall save-position-maybe)))
   8324 
   8325 ;;;###autoload
   8326 (defun org-open-at-point-global ()
   8327   "Follow a link or a time-stamp like Org mode does.
   8328 Also follow links and emails as seen by `thing-at-point'.
   8329 This command can be called in any mode to follow an external
   8330 link or a time-stamp that has Org mode syntax.  Its behavior
   8331 is undefined when called on internal links like fuzzy links.
   8332 Raise a user error when there is nothing to follow."
   8333   (interactive)
   8334   (let ((tap-url (thing-at-point 'url))
   8335 	(tap-email (thing-at-point 'email)))
   8336     (cond ((org-in-regexp org-link-any-re)
   8337 	   (org-link-open-from-string (match-string-no-properties 0)))
   8338 	  ((or (org-in-regexp org-ts-regexp-both nil t)
   8339 	       (org-in-regexp org-tsr-regexp-both nil t))
   8340 	   (org-follow-timestamp-link))
   8341 	  (tap-url (org-link-open-from-string tap-url))
   8342 	  (tap-email (org-link-open-from-string
   8343 		      (concat "mailto:" tap-email)))
   8344 	  (t (user-error "No link found")))))
   8345 
   8346 (defvar org-open-at-point-functions nil
   8347   "Hook that is run when following a link at point.
   8348 
   8349 Functions in this hook must return t if they identify and follow
   8350 a link at point.  If they don't find anything interesting at point,
   8351 they must return nil.")
   8352 
   8353 (defun org-open-at-point (&optional arg)
   8354   "Open thing at point.
   8355 The thing can be a link, citation, timestamp, footnote, src-block or
   8356 tags.
   8357 
   8358 When point is on a link, follow it.  Normally, files will be
   8359 opened by an appropriate application.  If the optional prefix
   8360 argument ARG is non-nil, Emacs will visit the file.  With
   8361 a double prefix argument, try to open outside of Emacs, in the
   8362 application the system uses for this file type.
   8363 
   8364 When point is on a timestamp, open the agenda at the day
   8365 specified.
   8366 
   8367 When point is a footnote definition, move to the first reference
   8368 found.  If it is on a reference, move to the associated
   8369 definition.
   8370 
   8371 When point is on a src-block of inline src-block, open its result.
   8372 
   8373 When point is on a citation, follow it.
   8374 
   8375 When point is on a headline, display a list of every link in the
   8376 entry, so it is possible to pick one, or all, of them.  If point
   8377 is on a tag, call `org-tags-view' instead.
   8378 
   8379 On top of syntactically correct links, this function also tries
   8380 to open links and time-stamps in comments, node properties, and
   8381 keywords if point is on something looking like a timestamp or
   8382 a link."
   8383   (interactive "P")
   8384   (org-load-modules-maybe)
   8385   (setq org-window-config-before-follow-link (current-window-configuration))
   8386   (org-remove-occur-highlights nil nil t)
   8387   (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
   8388     (let* ((context
   8389 	    ;; Only consider supported types, even if they are not the
   8390 	    ;; closest one.
   8391 	    (org-element-lineage
   8392 	     (org-element-context)
   8393 	     '(citation citation-reference clock comment comment-block
   8394                         footnote-definition footnote-reference headline
   8395                         inline-src-block inlinetask keyword link node-property
   8396                         planning src-block timestamp)
   8397 	     t))
   8398 	   (type (org-element-type context))
   8399 	   (value (org-element-property :value context)))
   8400       (cond
   8401        ((not type) (user-error "No link found"))
   8402        ;; No valid link at point.  For convenience, look if something
   8403        ;; looks like a link under point in some specific places.
   8404        ((memq type '(comment comment-block node-property keyword))
   8405 	(call-interactively #'org-open-at-point-global))
   8406        ;; On a headline or an inlinetask, but not on a timestamp,
   8407        ;; a link, a footnote reference or a citation.
   8408        ((memq type '(headline inlinetask))
   8409 	(org-match-line org-complex-heading-regexp)
   8410 	(let ((tags-beg (match-beginning 5))
   8411 	      (tags-end (match-end 5)))
   8412 	  (if (and tags-beg (>= (point) tags-beg) (< (point) tags-end))
   8413 	      ;; On tags.
   8414 	      (org-tags-view
   8415 	       arg
   8416 	       (save-excursion
   8417 		 (let* ((beg-tag (or (search-backward ":" tags-beg 'at-limit) (point)))
   8418 			(end-tag (search-forward ":" tags-end nil 2)))
   8419 		   (buffer-substring (1+ beg-tag) (1- end-tag)))))
   8420 	    ;; Not on tags.
   8421 	    (pcase (org-offer-links-in-entry (current-buffer) (point) arg)
   8422 	      (`(nil . ,_)
   8423 	       (require 'org-attach)
   8424 	       (when (org-attach-dir)
   8425 		 (message "Opening attachment")
   8426 		 (if (equal arg '(4))
   8427 		     (org-attach-reveal-in-emacs)
   8428 		   (org-attach-reveal))))
   8429 	      (`(,links . ,links-end)
   8430 	       (dolist (link (if (stringp links) (list links) links))
   8431 		 (search-forward link nil links-end)
   8432 		 (goto-char (match-beginning 0))
   8433 		 (org-open-at-point arg)))))))
   8434        ;; On a footnote reference or at definition's label.
   8435        ((or (eq type 'footnote-reference)
   8436 	    (and (eq type 'footnote-definition)
   8437 		 (save-excursion
   8438 		   ;; Do not validate action when point is on the
   8439 		   ;; spaces right after the footnote label, in order
   8440 		   ;; to be on par with behavior on links.
   8441 		   (skip-chars-forward " \t")
   8442 		   (let ((begin
   8443 			  (org-element-property :contents-begin context)))
   8444 		     (if begin (< (point) begin)
   8445 		       (= (org-element-property :post-affiliated context)
   8446 			  (line-beginning-position)))))))
   8447 	(org-footnote-action))
   8448        ;; On a planning line.  Check if we are really on a timestamp.
   8449        ((and (eq type 'planning)
   8450 	     (org-in-regexp org-ts-regexp-both nil t))
   8451 	(org-follow-timestamp-link))
   8452        ;; On a clock line, make sure point is on the timestamp
   8453        ;; before opening it.
   8454        ((and (eq type 'clock)
   8455 	     value
   8456 	     (>= (point) (org-element-property :begin value))
   8457 	     (<= (point) (org-element-property :end value)))
   8458 	(org-follow-timestamp-link))
   8459        ((eq type 'src-block) (org-babel-open-src-block-result))
   8460        ;; Do nothing on white spaces after an object.
   8461        ((>= (point)
   8462 	    (save-excursion
   8463 	      (goto-char (org-element-property :end context))
   8464 	      (skip-chars-backward " \t")
   8465 	      (point)))
   8466 	(user-error "No link found"))
   8467        ((eq type 'inline-src-block) (org-babel-open-src-block-result))
   8468        ((eq type 'timestamp) (org-follow-timestamp-link))
   8469        ((eq type 'link) (org-link-open context arg))
   8470        ((memq type '(citation citation-reference)) (org-cite-follow context arg))
   8471        (t (user-error "No link found")))))
   8472   (run-hook-with-args 'org-follow-link-hook))
   8473 
   8474 ;;;###autoload
   8475 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
   8476   "Offer links in the current entry and return the selected link.
   8477 If there is only one link, return it.
   8478 If NTH is an integer, return the NTH link found.
   8479 If ZERO is a string, check also this string for a link, and if
   8480 there is one, return it."
   8481   (with-current-buffer buffer
   8482     (org-with-wide-buffer
   8483      (goto-char marker)
   8484      (let ((cnt ?0)
   8485 	   have-zero end links link c)
   8486        (when (and (stringp zero) (string-match org-link-bracket-re zero))
   8487 	 (push (match-string 0 zero) links)
   8488 	 (setq cnt (1- cnt) have-zero t))
   8489        (save-excursion
   8490 	 (org-back-to-heading t)
   8491 	 (setq end (save-excursion (outline-next-heading) (point)))
   8492 	 (while (re-search-forward org-link-any-re end t)
   8493            ;; Only consider valid links or links openable via
   8494            ;; `org-open-at-point'.
   8495            (when (memq (org-element-type (org-element-context)) '(link comment comment-block node-property keyword))
   8496 	     (push (match-string 0) links)))
   8497 	 (setq links (org-uniquify (reverse links))))
   8498        (cond
   8499 	((null links)
   8500 	 (message "No links"))
   8501 	((equal (length links) 1)
   8502 	 (setq link (car links)))
   8503 	((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
   8504 	 (setq link (nth (if have-zero nth (1- nth)) links)))
   8505 	(t				; we have to select a link
   8506 	 (save-excursion
   8507 	   (save-window-excursion
   8508 	     (delete-other-windows)
   8509 	     (with-output-to-temp-buffer "*Select Link*"
   8510 	       (dolist (l links)
   8511 		 (cond
   8512 		  ((not (string-match org-link-bracket-re l))
   8513 		   (princ (format "[%c]  %s\n" (cl-incf cnt)
   8514 				  (org-unbracket-string "<" ">" l))))
   8515 		  ((match-end 2)
   8516 		   (princ (format "[%c]  %s (%s)\n" (cl-incf cnt)
   8517 				  (match-string 2 l) (match-string 1 l))))
   8518 		  (t (princ (format "[%c]  %s\n" (cl-incf cnt)
   8519 				    (match-string 1 l)))))))
   8520 	     (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
   8521 	     (message "Select link to open, RET to open all:")
   8522 	     (setq c (read-char-exclusive))
   8523 	     (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
   8524 	 (when (equal c ?q) (user-error "Abort"))
   8525 	 (if (equal c ?\C-m)
   8526 	     (setq link links)
   8527 	   (setq nth (- c ?0))
   8528 	   (when have-zero (setq nth (1+ nth)))
   8529 	   (unless (and (integerp nth) (>= (length links) nth))
   8530 	     (user-error "Invalid link selection"))
   8531 	   (setq link (nth (1- nth) links)))))
   8532        (cons link end)))))
   8533 
   8534 ;;; File search
   8535 
   8536 (defun org-do-occur (regexp &optional cleanup)
   8537   "Call the Emacs command `occur'.
   8538 If CLEANUP is non-nil, remove the printout of the regular expression
   8539 in the *Occur* buffer.  This is useful if the regex is long and not useful
   8540 to read."
   8541   (occur regexp)
   8542   (when cleanup
   8543     (let ((cwin (selected-window)) win beg end)
   8544       (when (setq win (get-buffer-window "*Occur*"))
   8545 	(select-window win))
   8546       (goto-char (point-min))
   8547       (when (re-search-forward "match[a-z]+" nil t)
   8548 	(setq beg (match-end 0))
   8549 	(when (re-search-forward "^[ \t]*[0-9]+" nil t)
   8550 	  (setq end (1- (match-beginning 0)))))
   8551       (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
   8552       (goto-char (point-min))
   8553       (select-window cwin))))
   8554 
   8555 
   8556 ;;; The Mark Ring
   8557 
   8558 (defvar org-mark-ring nil
   8559   "Mark ring for positions before jumps in Org mode.")
   8560 
   8561 (defvar org-mark-ring-last-goto nil
   8562   "Last position in the mark ring used to go back.")
   8563 
   8564 ;; Fill and close the ring
   8565 (setq org-mark-ring nil)
   8566 (setq org-mark-ring-last-goto nil) ;in case file is reloaded
   8567 
   8568 (dotimes (_ org-mark-ring-length) (push (make-marker) org-mark-ring))
   8569 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
   8570 	org-mark-ring)
   8571 
   8572 (defun org-mark-ring-push (&optional pos buffer)
   8573   "Put the current position into the mark ring and rotate it.
   8574 Also push position into the Emacs mark ring.  If optional
   8575 argument POS and BUFFER are not nil, mark this location instead."
   8576   (interactive)
   8577   (let ((pos (or pos (point)))
   8578 	(buffer (or buffer (current-buffer))))
   8579     (with-current-buffer buffer
   8580       (org-with-point-at pos (push-mark nil t)))
   8581     (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
   8582     (move-marker (car org-mark-ring) pos buffer))
   8583   (message
   8584    (substitute-command-keys
   8585     "Position saved to mark ring, go back with `\\[org-mark-ring-goto]'.")))
   8586 
   8587 (defun org-mark-ring-goto (&optional n)
   8588   "Jump to the previous position in the mark ring.
   8589 With prefix arg N, jump back that many stored positions.  When
   8590 called several times in succession, walk through the entire ring.
   8591 Org mode commands jumping to a different position in the current file,
   8592 or to another Org file, automatically push the old position onto the ring."
   8593   (interactive "p")
   8594   (let (p m)
   8595     (if (eq last-command this-command)
   8596 	(setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
   8597       (setq p org-mark-ring))
   8598     (setq org-mark-ring-last-goto p)
   8599     (setq m (car p))
   8600     (pop-to-buffer-same-window (marker-buffer m))
   8601     (goto-char m)
   8602     (when (or (org-invisible-p) (org-invisible-p2)) (org-fold-show-context 'mark-goto))))
   8603 
   8604 ;;; Following specific links
   8605 
   8606 (defvar org-agenda-buffer-tmp-name)
   8607 (defvar org-agenda-start-on-weekday)
   8608 (defvar org-agenda-buffer-name)
   8609 (defun org-follow-timestamp-link ()
   8610   "Open an agenda view for the time-stamp date/range at point."
   8611   ;; Avoid changing the global value.
   8612   (let ((org-agenda-buffer-name org-agenda-buffer-name))
   8613     (cond
   8614      ((org-at-date-range-p t)
   8615       (let ((org-agenda-start-on-weekday)
   8616 	    (t1 (match-string 1))
   8617 	    (t2 (match-string 2)) tt1 tt2)
   8618 	(setq tt1 (time-to-days (org-time-string-to-time t1))
   8619 	      tt2 (time-to-days (org-time-string-to-time t2)))
   8620 	(let ((org-agenda-buffer-tmp-name
   8621 	       (format "*Org Agenda(a:%s)"
   8622 		       (concat (substring t1 0 10) "--" (substring t2 0 10)))))
   8623 	  (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
   8624      ((org-at-timestamp-p 'lax)
   8625       (let ((org-agenda-buffer-tmp-name
   8626 	     (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
   8627 	(org-agenda-list nil (time-to-days (org-time-string-to-time
   8628 					    (substring (match-string 1) 0 10)))
   8629 			 1)))
   8630      (t (error "This should not happen")))))
   8631 
   8632 
   8633 ;;; Following file links
   8634 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
   8635 (declare-function mailcap-extension-to-mime "mailcap" (extn))
   8636 (declare-function mailcap-mime-info
   8637 		  "mailcap" (string &optional request no-decode))
   8638 (defvar org-wait nil)
   8639 
   8640 ;;;; Refiling
   8641 
   8642 (defun org-get-org-file ()
   8643   "Read a filename, with default directory `org-directory'."
   8644   (let ((default (or org-default-notes-file remember-data-file)))
   8645     (read-file-name (format "File name [%s]: " default)
   8646 		    (file-name-as-directory org-directory)
   8647 		    default)))
   8648 
   8649 (defun org-notes-order-reversed-p ()
   8650   "Check if the current file should receive notes in reversed order."
   8651   (cond
   8652    ((not org-reverse-note-order) nil)
   8653    ((eq t org-reverse-note-order) t)
   8654    ((not (listp org-reverse-note-order)) nil)
   8655    (t (catch 'exit
   8656         (dolist (entry org-reverse-note-order)
   8657           (when (string-match (car entry) buffer-file-name)
   8658 	    (throw 'exit (cdr entry))))))))
   8659 
   8660 (defvar org-agenda-new-buffers nil
   8661   "Buffers created to visit agenda files.")
   8662 
   8663 (declare-function org-string-nw-p "org-macs" (s))
   8664 ;;;; Dynamic blocks
   8665 
   8666 (defun org-find-dblock (name)
   8667   "Find the first dynamic block with name NAME in the buffer.
   8668 If not found, stay at current position and return nil."
   8669   (let ((case-fold-search t) pos)
   8670     (save-excursion
   8671       (goto-char (point-min))
   8672       (setq pos (and (re-search-forward
   8673 		      (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
   8674 		     (match-beginning 0))))
   8675     (when pos (goto-char pos))
   8676     pos))
   8677 
   8678 (defun org-create-dblock (plist)
   8679   "Create a dynamic block section, with parameters taken from PLIST.
   8680 PLIST must contain a :name entry which is used as the name of the block."
   8681   (when (string-match "\\S-" (buffer-substring (line-beginning-position)
   8682                                                (line-end-position)))
   8683     (end-of-line 1)
   8684     (newline))
   8685   (let ((col (current-column))
   8686 	(name (plist-get plist :name)))
   8687     (insert "#+BEGIN: " name)
   8688     (while plist
   8689       (if (eq (car plist) :name)
   8690 	  (setq plist (cddr plist))
   8691 	(insert " " (prin1-to-string (pop plist)))))
   8692     (insert "\n\n" (make-string col ?\ ) "#+END:\n")
   8693     (beginning-of-line -2)))
   8694 
   8695 (defun org-prepare-dblock ()
   8696   "Prepare dynamic block for refresh.
   8697 This empties the block, puts the cursor at the insert position and returns
   8698 the property list including an extra property :name with the block name."
   8699   (unless (looking-at org-dblock-start-re)
   8700     (user-error "Not at a dynamic block"))
   8701   (let* ((begdel (1+ (match-end 0)))
   8702 	 (name (org-no-properties (match-string 1)))
   8703 	 (params (append (list :name name)
   8704 			 (read (concat "(" (match-string 3) ")")))))
   8705     (save-excursion
   8706       (beginning-of-line 1)
   8707       (skip-chars-forward " \t")
   8708       (setq params (plist-put params :indentation-column (current-column))))
   8709     (unless (re-search-forward org-dblock-end-re nil t)
   8710       (error "Dynamic block not terminated"))
   8711     (setq params
   8712 	  (append params
   8713 		  (list :content (buffer-substring
   8714 				  begdel (match-beginning 0)))))
   8715     (delete-region begdel (match-beginning 0))
   8716     (goto-char begdel)
   8717     (open-line 1)
   8718     params))
   8719 
   8720 (defun org-map-dblocks (&optional command)
   8721   "Apply COMMAND to all dynamic blocks in the current buffer.
   8722 If COMMAND is not given, use `org-update-dblock'."
   8723   (let ((cmd (or command 'org-update-dblock)))
   8724     (save-excursion
   8725       (goto-char (point-min))
   8726       (while (re-search-forward org-dblock-start-re nil t)
   8727 	(goto-char (match-beginning 0))
   8728         (save-excursion
   8729           (condition-case nil
   8730               (funcall cmd)
   8731             (error (message "Error during update of dynamic block"))))
   8732 	(unless (re-search-forward org-dblock-end-re nil t)
   8733 	  (error "Dynamic block not terminated"))))))
   8734 
   8735 (defvar org-dynamic-block-alist nil
   8736   "Alist defining all the Org dynamic blocks.
   8737 
   8738 The key is the dynamic block type name, as a string.  The value
   8739 is the function used to insert the dynamic block.
   8740 
   8741 Use `org-dynamic-block-define' to populate it.")
   8742 
   8743 (defun org-dynamic-block-function (type)
   8744   "Return function associated to a given dynamic block type.
   8745 TYPE is the dynamic block type, as a string."
   8746   (cdr (assoc type org-dynamic-block-alist)))
   8747 
   8748 (defun org-dynamic-block-types ()
   8749   "List all defined dynamic block types."
   8750   (mapcar #'car org-dynamic-block-alist))
   8751 
   8752 ;;;###org-autoload
   8753 (defun org-dynamic-block-define (type func)
   8754   "Define dynamic block TYPE with FUNC.
   8755 TYPE is a string.  FUNC is the function creating the dynamic
   8756 block of such type."
   8757   (pcase (assoc type org-dynamic-block-alist)
   8758     (`nil (push (cons type func) org-dynamic-block-alist))
   8759     (def (setcdr def func))))
   8760 
   8761 (defun org-dynamic-block-insert-dblock (type &optional interactive-p)
   8762   "Insert a dynamic block of type TYPE.
   8763 When used interactively, select the dynamic block types among
   8764 defined types, per `org-dynamic-block-define'.  If INTERACTIVE-P
   8765 is non-nil, call the dynamic block function interactively."
   8766   (interactive (list (completing-read "Dynamic block: "
   8767 				      (org-dynamic-block-types))
   8768 		     t))
   8769   (pcase (org-dynamic-block-function type)
   8770     (`nil (error "No such dynamic block: %S" type))
   8771     ((and f (pred functionp))
   8772      (if interactive-p (call-interactively f) (funcall f)))
   8773     (_ (error "Invalid function for dynamic block %S" type))))
   8774 
   8775 (defun org-dblock-update (&optional arg)
   8776   "User command for updating dynamic blocks.
   8777 Update the dynamic block at point.  With prefix ARG, update all dynamic
   8778 blocks in the buffer."
   8779   (interactive "P")
   8780   (if arg
   8781       (org-update-all-dblocks)
   8782     (or (looking-at org-dblock-start-re)
   8783 	(org-beginning-of-dblock))
   8784     (org-update-dblock)))
   8785 
   8786 (defun org-update-dblock ()
   8787   "Update the dynamic block at point.
   8788 This means to empty the block, parse for parameters and then call
   8789 the correct writing function."
   8790   (interactive)
   8791   (save-excursion
   8792     (let* ((win (selected-window))
   8793 	   (pos (point))
   8794 	   (line (org-current-line))
   8795 	   (params (org-prepare-dblock))
   8796 	   (name (plist-get params :name))
   8797 	   (indent (plist-get params :indentation-column))
   8798 	   (cmd (intern (concat "org-dblock-write:" name))))
   8799       (message "Updating dynamic block `%s' at line %d..." name line)
   8800       (funcall cmd params)
   8801       (message "Updating dynamic block `%s' at line %d...done" name line)
   8802       (goto-char pos)
   8803       (when (and indent (> indent 0))
   8804 	(setq indent (make-string indent ?\ ))
   8805 	(save-excursion
   8806 	  (select-window win)
   8807 	  (org-beginning-of-dblock)
   8808 	  (forward-line 1)
   8809 	  (while (not (looking-at org-dblock-end-re))
   8810 	    (insert indent)
   8811 	    (beginning-of-line 2))
   8812 	  (when (looking-at org-dblock-end-re)
   8813 	    (and (looking-at "[ \t]+")
   8814 		 (replace-match ""))
   8815 	    (insert indent)))))))
   8816 
   8817 (defun org-beginning-of-dblock ()
   8818   "Find the beginning of the dynamic block at point.
   8819 Error if there is no such block at point."
   8820   (let ((pos (point))
   8821 	beg)
   8822     (end-of-line 1)
   8823     (if (and (re-search-backward org-dblock-start-re nil t)
   8824 	     (setq beg (match-beginning 0))
   8825 	     (re-search-forward org-dblock-end-re nil t)
   8826 	     (> (match-end 0) pos))
   8827 	(goto-char beg)
   8828       (goto-char pos)
   8829       (error "Not in a dynamic block"))))
   8830 
   8831 (defun org-update-all-dblocks ()
   8832   "Update all dynamic blocks in the buffer.
   8833 This function can be used in a hook."
   8834   (interactive)
   8835   (when (derived-mode-p 'org-mode)
   8836     (org-map-dblocks 'org-update-dblock)))
   8837 
   8838 
   8839 ;;;; Completion
   8840 
   8841 (declare-function org-export-backend-options "ox" (cl-x) t)
   8842 (defun org-get-export-keywords ()
   8843   "Return a list of all currently understood export keywords.
   8844 Export keywords include options, block names, attributes and
   8845 keywords relative to each registered export back-end."
   8846   (let (keywords)
   8847     (dolist (backend
   8848 	     (bound-and-true-p org-export-registered-backends)
   8849 	     (delq nil keywords))
   8850       ;; Back-end name (for keywords, like #+LATEX:)
   8851       (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
   8852       (dolist (option-entry (org-export-backend-options backend))
   8853 	;; Back-end options.
   8854 	(push (nth 1 option-entry) keywords)))))
   8855 
   8856 (defconst org-options-keywords
   8857   '("ARCHIVE:" "AUTHOR:" "BIBLIOGRAPHY:" "BIND:" "CATEGORY:" "CITE_EXPORT:"
   8858     "COLUMNS:" "CREATOR:" "DATE:" "DESCRIPTION:" "DRAWERS:" "EMAIL:"
   8859     "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:" "INDEX:" "KEYWORDS:" "LANGUAGE:"
   8860     "MACRO:" "OPTIONS:" "PROPERTY:" "PRINT_BIBLIOGRAPHY" "PRIORITIES:"
   8861     "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:" "TITLE:" "TODO:"
   8862     "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:" "EXPORT_FILE_NAME:"))
   8863 
   8864 (defcustom org-structure-template-alist
   8865   '(("a" . "export ascii")
   8866     ("c" . "center")
   8867     ("C" . "comment")
   8868     ("e" . "example")
   8869     ("E" . "export")
   8870     ("h" . "export html")
   8871     ("l" . "export latex")
   8872     ("q" . "quote")
   8873     ("s" . "src")
   8874     ("v" . "verse"))
   8875   "An alist of keys and block types.
   8876 `org-insert-structure-template' will display a menu with this list of
   8877 templates to choose from.  The block type is inserted, with
   8878 \"#+begin_\" and \"#+end_\" added automatically.  If the block type
   8879 consists of just uppercase letters, \"#+BEGIN_\" and \"#+END_\" are
   8880 added instead.
   8881 
   8882 The menu keys are defined by the car of each entry in this alist.
   8883 If two entries have the keys \"a\" and \"aa\" respectively, the
   8884 former will be inserted by typing \"a TAB/RET/SPC\" and the
   8885 latter will be inserted by typing \"aa\".  If an entry with the
   8886 key \"aab\" is later added, it can be inserted by typing \"ab\".
   8887 
   8888 If loaded, Org Tempo also uses `org-structure-template-alist'.  A
   8889 block can be inserted by pressing TAB after the string \"<KEY\"."
   8890   :group 'org-edit-structure
   8891   :type '(repeat
   8892 	  (cons (string :tag "Key")
   8893 		(string :tag "Template")))
   8894   :package-version '(Org . "9.6"))
   8895 
   8896 (defun org--check-org-structure-template-alist (&optional checklist)
   8897   "Check whether `org-structure-template-alist' is set up correctly.
   8898 In particular, check if the Org 9.2 format is used as opposed to
   8899 previous format."
   8900   (let ((elm (cl-remove-if-not (lambda (x) (listp (cdr x)))
   8901 			       (or (symbol-value checklist)
   8902 				   org-structure-template-alist))))
   8903     (when elm
   8904       (org-display-warning
   8905        (format "
   8906 Please update the entries of `%s'.
   8907 
   8908 In Org 9.2 the format was changed from something like
   8909 
   8910     (\"s\" \"#+BEGIN_SRC ?\\n#+END_SRC\")
   8911 
   8912 to something like
   8913 
   8914     (\"s\" . \"src\")
   8915 
   8916 Please refer to the documentation of `org-structure-template-alist'.
   8917 
   8918 The following entries must be updated:
   8919 
   8920 %s"
   8921 	       (or checklist 'org-structure-template-alist)
   8922 	       (pp-to-string elm))))))
   8923 
   8924 (defun org--insert-structure-template-mks ()
   8925   "Present `org-structure-template-alist' with `org-mks'.
   8926 
   8927 Menus are added if keys require more than one keystroke.  Tabs
   8928 are added to single key entries when more than one stroke is
   8929 needed.  Keys longer than two characters are reduced to two
   8930 characters."
   8931   (org--check-org-structure-template-alist)
   8932   (let* (case-fold-search
   8933 	 (templates (append org-structure-template-alist
   8934 			    '(("\t" . "Press TAB, RET or SPC to write block name"))))
   8935          (keys (mapcar #'car templates))
   8936          (start-letters
   8937 	  (delete-dups (mapcar (lambda (key) (substring key 0 1)) keys)))
   8938 	 ;; Sort each element of `org-structure-template-alist' into
   8939 	 ;; sublists according to the first letter.
   8940          (superlist
   8941 	  (mapcar (lambda (letter)
   8942                     (list letter
   8943 			  (cl-remove-if-not
   8944 			   (apply-partially #'string-match-p (concat "^" letter))
   8945 			   templates :key #'car)))
   8946 		  start-letters)))
   8947     (org-mks
   8948      (apply #'append
   8949 	    ;; Make an `org-mks' table.  If only one element is
   8950 	    ;; present in a sublist, make it part of the top-menu,
   8951 	    ;; otherwise make a submenu according to the starting
   8952 	    ;; letter and populate it.
   8953 	    (mapcar (lambda (sublist)
   8954 		      (if (eq 1 (length (cadr sublist)))
   8955                           (mapcar (lambda (elm)
   8956 				    (list (substring (car elm) 0 1)
   8957                                           (cdr elm) ""))
   8958                                   (cadr sublist))
   8959 			;; Create submenu.
   8960                         (let* ((topkey (car sublist))
   8961 			       (elms (cadr sublist))
   8962 			       (keys (mapcar #'car elms))
   8963 			       (long (> (length elms) 3)))
   8964                           (append
   8965 			   (list
   8966 			    ;; Make a description of the submenu.
   8967 			    (list topkey
   8968 				  (concat
   8969 				   (mapconcat #'cdr
   8970 					      (cl-subseq elms 0 (if long 3 (length elms)))
   8971 					      ", ")
   8972                                    (when long ", ..."))))
   8973 			   ;; List of entries in submenu.
   8974 			   (cl-mapcar #'list
   8975 				      (org--insert-structure-template-unique-keys keys)
   8976 				      (mapcar #'cdr elms)
   8977 				      (make-list (length elms) ""))))))
   8978 		    superlist))
   8979      "Select a key\n============"
   8980      "Key: ")))
   8981 
   8982 (defun org--insert-structure-template-unique-keys (keys)
   8983   "Make a list of unique, two characters long elements from KEYS.
   8984 
   8985 Elements of length one have a tab appended.  Elements of length
   8986 two are kept as is.  Longer elements are truncated to length two.
   8987 
   8988 If an element cannot be made unique, an error is raised."
   8989   (let ((ordered-keys (cl-sort (copy-sequence keys) #'< :key #'length))
   8990 	menu-keys)
   8991     (dolist (key ordered-keys)
   8992       (let ((potential-key
   8993 	     (cl-case (length key)
   8994 	       (1 (concat key "\t"))
   8995 	       (2 key)
   8996 	       (otherwise
   8997 		(cl-find-if-not (lambda (k) (assoc k menu-keys))
   8998 				(mapcar (apply-partially #'concat (substring  key 0 1))
   8999 					(split-string (substring key 1) "" t)))))))
   9000 	(if (or (not potential-key) (assoc potential-key menu-keys))
   9001             (user-error "Could not make unique key for `%s'" key)
   9002 	  (push (cons potential-key key) menu-keys))))
   9003     (mapcar #'car
   9004 	    (cl-sort menu-keys #'<
   9005 		     :key (lambda (elm) (cl-position (cdr elm) keys))))))
   9006 
   9007 (defun org-insert-structure-template (type)
   9008   "Insert a block structure of the type #+begin_foo/#+end_foo.
   9009 Select a block from `org-structure-template-alist' then type
   9010 either RET, TAB or SPC to write the block type.  With an active
   9011 region, wrap the region in the block.  Otherwise, insert an empty
   9012 block.
   9013 
   9014 When foo is written as FOO, upcase the #+BEGIN/END as well."
   9015   (interactive
   9016    (list (pcase (org--insert-structure-template-mks)
   9017 	   (`("\t" . ,_) (read-string "Structure type: "))
   9018 	   (`(,_ ,choice . ,_) choice))))
   9019   (let* ((case-fold-search t) ; Make sure that matches are case-insensitive.
   9020          (region? (use-region-p))
   9021 	 (region-start (and region? (region-beginning)))
   9022 	 (region-end (and region? (copy-marker (region-end))))
   9023 	 (extended? (string-match-p "\\`\\(src\\|export\\)\\'" type))
   9024 	 (verbatim? (string-match-p
   9025 		     (concat "\\`" (regexp-opt '("example" "export"
   9026                                                 "src" "comment")))
   9027 		     type))
   9028          (upcase? (string= (car (split-string type))
   9029                            (upcase (car (split-string type))))))
   9030     (when region? (goto-char region-start))
   9031     (let ((column (current-indentation)))
   9032       (if (save-excursion (skip-chars-backward " \t") (bolp))
   9033 	  (beginning-of-line)
   9034 	(insert "\n"))
   9035       (save-excursion
   9036 	(indent-to column)
   9037 	(insert (format "#+%s_%s%s\n" (if upcase? "BEGIN" "begin") type (if extended? " " "")))
   9038 	(when region?
   9039 	  (when verbatim? (org-escape-code-in-region (point) region-end))
   9040 	  (goto-char region-end)
   9041 	  ;; Ignore empty lines at the end of the region.
   9042 	  (skip-chars-backward " \r\t\n")
   9043 	  (end-of-line))
   9044 	(unless (bolp) (insert "\n"))
   9045 	(indent-to column)
   9046 	(insert (format "#+%s_%s" (if upcase? "END" "end") (car (split-string type))))
   9047 	(if (looking-at "[ \t]*$") (replace-match "")
   9048 	  (insert "\n"))
   9049 	(when (and (eobp) (not (bolp))) (insert "\n")))
   9050       (if extended? (end-of-line)
   9051 	(forward-line)
   9052 	(skip-chars-forward " \t")))))
   9053 
   9054 
   9055 ;;;; TODO, DEADLINE, Comments
   9056 
   9057 (defun org-toggle-comment ()
   9058   "Change the COMMENT state of an entry."
   9059   (interactive)
   9060   (save-excursion
   9061     (org-back-to-heading)
   9062     (let ((case-fold-search nil))
   9063       (looking-at org-complex-heading-regexp))
   9064     (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
   9065     (skip-chars-forward " \t")
   9066     (unless (memq (char-before) '(?\s ?\t)) (insert " "))
   9067     (if (org-in-commented-heading-p t)
   9068 	(delete-region (point)
   9069 		       (progn (search-forward " " (line-end-position) 'move)
   9070 			      (skip-chars-forward " \t")
   9071 			      (point)))
   9072       (insert org-comment-string)
   9073       (unless (eolp) (insert " ")))))
   9074 
   9075 (defvar org-last-todo-state-is-todo nil
   9076   "This is non-nil when the last TODO state change led to a TODO state.
   9077 If the last change removed the TODO tag or switched to DONE, then
   9078 this is nil.")
   9079 
   9080 (defvar org-todo-setup-filter-hook nil
   9081   "Hook for functions that pre-filter todo specs.
   9082 Each function takes a todo spec and returns either nil or the spec
   9083 transformed into canonical form." )
   9084 
   9085 (defvar org-todo-get-default-hook nil
   9086   "Hook for functions that get a default item for todo.
   9087 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
   9088 nil or a string to be used for the todo mark." )
   9089 
   9090 (defvar org-agenda-headline-snapshot-before-repeat)
   9091 
   9092 (defun org-current-effective-time ()
   9093   "Return current time adjusted for `org-extend-today-until' variable."
   9094   (let* ((ct (org-current-time))
   9095 	 (dct (decode-time ct))
   9096 	 (ct1
   9097 	  (cond
   9098 	   (org-use-last-clock-out-time-as-effective-time
   9099 	    (or (org-clock-get-last-clock-out-time) ct))
   9100 	   ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
   9101 	    (org-encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
   9102 	   (t ct))))
   9103     ct1))
   9104 
   9105 (defun org-todo-yesterday (&optional arg)
   9106   "Like `org-todo' but the time of change will be 23:59 of yesterday."
   9107   (interactive "P")
   9108   (if (eq major-mode 'org-agenda-mode)
   9109       (org-agenda-todo-yesterday arg)
   9110     (let* ((org-use-effective-time t)
   9111 	   (hour (nth 2 (decode-time (org-current-time))))
   9112 	   (org-extend-today-until (1+ hour)))
   9113       (org-todo arg))))
   9114 
   9115 (defvar org-block-entry-blocking ""
   9116   "First entry preventing the TODO state change.")
   9117 
   9118 (defun org-cancel-repeater ()
   9119   "Cancel a repeater by setting its numeric value to zero."
   9120   (interactive)
   9121   (save-excursion
   9122     (org-back-to-heading t)
   9123     (let ((bound1 (point))
   9124 	  (bound0 (save-excursion (outline-next-heading) (point))))
   9125       (when (and (re-search-forward
   9126 		  (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
   9127 			  org-deadline-time-regexp "\\)\\|\\("
   9128 			  org-ts-regexp "\\)")
   9129 		  bound0 t)
   9130 		 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
   9131 				     bound1 t))
   9132 	(replace-match "0" t nil nil 1)))))
   9133 
   9134 (defvar org-state)
   9135 (defvar org-blocked-by-checkboxes)
   9136 (defun org-todo (&optional arg)
   9137   "Change the TODO state of an item.
   9138 
   9139 The state of an item is given by a keyword at the start of the heading,
   9140 like
   9141      *** TODO Write paper
   9142      *** DONE Call mom
   9143 
   9144 The different keywords are specified in the variable `org-todo-keywords'.
   9145 By default the available states are \"TODO\" and \"DONE\".  So, for this
   9146 example: when the item starts with TODO, it is changed to DONE.
   9147 When it starts with DONE, the DONE is removed.  And when neither TODO nor
   9148 DONE are present, add TODO at the beginning of the heading.
   9149 You can set up single-character keys to fast-select the new state.  See the
   9150 `org-todo-keywords' and `org-use-fast-todo-selection' for details.
   9151 
   9152 With `\\[universal-argument]' prefix ARG, force logging the state change \
   9153 and take a
   9154 logging note.
   9155 With a `\\[universal-argument] \\[universal-argument]' prefix, switch to the \
   9156 next set of TODO \
   9157 keywords (nextset).
   9158 Another way to achieve this is `S-C-<right>'.
   9159 With a `\\[universal-argument] \\[universal-argument] \\[universal-argument]' \
   9160 prefix, circumvent any state blocking.
   9161 With numeric prefix arg, switch to the Nth state.
   9162 
   9163 With a numeric prefix arg of 0, inhibit note taking for the change.
   9164 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
   9165 
   9166 When called through ELisp, arg is also interpreted in the following way:
   9167 `none'        -> empty state
   9168 \"\"            -> switch to empty state
   9169 `done'        -> switch to DONE
   9170 `nextset'     -> switch to the next set of keywords
   9171 `previousset' -> switch to the previous set of keywords
   9172 \"WAITING\"     -> switch to the specified keyword, but only if it
   9173                  really is a member of `org-todo-keywords'."
   9174   (interactive "P")
   9175   (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
   9176       (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
   9177 		    'region-start-level 'region))
   9178 	    org-loop-over-headlines-in-active-region)
   9179 	(org-map-entries
   9180 	 (lambda () (org-todo arg))
   9181 	 nil cl
   9182 	 (when (org-invisible-p) (org-end-of-subtree nil t))))
   9183     (when (equal arg '(16)) (setq arg 'nextset))
   9184     (when (equal (prefix-numeric-value arg) -1) (org-cancel-repeater) (setq arg nil))
   9185     (when (< (prefix-numeric-value arg) -1) (user-error "Prefix argument %d not supported" arg))
   9186     (let ((org-blocker-hook org-blocker-hook)
   9187 	  commentp
   9188 	  case-fold-search)
   9189       (when (equal arg '(64))
   9190 	(setq arg nil org-blocker-hook nil))
   9191       (when (and org-blocker-hook
   9192 		 (or org-inhibit-blocking
   9193 		     (org-entry-get nil "NOBLOCKING")))
   9194 	(setq org-blocker-hook nil))
   9195       (save-excursion
   9196 	(catch 'exit
   9197 	  (org-back-to-heading t)
   9198 	  (when (org-in-commented-heading-p t)
   9199 	    (org-toggle-comment)
   9200 	    (setq commentp t))
   9201 	  (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
   9202 	  (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
   9203 	      (looking-at "\\(?: *\\|[ \t]*$\\)"))
   9204 	  (let* ((match-data (match-data))
   9205 		 (startpos (copy-marker (line-beginning-position)))
   9206 		 (force-log (and  (equal arg '(4)) (prog1 t (setq arg nil))))
   9207 		 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
   9208 		 (org-log-done org-log-done)
   9209 		 (org-log-repeat org-log-repeat)
   9210 		 (org-todo-log-states org-todo-log-states)
   9211 		 (org-inhibit-logging
   9212 		  (if (equal arg 0)
   9213 		      (progn (setq arg nil) 'note) org-inhibit-logging))
   9214 		 (this (match-string 1))
   9215 		 (hl-pos (match-beginning 0))
   9216 		 (head (org-get-todo-sequence-head this))
   9217 		 (ass (assoc head org-todo-kwd-alist))
   9218 		 (interpret (nth 1 ass))
   9219 		 (done-word (nth 3 ass))
   9220 		 (final-done-word (nth 4 ass))
   9221 		 (org-last-state (or this ""))
   9222 		 (completion-ignore-case t)
   9223 		 (member (member this org-todo-keywords-1))
   9224 		 (tail (cdr member))
   9225 		 (org-state (cond
   9226 			     ((eq arg 'right)
   9227 			      ;; Next state
   9228 			      (if this
   9229 			          (if tail (car tail) nil)
   9230 			        (car org-todo-keywords-1)))
   9231 			     ((eq arg 'left)
   9232 			      ;; Previous state
   9233 			      (unless (equal member org-todo-keywords-1)
   9234 			        (if this
   9235 				    (nth (- (length org-todo-keywords-1)
   9236 					    (length tail) 2)
   9237 				         org-todo-keywords-1)
   9238 			          (org-last org-todo-keywords-1))))
   9239 			     (arg
   9240 			      ;; User or caller requests a specific state.
   9241 			      (cond
   9242 			       ((equal arg "") nil)
   9243 			       ((eq arg 'none) nil)
   9244 			       ((eq arg 'done) (or done-word (car org-done-keywords)))
   9245 			       ((eq arg 'nextset)
   9246 			        (or (car (cdr (member head org-todo-heads)))
   9247 				    (car org-todo-heads)))
   9248 			       ((eq arg 'previousset)
   9249 			        (let ((org-todo-heads (reverse org-todo-heads)))
   9250 			          (or (car (cdr (member head org-todo-heads)))
   9251 				      (car org-todo-heads))))
   9252 			       ((car (member arg org-todo-keywords-1)))
   9253 			       ((stringp arg)
   9254 			        (user-error "State `%s' not valid in this file" arg))
   9255 			       ((nth (1- (prefix-numeric-value arg))
   9256 				     org-todo-keywords-1))))
   9257 			     ((and org-todo-key-trigger org-use-fast-todo-selection)
   9258 			      ;; Use fast selection.
   9259 			      (org-fast-todo-selection this))
   9260 			     ((null member) (or head (car org-todo-keywords-1)))
   9261 			     ((equal this final-done-word) nil) ;-> make empty
   9262 			     ((null tail) nil) ;-> first entry
   9263 			     ((memq interpret '(type priority))
   9264 			      (if (eq this-command last-command)
   9265 			          (car tail)
   9266 			        (if (> (length tail) 0)
   9267 				    (or done-word (car org-done-keywords))
   9268 			          nil)))
   9269 			     (t
   9270 			      (car tail))))
   9271 		 (org-state (or
   9272 			     (run-hook-with-args-until-success
   9273 			      'org-todo-get-default-hook org-state org-last-state)
   9274 			     org-state))
   9275 		 (next (if (org-string-nw-p org-state) (concat " " org-state " ") " "))
   9276 		 (change-plist (list :type 'todo-state-change :from this :to org-state
   9277 				     :position startpos))
   9278 		 dolog now-done-p)
   9279 	    (when org-blocker-hook
   9280 	      (let (org-blocked-by-checkboxes block-reason)
   9281 		(setq org-last-todo-state-is-todo
   9282 		      (not (member this org-done-keywords)))
   9283 		(unless (save-excursion
   9284 			  (save-match-data
   9285 			    (org-with-wide-buffer
   9286 			     (run-hook-with-args-until-failure
   9287 			      'org-blocker-hook change-plist))))
   9288 		  (setq block-reason (if org-blocked-by-checkboxes
   9289 					 "contained checkboxes"
   9290 				       (format "\"%s\"" org-block-entry-blocking)))
   9291 		  (if (called-interactively-p 'interactive)
   9292 		      (user-error "TODO state change from %s to %s blocked (by %s)"
   9293 				  this org-state block-reason)
   9294 		    ;; Fail silently.
   9295 		    (message "TODO state change from %s to %s blocked (by %s)"
   9296 			     this org-state block-reason)
   9297 		    (throw 'exit nil)))))
   9298 	    (store-match-data match-data)
   9299             (org-fold-core-ignore-modifications
   9300               (goto-char (match-beginning 0))
   9301               (replace-match "")
   9302               ;; We need to use `insert-before-markers-and-inherit'
   9303               ;; because: (1) We want to preserve the folding state
   9304               ;; text properties; (2) We do not want to make point
   9305               ;; move before new todo state when inserting a new todo
   9306               ;; into an empty heading.  In (2), the above
   9307               ;; `save-excursion' is relying on markers saved before.
   9308               (insert-before-markers-and-inherit next)
   9309               (unless (org-invisible-p (line-beginning-position))
   9310                 (org-fold-region (line-beginning-position)
   9311                                  (line-end-position)
   9312                                  nil)))
   9313 	    (cond ((and org-state (equal this org-state))
   9314 		   (message "TODO state was already %s" (org-trim next)))
   9315 		  ((not (pos-visible-in-window-p hl-pos))
   9316 		   (message "TODO state changed to %s" (org-trim next))))
   9317 	    (unless head
   9318 	      (setq head (org-get-todo-sequence-head org-state)
   9319 		    ass (assoc head org-todo-kwd-alist)
   9320 		    interpret (nth 1 ass)
   9321 		    done-word (nth 3 ass)
   9322 		    final-done-word (nth 4 ass)))
   9323 	    (when (memq arg '(nextset previousset))
   9324 	      (message "Keyword-Set %d/%d: %s"
   9325 		       (- (length org-todo-sets) -1
   9326 			  (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
   9327 		       (length org-todo-sets)
   9328 		       (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
   9329 	    (setq org-last-todo-state-is-todo
   9330 		  (not (member org-state org-done-keywords)))
   9331 	    (setq now-done-p (and (member org-state org-done-keywords)
   9332 				  (not (member this org-done-keywords))))
   9333 	    (and logging (org-local-logging logging))
   9334 	    (when (or (and (or org-todo-log-states org-log-done)
   9335 			   (not (eq org-inhibit-logging t))
   9336 			   (not (memq arg '(nextset previousset))))
   9337 		      force-log)
   9338 	      ;; We need to look at recording a time and note.
   9339 	      (setq dolog (or (if force-log 'note)
   9340 			      (nth 1 (assoc org-state org-todo-log-states))
   9341 			      (nth 2 (assoc this org-todo-log-states))))
   9342 	      (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
   9343 		(setq dolog 'time))
   9344 	      (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
   9345 			(and org-state
   9346 			     (member org-state org-not-done-keywords)
   9347 			     (not (member this org-not-done-keywords))))
   9348 		;; This is now a todo state and was not one before
   9349 		;; If there was a CLOSED time stamp, get rid of it.
   9350 		(org-add-planning-info nil nil 'closed))
   9351 	      (when (and now-done-p org-log-done)
   9352 		;; It is now done, and it was not done before.
   9353 		(org-add-planning-info 'closed (org-current-effective-time))
   9354 		(when (and (not dolog) (eq 'note org-log-done))
   9355 		  (org-add-log-setup 'done org-state this 'note)))
   9356 	      (when (and org-state dolog)
   9357 		;; This is a non-nil state, and we need to log it.
   9358 		(org-add-log-setup 'state org-state this dolog)))
   9359 	    ;; Fixup tag positioning.
   9360 	    (org-todo-trigger-tag-changes org-state)
   9361 	    (when org-auto-align-tags (org-align-tags))
   9362 	    (when org-provide-todo-statistics
   9363 	      (org-update-parent-todo-statistics))
   9364 	    (when (bound-and-true-p org-clock-out-when-done)
   9365 	      (org-clock-out-if-current))
   9366 	    (run-hooks 'org-after-todo-state-change-hook)
   9367 	    (when (and arg (not (member org-state org-done-keywords)))
   9368 	      (setq head (org-get-todo-sequence-head org-state)))
   9369             (put-text-property (line-beginning-position)
   9370                                (line-end-position) 'org-todo-head head)
   9371 	    ;; Do we need to trigger a repeat?
   9372 	    (when now-done-p
   9373 	      (when (boundp 'org-agenda-headline-snapshot-before-repeat)
   9374 		;; This is for the agenda, take a snapshot of the headline.
   9375 		(save-match-data
   9376 		  (setq org-agenda-headline-snapshot-before-repeat
   9377 			(org-get-heading))))
   9378 	      (org-auto-repeat-maybe org-state))
   9379 	    ;; Fixup cursor location if close to the keyword.
   9380 	    (when (and (outline-on-heading-p)
   9381 		       (not (bolp))
   9382 		       (save-excursion (beginning-of-line 1)
   9383 				       (looking-at org-todo-line-regexp))
   9384 		       (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
   9385 	      (goto-char (or (match-end 2) (match-end 1)))
   9386 	      (and (looking-at " ")
   9387 		   (not (looking-at " *:"))
   9388 		   (just-one-space)))
   9389 	    (when org-trigger-hook
   9390 	      (save-excursion
   9391 		(run-hook-with-args 'org-trigger-hook change-plist)))
   9392 	    (when commentp (org-toggle-comment))))))))
   9393 
   9394 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
   9395   "Block turning an entry into a TODO, using the hierarchy.
   9396 This checks whether the current task should be blocked from state
   9397 changes.  Such blocking occurs when:
   9398 
   9399   1. The task has children which are not all in a completed state.
   9400 
   9401   2. A task has a parent with the property :ORDERED:, and there
   9402      are siblings prior to the current task with incomplete
   9403      status.
   9404 
   9405   3. The parent of the task is blocked because it has siblings that should
   9406      be done first, or is child of a block grandparent TODO entry."
   9407 
   9408   (if (not org-enforce-todo-dependencies)
   9409       t ; if locally turned off don't block
   9410     (catch 'dont-block
   9411       ;; If this is not a todo state change, or if this entry is already DONE,
   9412       ;; do not block
   9413       (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
   9414 		(member (plist-get change-plist :from)
   9415 			(cons 'done org-done-keywords))
   9416 		(member (plist-get change-plist :to)
   9417 			(cons 'todo org-not-done-keywords))
   9418 		(not (plist-get change-plist :to)))
   9419 	(throw 'dont-block t))
   9420       ;; If this task has children, and any are undone, it's blocked
   9421       (save-excursion
   9422 	(org-back-to-heading t)
   9423 	(let ((this-level (funcall outline-level)))
   9424 	  (outline-next-heading)
   9425 	  (let ((child-level (funcall outline-level)))
   9426 	    (while (and (not (eobp))
   9427 			(> child-level this-level))
   9428 	      ;; this todo has children, check whether they are all
   9429 	      ;; completed
   9430 	      (when (and (not (org-entry-is-done-p))
   9431 			 (org-entry-is-todo-p))
   9432 		(setq org-block-entry-blocking (org-get-heading))
   9433 		(throw 'dont-block nil))
   9434 	      (outline-next-heading)
   9435 	      (setq child-level (funcall outline-level))))))
   9436       ;; Otherwise, if the task's parent has the :ORDERED: property, and
   9437       ;; any previous siblings are undone, it's blocked
   9438       (save-excursion
   9439 	(org-back-to-heading t)
   9440 	(let* ((pos (point))
   9441 	       (parent-pos (and (org-up-heading-safe) (point)))
   9442 	       (case-fold-search nil))
   9443 	  (unless parent-pos (throw 'dont-block t)) ; no parent
   9444 	  (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
   9445 		     (forward-line 1)
   9446 		     (re-search-forward org-not-done-heading-regexp pos t))
   9447 	    (setq org-block-entry-blocking (match-string 0))
   9448 	    (throw 'dont-block nil))  ; block, there is an older sibling not done.
   9449 	  ;; Search further up the hierarchy, to see if an ancestor is blocked
   9450 	  (while t
   9451 	    (goto-char parent-pos)
   9452 	    (unless (looking-at org-not-done-heading-regexp)
   9453 	      (throw 'dont-block t))	; do not block, parent is not a TODO
   9454 	    (setq pos (point))
   9455 	    (setq parent-pos (and (org-up-heading-safe) (point)))
   9456 	    (unless parent-pos (throw 'dont-block t)) ; no parent
   9457 	    (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
   9458 		       (forward-line 1)
   9459 		       (re-search-forward org-not-done-heading-regexp pos t)
   9460 		       (setq org-block-entry-blocking (org-get-heading)))
   9461 	      (throw 'dont-block nil)))))))) ; block, older sibling not done.
   9462 
   9463 (defcustom org-track-ordered-property-with-tag nil
   9464   "Should the ORDERED property also be shown as a tag?
   9465 The ORDERED property decides if an entry should require subtasks to be
   9466 completed in sequence.  Since a property is not very visible, setting
   9467 this option means that toggling the ORDERED property with the command
   9468 `org-toggle-ordered-property' will also toggle a tag ORDERED.  That tag is
   9469 not relevant for the behavior, but it makes things more visible.
   9470 
   9471 Note that toggling the tag with tags commands will not change the property
   9472 and therefore not influence behavior!
   9473 
   9474 This can be t, meaning the tag ORDERED should be used.  It can also be a
   9475 string to select a different tag for this task."
   9476   :group 'org-todo
   9477   :type '(choice
   9478 	  (const :tag "No tracking" nil)
   9479 	  (const :tag "Track with ORDERED tag" t)
   9480 	  (string :tag "Use other tag")))
   9481 
   9482 (defun org-toggle-ordered-property ()
   9483   "Toggle the ORDERED property of the current entry.
   9484 For better visibility, you can track the value of this property with a tag.
   9485 See variable `org-track-ordered-property-with-tag'."
   9486   (interactive)
   9487   (let* ((t1 org-track-ordered-property-with-tag)
   9488 	 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
   9489     (save-excursion
   9490       (org-back-to-heading)
   9491       (if (org-entry-get nil "ORDERED")
   9492 	  (progn
   9493 	    (org-delete-property "ORDERED")
   9494 	    (and tag (org-toggle-tag tag 'off))
   9495 	    (message "Subtasks can be completed in arbitrary order"))
   9496 	(org-entry-put nil "ORDERED" "t")
   9497 	(and tag (org-toggle-tag tag 'on))
   9498 	(message "Subtasks must be completed in sequence")))))
   9499 
   9500 (defun org-block-todo-from-checkboxes (change-plist)
   9501   "Block turning an entry into a TODO, using checkboxes.
   9502 This checks whether the current task should be blocked from state
   9503 changes because there are unchecked boxes in this entry."
   9504   (if (not org-enforce-todo-checkbox-dependencies)
   9505       t ; if locally turned off don't block
   9506     (catch 'dont-block
   9507       ;; If this is not a todo state change, or if this entry is already DONE,
   9508       ;; do not block
   9509       (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
   9510 		(member (plist-get change-plist :from)
   9511 			(cons 'done org-done-keywords))
   9512 		(member (plist-get change-plist :to)
   9513 			(cons 'todo org-not-done-keywords))
   9514 		(not (plist-get change-plist :to)))
   9515 	(throw 'dont-block t))
   9516       ;; If this task has checkboxes that are not checked, it's blocked
   9517       (save-excursion
   9518 	(org-back-to-heading t)
   9519 	(let ((beg (point)) end)
   9520 	  (outline-next-heading)
   9521 	  (setq end (point))
   9522 	  (goto-char beg)
   9523 	  (when (org-list-search-forward
   9524 		 (concat (org-item-beginning-re)
   9525 			 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
   9526 			 "\\[[- ]\\]")
   9527 		 end t)
   9528 	    (when (boundp 'org-blocked-by-checkboxes)
   9529 	      (setq org-blocked-by-checkboxes t))
   9530 	    (throw 'dont-block nil))))
   9531       t))) ; do not block
   9532 
   9533 (defun org-entry-blocked-p ()
   9534   "Non-nil if entry at point is blocked."
   9535   (and (not (org-entry-get nil "NOBLOCKING"))
   9536        (member (org-entry-get nil "TODO") org-not-done-keywords)
   9537        (not (run-hook-with-args-until-failure
   9538 	     'org-blocker-hook
   9539 	     (list :type 'todo-state-change
   9540 		   :position (point)
   9541 		   :from 'todo
   9542 		   :to 'done)))))
   9543 
   9544 (defun org-update-statistics-cookies (all)
   9545   "Update the statistics cookie, either from TODO or from checkboxes.
   9546 This should be called with the cursor in a line with a statistics
   9547 cookie.  When called with a \\[universal-argument] prefix, update
   9548 all statistics cookies in the buffer."
   9549   (interactive "P")
   9550   (if all
   9551       (progn
   9552 	(org-update-checkbox-count 'all)
   9553 	(org-map-region 'org-update-parent-todo-statistics
   9554                         (point-min) (point-max)))
   9555     (if (not (org-at-heading-p))
   9556 	(org-update-checkbox-count)
   9557       (let ((pos (point-marker))
   9558 	    end l1 l2)
   9559 	(ignore-errors (org-back-to-heading t))
   9560 	(if (not (org-at-heading-p))
   9561 	    (org-update-checkbox-count)
   9562 	  (setq l1 (org-outline-level))
   9563 	  (setq end
   9564                 (save-excursion
   9565 		  (outline-next-heading)
   9566 		  (when (org-at-heading-p) (setq l2 (org-outline-level)))
   9567 		  (point)))
   9568 	  (if (and (save-excursion
   9569 		     (re-search-forward
   9570 		      "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
   9571 	           (not (save-excursion
   9572                           (re-search-forward
   9573 			   ":COOKIE_DATA:.*\\<todo\\>" end t))))
   9574 	      (org-update-checkbox-count)
   9575 	    (if (and l2 (> l2 l1))
   9576 		(progn
   9577 		  (goto-char end)
   9578 		  (org-update-parent-todo-statistics))
   9579 	      (goto-char pos)
   9580 	      (beginning-of-line 1)
   9581 	      (while (re-search-forward
   9582 		      "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
   9583                       (line-end-position) t)
   9584 		(replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
   9585 	(goto-char pos)
   9586 	(move-marker pos nil)))))
   9587 
   9588 (defvar org-entry-property-inherited-from) ;; defined below
   9589 (defun org-update-parent-todo-statistics ()
   9590   "Update any statistics cookie in the parent of the current headline.
   9591 When `org-hierarchical-todo-statistics' is nil, statistics will cover
   9592 the entire subtree and this will travel up the hierarchy and update
   9593 statistics everywhere."
   9594   (let* ((prop (save-excursion
   9595                  (org-up-heading-safe)
   9596 		 (org-entry-get nil "COOKIE_DATA" 'inherit)))
   9597 	 (recursive (or (not org-hierarchical-todo-statistics)
   9598 			(and prop (string-match "\\<recursive\\>" prop))))
   9599 	 (lim (or (and prop (marker-position org-entry-property-inherited-from))
   9600 		  0))
   9601 	 (first t)
   9602 	 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
   9603 	 level ltoggle l1 new ndel
   9604 	 (cnt-all 0) (cnt-done 0) is-percent kwd
   9605 	 checkbox-beg cookie-present)
   9606     (catch 'exit
   9607       (save-excursion
   9608 	(beginning-of-line 1)
   9609 	(setq ltoggle (funcall outline-level))
   9610 	;; Three situations are to consider:
   9611 
   9612 	;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
   9613 	;;    to the top-level ancestor on the headline;
   9614 
   9615 	;; 2. If parent has "recursive" property, repeat up to the
   9616 	;;    headline setting that property, taking inheritance into
   9617 	;;    account;
   9618 
   9619 	;; 3. Else, move up to direct parent and proceed only once.
   9620 	(while (and (setq level (org-up-heading-safe))
   9621 		    (or recursive first)
   9622 		    (>= (point) lim))
   9623 	  (setq first nil cookie-present nil)
   9624 	  (unless (and level
   9625 		       (not (string-match
   9626 			   "\\<checkbox\\>"
   9627 			   (downcase (or (org-entry-get nil "COOKIE_DATA")
   9628 					 "")))))
   9629 	    (throw 'exit nil))
   9630           (while (re-search-forward box-re (line-end-position) t)
   9631 	    (setq cnt-all 0 cnt-done 0 cookie-present t)
   9632 	    (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
   9633 	    (save-match-data
   9634 	      (unless (outline-next-heading) (throw 'exit nil))
   9635 	      (while (and (looking-at org-complex-heading-regexp)
   9636 	    		  (> (setq l1 (length (match-string 1))) level))
   9637 	    	(setq kwd (and (or recursive (= l1 ltoggle))
   9638 	    		       (match-string 2)))
   9639 	    	(if (or (eq org-provide-todo-statistics 'all-headlines)
   9640 			(and (eq org-provide-todo-statistics t)
   9641 			     (or (member kwd org-done-keywords)))
   9642 	    		(and (listp org-provide-todo-statistics)
   9643 			     (stringp (car org-provide-todo-statistics))
   9644 	    		     (or (member kwd org-provide-todo-statistics)
   9645 				 (member kwd org-done-keywords)))
   9646 			(and (listp org-provide-todo-statistics)
   9647 			     (listp (car org-provide-todo-statistics))
   9648 			     (or (member kwd (car org-provide-todo-statistics))
   9649 				 (and (member kwd org-done-keywords)
   9650 				      (member kwd (cadr org-provide-todo-statistics))))))
   9651 	    	    (setq cnt-all (1+ cnt-all))
   9652 		  (and (eq org-provide-todo-statistics t)
   9653 		       kwd
   9654 		       (setq cnt-all (1+ cnt-all))))
   9655 		(when (or (and (member org-provide-todo-statistics '(t all-headlines))
   9656 			       (member kwd org-done-keywords))
   9657 			  (and (listp org-provide-todo-statistics)
   9658 			       (listp (car org-provide-todo-statistics))
   9659 			       (member kwd org-done-keywords)
   9660 			       (member kwd (cadr org-provide-todo-statistics)))
   9661 			  (and (listp org-provide-todo-statistics)
   9662 			       (stringp (car org-provide-todo-statistics))
   9663 			       (member kwd org-done-keywords)))
   9664 		  (setq cnt-done (1+ cnt-done)))
   9665 	    	(outline-next-heading)))
   9666 	    (setq new
   9667 	    	  (if is-percent
   9668 		      (format "[%d%%]" (floor (* 100.0 cnt-done)
   9669 					      (max 1 cnt-all)))
   9670 	    	    (format "[%d/%d]" cnt-done cnt-all))
   9671 	    	  ndel (- (match-end 0) checkbox-beg))
   9672 	    (goto-char checkbox-beg)
   9673 	    (insert new)
   9674 	    (delete-region (point) (+ (point) ndel))
   9675 	    (when org-auto-align-tags (org-fix-tags-on-the-fly)))
   9676 	  (when cookie-present
   9677 	    (run-hook-with-args 'org-after-todo-statistics-hook
   9678 				cnt-done (- cnt-all cnt-done))))))
   9679     (run-hooks 'org-todo-statistics-hook)))
   9680 
   9681 (defvar org-after-todo-statistics-hook nil
   9682   "Hook that is called after a TODO statistics cookie has been updated.
   9683 Each function is called with two arguments: the number of not-done entries
   9684 and the number of done entries.
   9685 
   9686 For example, the following function, when added to this hook, will switch
   9687 an entry to DONE when all children are done, and back to TODO when new
   9688 entries are set to a TODO status.  Note that this hook is only called
   9689 when there is a statistics cookie in the headline!
   9690 
   9691  (defun org-summary-todo (n-done n-not-done)
   9692    \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
   9693    (let (org-log-done org-log-states)   ; turn off logging
   9694      (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))")
   9695 
   9696 (defvar org-todo-statistics-hook nil
   9697   "Hook that is run whenever Org thinks TODO statistics should be updated.
   9698 This hook runs even if there is no statistics cookie present, in which case
   9699 `org-after-todo-statistics-hook' would not run.")
   9700 
   9701 (defun org-todo-trigger-tag-changes (state)
   9702   "Apply the changes defined in `org-todo-state-tags-triggers'."
   9703   (let ((l org-todo-state-tags-triggers)
   9704 	changes)
   9705     (when (or (not state) (equal state ""))
   9706       (setq changes (append changes (cdr (assoc "" l)))))
   9707     (when (and (stringp state) (> (length state) 0))
   9708       (setq changes (append changes (cdr (assoc state l)))))
   9709     (when (member state org-not-done-keywords)
   9710       (setq changes (append changes (cdr (assq 'todo l)))))
   9711     (when (member state org-done-keywords)
   9712       (setq changes (append changes (cdr (assq 'done l)))))
   9713     (dolist (c changes)
   9714       (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
   9715 
   9716 (defun org-local-logging (value)
   9717   "Get logging settings from a property VALUE."
   9718   ;; Directly set the variables, they are already local.
   9719   (setq org-log-done nil
   9720         org-log-repeat nil
   9721         org-todo-log-states nil)
   9722   (dolist (w (split-string value))
   9723     (let (a)
   9724       (cond
   9725        ((setq a (assoc w org-startup-options))
   9726         (and (member (nth 1 a) '(org-log-done org-log-repeat))
   9727              (set (nth 1 a) (nth 2 a))))
   9728        ((setq a (org-extract-log-state-settings w))
   9729         (and (member (car a) org-todo-keywords-1)
   9730              (push a org-todo-log-states)))))))
   9731 
   9732 (defun org-get-todo-sequence-head (kwd)
   9733   "Return the head of the TODO sequence to which KWD belongs.
   9734 If KWD is not set, check if there is a text property remembering the
   9735 right sequence."
   9736   (let (p)
   9737     (cond
   9738      ((not kwd)
   9739       (or (get-text-property (line-beginning-position) 'org-todo-head)
   9740 	  (progn
   9741             (setq p (next-single-property-change (line-beginning-position)
   9742                                                  'org-todo-head
   9743                                                  nil (line-end-position)))
   9744 	    (get-text-property p 'org-todo-head))))
   9745      ((not (member kwd org-todo-keywords-1))
   9746       (car org-todo-keywords-1))
   9747      (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
   9748 
   9749 (defun org-fast-todo-selection (&optional current-state)
   9750   "Fast TODO keyword selection with single keys.
   9751 Returns the new TODO keyword, or nil if no state change should occur.
   9752 When CURRENT-STATE is given and selection letters are not unique globally,
   9753 prefer a state in the current sequence over on in another sequence."
   9754   (let* ((fulltable org-todo-key-alist)
   9755 	 (head (org-get-todo-sequence-head current-state))
   9756 	 (done-keywords org-done-keywords) ;; needed for the faces.
   9757 	 (maxlen (apply 'max (mapcar
   9758 			      (lambda (x)
   9759 				(if (stringp (car x)) (string-width (car x)) 0))
   9760 			      fulltable)))
   9761 	 (expert (equal org-use-fast-todo-selection 'expert))
   9762 	 (prompt "")
   9763 	 (fwidth (+ maxlen 3 1 3))
   9764 	 (ncol (/ (- (window-width) 4) fwidth))
   9765 	 tg cnt e c tbl subtable
   9766 	 groups ingroup in-current-sequence)
   9767     (save-excursion
   9768       (save-window-excursion
   9769 	(if expert
   9770 	    (set-buffer (get-buffer-create " *Org todo*"))
   9771 	  (delete-other-windows)
   9772 	  (set-window-buffer (split-window-vertically) (get-buffer-create " *Org todo*"))
   9773 	  (org-switch-to-buffer-other-window " *Org todo*"))
   9774 	(erase-buffer)
   9775 	(setq-local org-done-keywords done-keywords)
   9776 	(setq tbl fulltable cnt 0)
   9777 	(while (setq e (pop tbl))
   9778 	  (cond
   9779 	   ((equal e '(:startgroup))
   9780 	    (push '() groups) (setq ingroup t)
   9781 	    (unless (= cnt 0)
   9782 	      (setq cnt 0)
   9783 	      (insert "\n"))
   9784 	    (setq prompt (concat prompt "{"))
   9785 	    (insert "{ "))
   9786 	   ((equal e '(:endgroup))
   9787 	    (setq ingroup nil cnt 0 in-current-sequence nil)
   9788 	    (setq prompt (concat prompt "}"))
   9789 	    (insert "}\n"))
   9790 	   ((equal e '(:newline))
   9791 	    (unless (= cnt 0)
   9792 	      (setq cnt 0)
   9793 	      (insert "\n")
   9794 	      (setq e (car tbl))
   9795 	      (while (equal (car tbl) '(:newline))
   9796 		(insert "\n")
   9797 		(setq tbl (cdr tbl)))))
   9798 	   (t
   9799 	    (setq tg (car e) c (cdr e))
   9800 	    (if (equal tg head) (setq in-current-sequence t))
   9801 	    (when ingroup (push tg (car groups)))
   9802 	    (when in-current-sequence (push e subtable))
   9803 	    (setq tg (org-add-props tg nil 'face
   9804 				    (org-get-todo-face tg)))
   9805 	    (when (and (= cnt 0) (not ingroup)) (insert "  "))
   9806 	    (setq prompt (concat prompt "[" (char-to-string c) "] " tg " "))
   9807 	    (insert "[" c "] " tg (make-string
   9808 				   (- fwidth 4 (length tg)) ?\ ))
   9809 	    (when (and (= (setq cnt (1+ cnt)) ncol)
   9810 		       ;; Avoid lines with just a closing delimiter.
   9811 		       (not (equal (car tbl) '(:endgroup))))
   9812 	      (insert "\n")
   9813 	      (when ingroup (insert "  "))
   9814 	      (setq cnt 0)))))
   9815 	(insert "\n")
   9816 	(goto-char (point-min))
   9817 	(unless expert (org-fit-window-to-buffer))
   9818 	(message (concat "[a-z..]:Set [SPC]:clear"
   9819 			 (if expert (concat "\n" prompt) "")))
   9820 	(setq c (let ((inhibit-quit t)) (read-char-exclusive)))
   9821 	(setq subtable (nreverse subtable))
   9822 	(cond
   9823 	 ((or (= c ?\C-g)
   9824 	      (and (= c ?q) (not (rassoc c fulltable))))
   9825 	  (setq quit-flag t))
   9826 	 ((= c ?\ ) nil)
   9827 	 ((setq e (or (rassoc c subtable) (rassoc c fulltable))
   9828 		tg (car e))
   9829 	  tg)
   9830 	 (t (setq quit-flag t)))))))
   9831 
   9832 (defun org-entry-is-todo-p ()
   9833   (member (org-get-todo-state) org-not-done-keywords))
   9834 
   9835 (defun org-entry-is-done-p ()
   9836   (member (org-get-todo-state) org-done-keywords))
   9837 
   9838 (defun org-get-todo-state ()
   9839   "Return the TODO keyword of the current subtree."
   9840   (save-excursion
   9841     (org-back-to-heading t)
   9842     (and (let ((case-fold-search nil))
   9843            (looking-at org-todo-line-regexp))
   9844 	 (match-end 2)
   9845 	 (match-string 2))))
   9846 
   9847 (defun org-at-date-range-p (&optional inactive-ok)
   9848   "Non-nil if point is inside a date range.
   9849 
   9850 When optional argument INACTIVE-OK is non-nil, also consider
   9851 inactive time ranges.
   9852 
   9853 When this function returns a non-nil value, match data is set
   9854 according to `org-tr-regexp-both' or `org-tr-regexp', depending
   9855 on INACTIVE-OK."
   9856   (interactive)
   9857   (save-excursion
   9858     (catch 'exit
   9859       (let ((pos (point)))
   9860 	(skip-chars-backward "^[<\r\n")
   9861 	(skip-chars-backward "<[")
   9862 	(and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
   9863 	     (>= (match-end 0) pos)
   9864 	     (throw 'exit t))
   9865 	(skip-chars-backward "^<[\r\n")
   9866 	(skip-chars-backward "<[")
   9867 	(and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
   9868 	     (>= (match-end 0) pos)
   9869 	     (throw 'exit t)))
   9870       nil)))
   9871 
   9872 (defun org-get-repeat (&optional timestamp)
   9873   "Check if there is a time-stamp with repeater in this entry.
   9874 
   9875 Return the repeater, as a string, or nil.  Also return nil when
   9876 this function is called before first heading.
   9877 
   9878 When optional argument TIMESTAMP is a string, extract the
   9879 repeater from there instead."
   9880   (save-match-data
   9881     (cond
   9882      (timestamp
   9883       (and (string-match org-repeat-re timestamp)
   9884 	   (match-string-no-properties 1 timestamp)))
   9885      ((org-before-first-heading-p) nil)
   9886      (t
   9887       (save-excursion
   9888 	(org-back-to-heading t)
   9889 	(let ((end (org-entry-end-position)))
   9890 	  (catch :repeat
   9891 	    (while (re-search-forward org-repeat-re end t)
   9892 	      (when (save-match-data (org-at-timestamp-p 'agenda))
   9893 		(throw :repeat (match-string-no-properties 1)))))))))))
   9894 
   9895 (defvar org-last-changed-timestamp)
   9896 (defvar org-last-inserted-timestamp)
   9897 (defvar org-log-post-message)
   9898 (defvar org-log-note-purpose)
   9899 (defvar org-log-note-how nil)
   9900 (defvar org-log-note-extra)
   9901 (defvar org-log-setup nil)
   9902 (defun org-auto-repeat-maybe (done-word)
   9903   "Check if the current headline contains a repeated time-stamp.
   9904 
   9905 If yes, set TODO state back to what it was and change the base date
   9906 of repeating deadline/scheduled time stamps to new date.
   9907 
   9908 This function is run automatically after each state change to a DONE state."
   9909   (let* ((repeat (org-get-repeat))
   9910 	 (aa (assoc org-last-state org-todo-kwd-alist))
   9911 	 (interpret (nth 1 aa))
   9912 	 (head (nth 2 aa))
   9913 	 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
   9914 	 (msg "Entry repeats: ")
   9915 	 (org-log-done nil)
   9916 	 (org-todo-log-states nil)
   9917 	 (end (copy-marker (org-entry-end-position))))
   9918     (when (and repeat (not (= 0 (string-to-number (substring repeat 1)))))
   9919       (when (eq org-log-repeat t) (setq org-log-repeat 'state))
   9920       (let ((to-state
   9921              (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
   9922 		 (and (stringp org-todo-repeat-to-state)
   9923 		      org-todo-repeat-to-state)
   9924 		 (and org-todo-repeat-to-state org-last-state))))
   9925 	(org-todo (cond ((and to-state (member to-state org-todo-keywords-1))
   9926 			 to-state)
   9927 			((eq interpret 'type) org-last-state)
   9928 			(head)
   9929 			(t 'none))))
   9930       (org-back-to-heading t)
   9931       (org-add-planning-info nil nil 'closed)
   9932       ;; When `org-log-repeat' is non-nil or entry contains
   9933       ;; a clock, set LAST_REPEAT property.
   9934       (when (or org-log-repeat
   9935 		(catch :clock
   9936 		  (save-excursion
   9937 		    (while (re-search-forward org-clock-line-re end t)
   9938 		      (when (org-at-clock-log-p) (throw :clock t))))))
   9939 	(org-entry-put nil "LAST_REPEAT" (format-time-string
   9940 					  (org-time-stamp-format t t)
   9941                                           (org-current-effective-time))))
   9942       (when org-log-repeat
   9943 	(if org-log-setup
   9944 	    ;; We are already setup for some record.
   9945 	    (when (eq org-log-repeat 'note)
   9946 	      ;; Make sure we take a note, not only a time stamp.
   9947 	      (setq org-log-note-how 'note))
   9948 	  ;; Set up for taking a record.
   9949 	  (org-add-log-setup 'state
   9950 			     (or done-word (car org-done-keywords))
   9951 			     org-last-state
   9952 			     org-log-repeat)))
   9953       ;; Time-stamps without a repeater are usually skipped.  However,
   9954       ;; a SCHEDULED time-stamp without one is removed, as they are no
   9955       ;; longer relevant.
   9956       (save-excursion
   9957 	(let ((scheduled (org-entry-get (point) "SCHEDULED")))
   9958 	  (when (and scheduled (not (string-match-p org-repeat-re scheduled)))
   9959 	    (org-remove-timestamp-with-keyword org-scheduled-string))))
   9960       ;; Update every time-stamp with a repeater in the entry.
   9961       (let ((planning-re (regexp-opt
   9962 			  (list org-scheduled-string org-deadline-string))))
   9963 	(while (re-search-forward org-repeat-re end t)
   9964 	  (let* ((ts (match-string 0))
   9965 		 (type (if (not (org-at-planning-p)) "Plain:"
   9966 			 (save-excursion
   9967 			   (re-search-backward
   9968 			    planning-re (line-beginning-position) t)
   9969 			   (match-string 0)))))
   9970 	    (when (and (org-at-timestamp-p 'agenda)
   9971 		       (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
   9972 	      (let ((n (string-to-number (match-string 2 ts)))
   9973 		    (what (match-string 3 ts)))
   9974 		(when (equal what "w") (setq n (* n 7) what "d"))
   9975 		(when (and (equal what "h")
   9976 			   (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
   9977 						ts)))
   9978 		  (user-error
   9979 		   "Cannot repeat in %d hour(s) because no hour has been set"
   9980 		   n))
   9981 		;; Preparation, see if we need to modify the start
   9982 		;; date for the change.
   9983 		(when (match-end 1)
   9984 		  (let ((time (save-match-data (org-time-string-to-time ts)))
   9985 			(repeater-type (match-string 1 ts)))
   9986 		    (cond
   9987 		     ((equal "." repeater-type)
   9988 		      ;; Shift starting date to today, or now if
   9989 		      ;; repeater is by hours.
   9990 		      (if (equal what "h")
   9991 			  (org-timestamp-change
   9992 			   (floor (- (org-time-stamp-to-now ts t)) 60) 'minute)
   9993 			(org-timestamp-change
   9994 			 (- (org-today) (time-to-days time)) 'day)))
   9995 		     ((equal "+" repeater-type)
   9996 		      (let ((nshiftmax 10)
   9997 			    (nshift 0))
   9998 			(while (or (= nshift 0)
   9999 				   (not (time-less-p nil time)))
  10000 			  (when (= nshiftmax (cl-incf nshift))
  10001 			    (or (y-or-n-p
  10002 				 (format "%d repeater intervals were not \
  10003 enough to shift date past today.  Continue? "
  10004 					 nshift))
  10005 				(user-error "Abort")))
  10006 			  (org-timestamp-change n (cdr (assoc what whata)))
  10007 			  (org-in-regexp org-ts-regexp3)
  10008 			  (setq ts (match-string 1))
  10009 			  (setq time
  10010 				(save-match-data
  10011 				  (org-time-string-to-time ts)))))
  10012 		      (org-timestamp-change (- n) (cdr (assoc what whata)))
  10013 		      ;; Rematch, so that we have everything in place
  10014 		      ;; for the real shift.
  10015 		      (org-in-regexp org-ts-regexp3)
  10016 		      (setq ts (match-string 1))
  10017 		      (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
  10018 				    ts)))))
  10019 		(save-excursion
  10020 		  (org-timestamp-change n (cdr (assoc what whata)) nil t))
  10021 		(setq msg
  10022 		      (concat msg type " " org-last-changed-timestamp " ")))))))
  10023       (run-hooks 'org-todo-repeat-hook)
  10024       (setq org-log-post-message msg)
  10025       (message msg))))
  10026 
  10027 (defun org-show-todo-tree (arg)
  10028   "Make a compact tree which shows all headlines marked with TODO.
  10029 The tree will show the lines where the regexp matches, and all higher
  10030 headlines above the match.
  10031 With a `\\[universal-argument]' prefix, prompt for a regexp to match.
  10032 With a numeric prefix N, construct a sparse tree for the Nth element
  10033 of `org-todo-keywords-1'."
  10034   (interactive "P")
  10035   (let ((case-fold-search nil)
  10036 	(kwd-re
  10037 	 (cond ((null arg) (concat org-not-done-regexp "\\s-"))
  10038 	       ((equal arg '(4))
  10039 		(let ((kwd
  10040 		       (completing-read "Keyword (or KWD1|KWD2|...): "
  10041 					(mapcar #'list org-todo-keywords-1))))
  10042 		  (concat "\\("
  10043 			  (mapconcat 'identity (org-split-string kwd "|") "\\|")
  10044 			  "\\)\\>")))
  10045 	       ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
  10046 		(regexp-quote (nth (1- (prefix-numeric-value arg))
  10047 				   org-todo-keywords-1)))
  10048 	       (t (user-error "Invalid prefix argument: %s" arg)))))
  10049     (message "%d TODO entries found"
  10050 	     (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
  10051 
  10052 (defun org--deadline-or-schedule (arg type time)
  10053   "Insert DEADLINE or SCHEDULE information in current entry.
  10054 TYPE is either `deadline' or `scheduled'.  See `org-deadline' or
  10055 `org-schedule' for information about ARG and TIME arguments."
  10056   (org-fold-core-ignore-modifications
  10057     (let* ((deadline? (eq type 'deadline))
  10058 	   (keyword (if deadline? org-deadline-string org-scheduled-string))
  10059 	   (log (if deadline? org-log-redeadline org-log-reschedule))
  10060 	   (old-date (org-entry-get nil (if deadline? "DEADLINE" "SCHEDULED")))
  10061 	   (old-date-time (and old-date (org-time-string-to-time old-date)))
  10062 	   ;; Save repeater cookie from either TIME or current scheduled
  10063 	   ;; time stamp.  We are going to insert it back at the end of
  10064 	   ;; the process.
  10065 	   (repeater (or (and (org-string-nw-p time)
  10066 			      ;; We use `org-ts-regexp-both' because we
  10067 			      ;; need to tell the difference between a
  10068 			      ;; real repeater and a time delta, e.g.
  10069 			      ;; "+2d".
  10070                               (string-match-p org-ts-regexp-both time)
  10071                               (string-match "\\([.+-]+[0-9]+[hdwmy]\
  10072 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  10073 					    time)
  10074 			      (match-string 1 time))
  10075 		         (and (org-string-nw-p old-date)
  10076 			      (string-match "\\([.+-]+[0-9]+[hdwmy]\
  10077 \\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\)"
  10078 					    old-date)
  10079 			      (match-string 1 old-date)))))
  10080       (pcase arg
  10081         (`(4)
  10082          (if (not old-date)
  10083 	     (message (if deadline? "Entry had no deadline to remove"
  10084 		        "Entry was not scheduled"))
  10085 	   (when (and old-date log)
  10086 	     (org-add-log-setup (if deadline? 'deldeadline 'delschedule)
  10087 			     nil old-date log))
  10088 	   (org-remove-timestamp-with-keyword keyword)
  10089 	   (message (if deadline? "Entry no longer has a deadline."
  10090 		      "Entry is no longer scheduled."))))
  10091         (`(16)
  10092          (save-excursion
  10093 	   (org-back-to-heading t)
  10094 	   (let ((regexp (if deadline? org-deadline-time-regexp
  10095 			   org-scheduled-time-regexp)))
  10096 	     (if (not (re-search-forward regexp (line-end-position 2) t))
  10097 	         (user-error (if deadline? "No deadline information to update"
  10098 			       "No scheduled information to update"))
  10099 	       (let* ((rpl0 (match-string 1))
  10100 		      (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))
  10101 		      (msg (if deadline? "Warn starting from" "Delay until")))
  10102 	         (replace-match
  10103 		  (concat keyword
  10104 			  " <" rpl
  10105 			  (format " -%dd"
  10106 				  (abs (- (time-to-days
  10107 					   (save-match-data
  10108 					     (org-read-date
  10109 					      nil t nil msg old-date-time)))
  10110 					  (time-to-days old-date-time))))
  10111 			  ">") t t))))))
  10112         (_
  10113          (org-add-planning-info type time 'closed)
  10114          (when (and old-date
  10115 		    log
  10116 		    (not (equal old-date org-last-inserted-timestamp)))
  10117 	   (org-add-log-setup (if deadline? 'redeadline 'reschedule)
  10118 			      org-last-inserted-timestamp
  10119 			      old-date
  10120 			      log))
  10121          (when repeater
  10122 	   (save-excursion
  10123 	     (org-back-to-heading t)
  10124 	     (when (re-search-forward
  10125 		    (concat keyword " " org-last-inserted-timestamp)
  10126 		    (line-end-position 2)
  10127 		    t)
  10128 	       (goto-char (1- (match-end 0)))
  10129 	       (insert-and-inherit " " repeater)
  10130 	       (setq org-last-inserted-timestamp
  10131 		     (concat (substring org-last-inserted-timestamp 0 -1)
  10132 			     " " repeater
  10133 			     (substring org-last-inserted-timestamp -1))))))
  10134          (message (if deadline? "Deadline on %s" "Scheduled to %s")
  10135 		  org-last-inserted-timestamp))))))
  10136 
  10137 (defun org-deadline (arg &optional time)
  10138   "Insert a \"DEADLINE:\" string with a timestamp to make a deadline.
  10139 
  10140 When called interactively, this command pops up the Emacs calendar to let
  10141 the user select a date.
  10142 
  10143 With one universal prefix argument, remove any deadline from the item.
  10144 With two universal prefix arguments, prompt for a warning delay.
  10145 With argument TIME, set the deadline at the corresponding date.  TIME
  10146 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  10147   (interactive "P")
  10148   (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10149       (org-map-entries
  10150        (lambda () (org--deadline-or-schedule arg 'deadline time))
  10151        nil
  10152        (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10153 	   'region-start-level
  10154 	 'region)
  10155        (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  10156     (org--deadline-or-schedule arg 'deadline time)))
  10157 
  10158 (defun org-schedule (arg &optional time)
  10159   "Insert a \"SCHEDULED:\" string with a timestamp to schedule an item.
  10160 
  10161 When called interactively, this command pops up the Emacs calendar to let
  10162 the user select a date.
  10163 
  10164 With one universal prefix argument, remove any scheduling date from the item.
  10165 With two universal prefix arguments, prompt for a delay cookie.
  10166 With argument TIME, scheduled at the corresponding date.  TIME can
  10167 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
  10168   (interactive "P")
  10169   (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
  10170       (org-map-entries
  10171        (lambda () (org--deadline-or-schedule arg 'scheduled time))
  10172        nil
  10173        (if (eq org-loop-over-headlines-in-active-region 'start-level)
  10174 	   'region-start-level
  10175 	 'region)
  10176        (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))
  10177     (org--deadline-or-schedule arg 'scheduled time)))
  10178 
  10179 (defun org-get-scheduled-time (pom &optional inherit)
  10180   "Get the scheduled time as a time tuple, of a format suitable
  10181 for calling org-schedule with, or if there is no scheduling,
  10182 returns nil."
  10183   (let ((time (org-entry-get pom "SCHEDULED" inherit)))
  10184     (when time
  10185       (org-time-string-to-time time))))
  10186 
  10187 (defun org-get-deadline-time (pom &optional inherit)
  10188   "Get the deadline as a time tuple, of a format suitable for
  10189 calling org-deadline with, or if there is no scheduling, returns
  10190 nil."
  10191   (let ((time (org-entry-get pom "DEADLINE" inherit)))
  10192     (when time
  10193       (org-time-string-to-time time))))
  10194 
  10195 (defun org-remove-timestamp-with-keyword (keyword)
  10196   "Remove all time stamps with KEYWORD in the current entry."
  10197   (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
  10198 	beg)
  10199     (save-excursion
  10200       (org-back-to-heading t)
  10201       (setq beg (point))
  10202       (outline-next-heading)
  10203       (while (re-search-backward re beg t)
  10204 	(replace-match "")
  10205         (if (and (string-match "\\S-" (buffer-substring (line-beginning-position) (point)))
  10206 		 (equal (char-before) ?\ ))
  10207 	    (backward-delete-char 1)
  10208 	  (when (string-match "^[ \t]*$" (buffer-substring
  10209                                           (line-beginning-position) (line-end-position)))
  10210             (delete-region (line-beginning-position)
  10211                            (min (point-max) (1+ (line-end-position))))))))))
  10212 
  10213 (defvar org-time-was-given) ; dynamically scoped parameter
  10214 (defvar org-end-time-was-given) ; dynamically scoped parameter
  10215 
  10216 (defun org-at-planning-p ()
  10217   "Non-nil when point is on a planning info line."
  10218   ;; This is as accurate and faster than `org-element-at-point' since
  10219   ;; planning info location is fixed in the section.
  10220   (or (let ((cached (org-element-at-point nil 'cached)))
  10221         (and cached
  10222              (eq 'planning (org-element-type cached))))
  10223       (org-with-wide-buffer
  10224        (beginning-of-line)
  10225        (and (looking-at-p org-planning-line-re)
  10226 	    (eq (point)
  10227 	        (ignore-errors
  10228 	          (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
  10229 		      (org-back-to-heading t)
  10230 		    (org-with-limited-levels (org-back-to-heading t)))
  10231 	          (line-beginning-position 2)))))))
  10232 
  10233 (defun org-add-planning-info (what &optional time &rest remove)
  10234   "Insert new timestamp with keyword in the planning line.
  10235 WHAT indicates what kind of time stamp to add.  It is a symbol
  10236 among `closed', `deadline', `scheduled' and nil.  TIME indicates
  10237 the time to use.  If none is given, the user is prompted for
  10238 a date.  REMOVE indicates what kind of entries to remove.  An old
  10239 WHAT entry will also be removed."
  10240   (org-fold-core-ignore-modifications
  10241     (let (org-time-was-given org-end-time-was-given default-time default-input)
  10242       (when (and (memq what '(scheduled deadline))
  10243 	         (or (not time)
  10244 		     (and (stringp time)
  10245 			  (string-match "^[-+]+[0-9]" time))))
  10246         ;; Try to get a default date/time from existing timestamp
  10247         (save-excursion
  10248 	  (org-back-to-heading t)
  10249 	  (let ((end (save-excursion (outline-next-heading) (point))) ts)
  10250 	    (when (re-search-forward (if (eq what 'scheduled)
  10251 				         org-scheduled-time-regexp
  10252 				       org-deadline-time-regexp)
  10253 				     end t)
  10254 	      (setq ts (match-string 1)
  10255 		    default-time (org-time-string-to-time ts)
  10256 		    default-input (and ts (org-get-compact-tod ts)))))))
  10257       (when what
  10258         (setq time
  10259 	      (if (stringp time)
  10260 		  ;; This is a string (relative or absolute), set
  10261 		  ;; proper date.
  10262 		  (org-encode-time
  10263 		   (org-read-date-analyze
  10264 		    time default-time (decode-time default-time)))
  10265 	        ;; If necessary, get the time from the user
  10266 	        (or time (org-read-date nil 'to-time nil
  10267 				     (cl-case what
  10268 				       (deadline "DEADLINE")
  10269 				       (scheduled "SCHEDULED")
  10270 				       (otherwise nil))
  10271 				     default-time default-input)))))
  10272       (org-with-wide-buffer
  10273        (org-back-to-heading t)
  10274        (let ((planning? (save-excursion
  10275 			  (forward-line)
  10276 			  (looking-at-p org-planning-line-re))))
  10277          (cond
  10278 	  (planning?
  10279 	   (forward-line)
  10280 	   ;; Move to current indentation.
  10281 	   (skip-chars-forward " \t")
  10282 	   ;; Check if we have to remove something.
  10283 	   (dolist (type (if what (cons what remove) remove))
  10284 	     (save-excursion
  10285 	       (when (re-search-forward
  10286 		      (cl-case type
  10287 		        (closed org-closed-time-regexp)
  10288 		        (deadline org-deadline-time-regexp)
  10289 		        (scheduled org-scheduled-time-regexp)
  10290 		        (otherwise (error "Invalid planning type: %s" type)))
  10291 		      (line-end-position)
  10292 		      t)
  10293 	         ;; Delete until next keyword or end of line.
  10294 	         (delete-region
  10295 		  (match-beginning 0)
  10296 		  (if (re-search-forward org-keyword-time-not-clock-regexp
  10297 				         (line-end-position)
  10298 				         t)
  10299 		      (match-beginning 0)
  10300 		    (line-end-position))))))
  10301 	   ;; If there is nothing more to add and no more keyword is
  10302 	   ;; left, remove the line completely.
  10303 	   (if (and (looking-at-p "[ \t]*$") (not what))
  10304 	       (delete-region (line-end-position 0)
  10305 			      (line-end-position))
  10306 	     ;; If we removed last keyword, do not leave trailing white
  10307 	     ;; space at the end of line.
  10308 	     (let ((p (point)))
  10309 	       (save-excursion
  10310 	         (end-of-line)
  10311 	         (unless (= (skip-chars-backward " \t" p) 0)
  10312 		   (delete-region (point) (line-end-position)))))))
  10313 	  (what
  10314 	   (end-of-line)
  10315 	   (insert-and-inherit "\n")
  10316 	   (when org-adapt-indentation
  10317 	     (indent-to-column (1+ (org-outline-level)))))
  10318 	  (t nil)))
  10319        (when what
  10320          ;; Insert planning keyword.
  10321          (insert-and-inherit (cl-case what
  10322 		               (closed org-closed-string)
  10323 		               (deadline org-deadline-string)
  10324 		               (scheduled org-scheduled-string)
  10325 		               (otherwise (error "Invalid planning type: %s" what)))
  10326 	                     " ")
  10327          ;; Insert associated timestamp.
  10328          (let ((ts (org-insert-time-stamp
  10329 		    time
  10330 		    (or org-time-was-given
  10331 		        (and (eq what 'closed) org-log-done-with-time))
  10332 		    (eq what 'closed)
  10333 		    nil nil (list org-end-time-was-given))))
  10334 	   (unless (eolp) (insert " "))
  10335 	   ts))))))
  10336 
  10337 (defvar org-log-note-marker (make-marker)
  10338   "Marker pointing at the entry where the note is to be inserted.")
  10339 (defvar org-log-note-purpose nil)
  10340 (defvar org-log-note-state nil)
  10341 (defvar org-log-note-previous-state nil)
  10342 (defvar org-log-note-extra nil)
  10343 (defvar org-log-note-window-configuration nil)
  10344 (defvar org-log-note-return-to (make-marker))
  10345 (defvar org-log-note-effective-time nil
  10346   "Remembered current time.
  10347 So that dynamically scoped `org-extend-today-until' affects
  10348 timestamps in state change log.")
  10349 (defvar org-log-note-this-command
  10350   "`this-command' when `org-add-log-setup' is called.")
  10351 (defvar org-log-note-recursion-depth
  10352   "`recursion-depth' when `org-add-log-setup' is called.")
  10353 
  10354 (defvar org-log-post-message nil
  10355   "Message to be displayed after a log note has been stored.
  10356 The auto-repeater uses this.")
  10357 
  10358 (defun org-add-note ()
  10359   "Add a note to the current entry.
  10360 This is done in the same way as adding a state change note."
  10361   (interactive)
  10362   (org-add-log-setup 'note))
  10363 
  10364 (defun org-log-beginning (&optional create)
  10365   "Return expected start of log notes in current entry.
  10366 When optional argument CREATE is non-nil, the function creates
  10367 a drawer to store notes, if necessary.  Returned position ignores
  10368 narrowing."
  10369   (org-with-wide-buffer
  10370    (let ((drawer (org-log-into-drawer)))
  10371      (cond
  10372       (drawer
  10373        (org-end-of-meta-data)
  10374        (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
  10375 	     (end (if (org-at-heading-p) (point)
  10376 		    (save-excursion (outline-next-heading) (point))))
  10377 	     (case-fold-search t))
  10378 	 (catch 'exit
  10379 	   ;; Try to find existing drawer.
  10380 	   (while (re-search-forward regexp end t)
  10381 	     (let ((element (org-element-at-point)))
  10382 	       (when (eq (org-element-type element) 'drawer)
  10383 		 (let ((cend  (org-element-property :contents-end element)))
  10384 		   (when (and (not org-log-states-order-reversed) cend)
  10385 		     (goto-char cend)))
  10386 		 (throw 'exit nil))))
  10387 	   ;; No drawer found.  Create one, if permitted.
  10388 	   (when create
  10389              ;; Unless current heading is the last heading in buffer
  10390              ;; and does not have a newline, `org-end-of-meta-data'
  10391              ;; should move us somewhere below the heading.
  10392              ;; Avoid situation when we insert drawer right before
  10393              ;; first "*".  Otherwise, if the previous heading is
  10394              ;; folded, we are inserting after visible newline at
  10395              ;; the end of the fold, thus breaking the fold
  10396              ;; continuity.
  10397              (unless (eobp)
  10398                (when (org-at-heading-p) (backward-char)))
  10399              (org-fold-core-ignore-modifications
  10400 	       (unless (bolp) (insert-and-inherit "\n"))
  10401 	       (let ((beg (point)))
  10402 	         (insert-and-inherit ":" drawer ":\n:END:\n")
  10403 	         (org-indent-region beg (point))
  10404 	         (org-fold-region (line-end-position -1) (1- (point)) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline)))))
  10405 	   (end-of-line -1))))
  10406       (t
  10407        (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
  10408        (let ((endpos (point)))
  10409          (skip-chars-forward " \t\n")
  10410          (beginning-of-line)
  10411          (unless org-log-states-order-reversed
  10412 	   (org-skip-over-state-notes)
  10413 	   (skip-chars-backward " \t\n")
  10414 	   (beginning-of-line 2))
  10415          ;; When current headline is at the end of buffer and does not
  10416          ;; end with trailing newline the above can move to the
  10417          ;; beginning of the headline.
  10418          (when (< (point) endpos) (goto-char endpos))))))
  10419    (if (bolp) (point) (line-beginning-position 2))))
  10420 
  10421 (defun org-add-log-setup (&optional purpose state prev-state how extra)
  10422   "Set up the post command hook to take a note.
  10423 If this is about to TODO state change, the new state is expected in STATE.
  10424 HOW is an indicator what kind of note should be created.
  10425 EXTRA is additional text that will be inserted into the notes buffer."
  10426   (move-marker org-log-note-marker (point))
  10427   (setq org-log-note-purpose purpose
  10428 	org-log-note-state state
  10429 	org-log-note-previous-state prev-state
  10430 	org-log-note-how how
  10431 	org-log-note-extra extra
  10432 	org-log-note-effective-time (org-current-effective-time)
  10433         org-log-note-this-command this-command
  10434         org-log-note-recursion-depth (recursion-depth)
  10435         org-log-setup t)
  10436   (add-hook 'post-command-hook 'org-add-log-note 'append))
  10437 
  10438 (defun org-skip-over-state-notes ()
  10439   "Skip past the list of State notes in an entry."
  10440   (when (ignore-errors (goto-char (org-in-item-p)))
  10441     (let* ((struct (org-list-struct))
  10442 	   (prevs (org-list-prevs-alist struct))
  10443 	   (regexp
  10444 	    (concat "[ \t]*- +"
  10445 		    (replace-regexp-in-string
  10446 		     " +" " +"
  10447 		     (org-replace-escapes
  10448 		      (regexp-quote (cdr (assq 'state org-log-note-headings)))
  10449 		      `(("%d" . ,org-ts-regexp-inactive)
  10450 			("%D" . ,org-ts-regexp)
  10451 			("%s" . "\\(?:\"\\S-+\"\\)?")
  10452 			("%S" . "\\(?:\"\\S-+\"\\)?")
  10453 			("%t" . ,org-ts-regexp-inactive)
  10454 			("%T" . ,org-ts-regexp)
  10455 			("%u" . ".*?")
  10456 			("%U" . ".*?")))))))
  10457       (while (looking-at-p regexp)
  10458 	(goto-char (or (org-list-get-next-item (point) struct prevs)
  10459 		       (org-list-get-item-end (point) struct)))))))
  10460 
  10461 (defun org-add-log-note (&optional _purpose)
  10462   "Pop up a window for taking a note, and add this note later."
  10463   (when (and (equal org-log-note-this-command this-command)
  10464              (= org-log-note-recursion-depth (recursion-depth)))
  10465     (remove-hook 'post-command-hook 'org-add-log-note)
  10466     (setq org-log-setup nil)
  10467     (setq org-log-note-window-configuration (current-window-configuration))
  10468     (delete-other-windows)
  10469     (move-marker org-log-note-return-to (point))
  10470     (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
  10471     (goto-char org-log-note-marker)
  10472     (org-switch-to-buffer-other-window "*Org Note*")
  10473     (erase-buffer)
  10474     (if (memq org-log-note-how '(time state))
  10475         (org-store-log-note)
  10476       (let ((org-inhibit-startup t)) (org-mode))
  10477       (insert (format "# Insert note for %s.
  10478 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
  10479                       (cl-case org-log-note-purpose
  10480                         (clock-out "stopped clock")
  10481                         (done  "closed todo item")
  10482                         (reschedule "rescheduling")
  10483                         (delschedule "no longer scheduled")
  10484                         (redeadline "changing deadline")
  10485                         (deldeadline "removing deadline")
  10486                         (refile "refiling")
  10487                         (note "this entry")
  10488                         (state
  10489                          (format "state change from \"%s\" to \"%s\""
  10490                                  (or org-log-note-previous-state "")
  10491                                  (or org-log-note-state "")))
  10492                         (t (error "This should not happen")))))
  10493       (when org-log-note-extra (insert org-log-note-extra))
  10494       (setq-local org-finish-function 'org-store-log-note)
  10495       (run-hooks 'org-log-buffer-setup-hook))))
  10496 
  10497 (defvar org-note-abort nil) ; dynamically scoped
  10498 (defun org-store-log-note ()
  10499   "Finish taking a log note, and insert it to where it belongs."
  10500   (let ((txt (prog1 (buffer-string)
  10501 	       (kill-buffer)))
  10502 	(note (cdr (assq org-log-note-purpose org-log-note-headings)))
  10503 	lines)
  10504     (while (string-match "\\`# .*\n[ \t\n]*" txt)
  10505       (setq txt (replace-match "" t t txt)))
  10506     (when (string-match "\\s-+\\'" txt)
  10507       (setq txt (replace-match "" t t txt)))
  10508     (setq lines (and (not (equal "" txt)) (org-split-string txt "\n")))
  10509     (when (org-string-nw-p note)
  10510       (setq note
  10511 	    (org-replace-escapes
  10512 	     note
  10513 	     (list (cons "%u" (user-login-name))
  10514 		   (cons "%U" user-full-name)
  10515 		   (cons "%t" (format-time-string
  10516 			       (org-time-stamp-format 'long 'inactive)
  10517 			       org-log-note-effective-time))
  10518 		   (cons "%T" (format-time-string
  10519 			       (org-time-stamp-format 'long nil)
  10520 			       org-log-note-effective-time))
  10521 		   (cons "%d" (format-time-string
  10522 			       (org-time-stamp-format nil 'inactive)
  10523 			       org-log-note-effective-time))
  10524 		   (cons "%D" (format-time-string
  10525 			       (org-time-stamp-format nil nil)
  10526 			       org-log-note-effective-time))
  10527 		   (cons "%s" (cond
  10528 			       ((not org-log-note-state) "")
  10529 			       ((string-match-p org-ts-regexp
  10530 						org-log-note-state)
  10531 				(format "\"[%s]\""
  10532 					(substring org-log-note-state 1 -1)))
  10533 			       (t (format "\"%s\"" org-log-note-state))))
  10534 		   (cons "%S"
  10535 			 (cond
  10536 			  ((not org-log-note-previous-state) "")
  10537 			  ((string-match-p org-ts-regexp
  10538 					   org-log-note-previous-state)
  10539 			   (format "\"[%s]\""
  10540 				   (substring
  10541 				    org-log-note-previous-state 1 -1)))
  10542 			  (t (format "\"%s\""
  10543 				     org-log-note-previous-state)))))))
  10544       (when lines (setq note (concat note " \\\\")))
  10545       (push note lines))
  10546     (when (and lines (not org-note-abort))
  10547       (with-current-buffer (marker-buffer org-log-note-marker)
  10548         (org-fold-core-ignore-modifications
  10549 	  (org-with-wide-buffer
  10550 	   ;; Find location for the new note.
  10551 	   (goto-char org-log-note-marker)
  10552 	   (set-marker org-log-note-marker nil)
  10553 	   ;; Note associated to a clock is to be located right after
  10554 	   ;; the clock.  Do not move point.
  10555 	   (unless (eq org-log-note-purpose 'clock-out)
  10556 	     (goto-char (org-log-beginning t)))
  10557 	   ;; Make sure point is at the beginning of an empty line.
  10558 	   (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert-and-inherit "\n")))
  10559 	         ((looking-at "[ \t]*\\S-") (save-excursion (insert-and-inherit "\n"))))
  10560 	   ;; In an existing list, add a new item at the top level.
  10561 	   ;; Otherwise, indent line like a regular one.
  10562 	   (let ((itemp (org-in-item-p)))
  10563 	     (if itemp
  10564 	         (indent-line-to
  10565 		  (let ((struct (save-excursion
  10566 				  (goto-char itemp) (org-list-struct))))
  10567 		    (org-list-get-ind (org-list-get-top-point struct) struct)))
  10568 	       (org-indent-line)))
  10569 	   (insert-and-inherit (org-list-bullet-string "-") (pop lines))
  10570 	   (let ((ind (org-list-item-body-column (line-beginning-position))))
  10571 	     (dolist (line lines)
  10572 	       (insert-and-inherit "\n")
  10573                (unless (string-empty-p line)
  10574 	         (indent-line-to ind)
  10575 	         (insert-and-inherit line))))
  10576 	   (message "Note stored")
  10577 	   (org-back-to-heading t))))))
  10578   ;; Don't add undo information when called from `org-agenda-todo'.
  10579   (set-window-configuration org-log-note-window-configuration)
  10580   (with-current-buffer (marker-buffer org-log-note-return-to)
  10581     (goto-char org-log-note-return-to))
  10582   (move-marker org-log-note-return-to nil)
  10583   (when org-log-post-message (message "%s" org-log-post-message)))
  10584 
  10585 (defun org-remove-empty-drawer-at (pos)
  10586   "Remove an empty drawer at position POS.
  10587 POS may also be a marker."
  10588   (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
  10589     (org-with-wide-buffer
  10590      (goto-char pos)
  10591      (let ((drawer (org-element-at-point)))
  10592        (when (and (memq (org-element-type drawer) '(drawer property-drawer))
  10593 		  (not (org-element-property :contents-begin drawer)))
  10594 	 (delete-region (org-element-property :begin drawer)
  10595 			(progn (goto-char (org-element-property :end drawer))
  10596 			       (skip-chars-backward " \r\t\n")
  10597 			       (forward-line)
  10598 			       (point))))))))
  10599 
  10600 (defvar org-ts-type nil)
  10601 (defun org-sparse-tree (&optional arg type)
  10602   "Create a sparse tree, prompt for the details.
  10603 This command can create sparse trees.  You first need to select the type
  10604 of match used to create the tree:
  10605 
  10606 t      Show all TODO entries.
  10607 T      Show entries with a specific TODO keyword.
  10608 m      Show entries selected by a tags/property match.
  10609 p      Enter a property name and its value (both with completion on existing
  10610        names/values) and show entries with that property.
  10611 r      Show entries matching a regular expression (`/' can be used as well).
  10612 b      Show deadlines and scheduled items before a date.
  10613 a      Show deadlines and scheduled items after a date.
  10614 d      Show deadlines due within `org-deadline-warning-days'.
  10615 D      Show deadlines and scheduled items between a date range."
  10616   (interactive "P")
  10617   (setq type (or type org-sparse-tree-default-date-type))
  10618   (setq org-ts-type type)
  10619   (message "Sparse tree: [r]egexp [t]odo [T]odo-kwd [m]atch [p]roperty
  10620              [d]eadlines [b]efore-date [a]fter-date [D]ates range
  10621              [c]ycle through date types: %s"
  10622 	   (cl-case type
  10623 	     (all "all timestamps")
  10624 	     (scheduled "only scheduled")
  10625 	     (deadline "only deadline")
  10626 	     (active "only active timestamps")
  10627 	     (inactive "only inactive timestamps")
  10628 	     (closed "with a closed time-stamp")
  10629 	     (otherwise "scheduled/deadline")))
  10630   (let ((answer (read-char-exclusive)))
  10631     (cl-case answer
  10632       (?c
  10633        (org-sparse-tree
  10634 	arg
  10635 	(cadr
  10636 	 (memq type '(nil all scheduled deadline active inactive closed)))))
  10637       (?d (call-interactively 'org-check-deadlines))
  10638       (?b (call-interactively 'org-check-before-date))
  10639       (?a (call-interactively 'org-check-after-date))
  10640       (?D (call-interactively 'org-check-dates-range))
  10641       (?t (call-interactively 'org-show-todo-tree))
  10642       (?T (org-show-todo-tree '(4)))
  10643       (?m (call-interactively 'org-match-sparse-tree))
  10644       ((?p ?P)
  10645        (let* ((kwd (completing-read
  10646 		    "Property: " (mapcar #'list (org-buffer-property-keys))))
  10647 	      (value (completing-read
  10648 		      "Value: " (mapcar #'list (org-property-values kwd)))))
  10649 	 (unless (string-match "\\`{.*}\\'" value)
  10650 	   (setq value (concat "\"" value "\"")))
  10651 	 (org-match-sparse-tree arg (concat kwd "=" value))))
  10652       ((?r ?R ?/) (call-interactively 'org-occur))
  10653       (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
  10654 
  10655 (defvar-local org-occur-highlights nil
  10656   "List of overlays used for occur matches.")
  10657 (defvar-local org-occur-parameters nil
  10658   "Parameters of the active org-occur calls.
  10659 This is a list, each call to org-occur pushes as cons cell,
  10660 containing the regular expression and the callback, onto the list.
  10661 The list can contain several entries if `org-occur' has been called
  10662 several time with the KEEP-PREVIOUS argument.  Otherwise, this list
  10663 will only contain one set of parameters.  When the highlights are
  10664 removed (for example with `C-c C-c', or with the next edit (depending
  10665 on `org-remove-highlights-with-change'), this variable is emptied
  10666 as well.")
  10667 
  10668 (defun org-occur (regexp &optional keep-previous callback)
  10669   "Make a compact tree showing all matches of REGEXP.
  10670 
  10671 The tree will show the lines where the regexp matches, and any other context
  10672 defined in `org-fold-show-context-detail', which see.
  10673 
  10674 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
  10675 done by a previous call to `org-occur' will be kept, to allow stacking of
  10676 calls to this command.
  10677 
  10678 Optional argument CALLBACK can be a function of no argument.  In this case,
  10679 it is called with point at the end of the match, match data being set
  10680 accordingly.  Current match is shown only if the return value is non-nil.
  10681 The function must neither move point nor alter narrowing."
  10682   (interactive "sRegexp: \nP")
  10683   (when (equal regexp "")
  10684     (user-error "Regexp cannot be empty"))
  10685   (unless keep-previous
  10686     (org-remove-occur-highlights nil nil t))
  10687   (push (cons regexp callback) org-occur-parameters)
  10688   (let ((cnt 0))
  10689     (save-excursion
  10690       (goto-char (point-min))
  10691       (when (or (not keep-previous)	    ; do not want to keep
  10692 		(not org-occur-highlights)) ; no previous matches
  10693 	;; hide everything
  10694 	(org-cycle-overview))
  10695       (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
  10696 				  (isearch-no-upper-case-p regexp t)
  10697 				org-occur-case-fold-search)))
  10698 	(while (re-search-forward regexp nil t)
  10699 	  (when (or (not callback)
  10700 		    (save-match-data (funcall callback)))
  10701 	    (setq cnt (1+ cnt))
  10702 	    (when org-highlight-sparse-tree-matches
  10703 	      (org-highlight-new-match (match-beginning 0) (match-end 0)))
  10704 	    (org-fold-show-context 'occur-tree)))))
  10705     (when org-remove-highlights-with-change
  10706       (add-hook 'before-change-functions 'org-remove-occur-highlights
  10707 		nil 'local))
  10708     (unless org-sparse-tree-open-archived-trees
  10709       (org-fold-hide-archived-subtrees (point-min) (point-max)))
  10710     (run-hooks 'org-occur-hook)
  10711     (when (called-interactively-p 'interactive)
  10712       (message "%d match(es) for regexp %s" cnt regexp))
  10713     cnt))
  10714 
  10715 (defun org-occur-next-match (&optional n _reset)
  10716   "Function for `next-error-function' to find sparse tree matches.
  10717 N is the number of matches to move, when negative move backwards.
  10718 This function always goes back to the starting point when no
  10719 match is found."
  10720   (let* ((limit (if (< n 0) (point-min) (point-max)))
  10721 	 (search-func (if (< n 0)
  10722 			  'previous-single-char-property-change
  10723 			'next-single-char-property-change))
  10724 	 (n (abs n))
  10725 	 (pos (point))
  10726 	 p1)
  10727     (catch 'exit
  10728       (while (setq p1 (funcall search-func (point) 'org-type))
  10729 	(when (equal p1 limit)
  10730 	  (goto-char pos)
  10731 	  (user-error "No more matches"))
  10732 	(when (equal (get-char-property p1 'org-type) 'org-occur)
  10733 	  (setq n (1- n))
  10734 	  (when (= n 0)
  10735 	    (goto-char p1)
  10736 	    (throw 'exit (point))))
  10737 	(goto-char p1))
  10738       (goto-char p1)
  10739       (user-error "No more matches"))))
  10740 
  10741 (defun org-highlight-new-match (beg end)
  10742   "Highlight from BEG to END and mark the highlight is an occur headline."
  10743   (let ((ov (make-overlay beg end)))
  10744     (overlay-put ov 'face 'secondary-selection)
  10745     (overlay-put ov 'org-type 'org-occur)
  10746     (push ov org-occur-highlights)))
  10747 
  10748 (defun org-remove-occur-highlights (&optional _beg _end noremove)
  10749   "Remove the occur highlights from the buffer.
  10750 BEG and END are ignored.  If NOREMOVE is nil, remove this function
  10751 from the `before-change-functions' in the current buffer."
  10752   (interactive)
  10753   (unless org-inhibit-highlight-removal
  10754     (mapc #'delete-overlay org-occur-highlights)
  10755     (setq org-occur-highlights nil)
  10756     (setq org-occur-parameters nil)
  10757     (unless noremove
  10758       (remove-hook 'before-change-functions
  10759 		   'org-remove-occur-highlights 'local))))
  10760 
  10761 ;;;; Priorities
  10762 
  10763 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]+\\)\\] ?\\)"
  10764   "Regular expression matching the priority indicator.
  10765 A priority indicator can be e.g. [#A] or [#1].
  10766 This regular expression matches these groups:
  10767 0 : the whole match, e.g. \"TODO [#A] Hack\"
  10768 1 : the priority cookie, e.g. \"[#A]\"
  10769 2 : the value of the priority cookie, e.g. \"A\".")
  10770 
  10771 (defun org-priority-up ()
  10772   "Increase the priority of the current item."
  10773   (interactive)
  10774   (org-priority 'up))
  10775 
  10776 (defun org-priority-down ()
  10777   "Decrease the priority of the current item."
  10778   (interactive)
  10779   (org-priority 'down))
  10780 
  10781 (defun org-priority (&optional action show)
  10782   "Change the priority of an item.
  10783 
  10784 When called interactively with a `\\[universal-argument]' prefix,
  10785 show the priority in the minibuffer instead of changing it.
  10786 
  10787 When called programmatically, ACTION can be `set', `up', `down',
  10788 or a character."
  10789   (interactive "P")
  10790   (when show
  10791     ;; Deprecation warning inserted for Org 9.2; once enough time has
  10792     ;; passed the SHOW argument should be removed.
  10793     (warn "`org-priority' called with deprecated SHOW argument"))
  10794   (if (equal action '(4))
  10795       (org-priority-show)
  10796     (unless org-priority-enable-commands
  10797       (user-error "Priority commands are disabled"))
  10798     (setq action (or action 'set))
  10799     (let ((nump (< org-priority-lowest 65))
  10800 	  current new news have remove)
  10801       (save-excursion
  10802 	(org-back-to-heading t)
  10803 	(when (looking-at org-priority-regexp)
  10804 	  (let ((ms (match-string 2)))
  10805 	    (setq current (org-priority-to-value ms)
  10806 		  have t)))
  10807 	(cond
  10808 	 ((eq action 'remove)
  10809 	  (setq remove t new ?\ ))
  10810 	 ((or (eq action 'set)
  10811 	      (integerp action))
  10812 	  (if (not (eq action 'set))
  10813 	      (setq new action)
  10814 	    (setq
  10815 	     new
  10816 	     (if nump
  10817                  (let* ((msg (format "Priority %s-%s, SPC to remove: "
  10818                                      (number-to-string org-priority-highest)
  10819                                      (number-to-string org-priority-lowest)))
  10820                         (s (if (< 9 org-priority-lowest)
  10821                                (read-string msg)
  10822                              (message msg)
  10823                              (char-to-string (read-char-exclusive)))))
  10824                    (if (equal s " ") ?\s (string-to-number s)))
  10825 	       (progn (message "Priority %c-%c, SPC to remove: "
  10826 			       org-priority-highest org-priority-lowest)
  10827 		      (save-match-data
  10828 			(setq new (read-char-exclusive)))))))
  10829 	  (when (and (= (upcase org-priority-highest) org-priority-highest)
  10830 		     (= (upcase org-priority-lowest) org-priority-lowest))
  10831 	    (setq new (upcase new)))
  10832 	  (cond ((equal new ?\s) (setq remove t))
  10833 		((or (< (upcase new) org-priority-highest) (> (upcase new) org-priority-lowest))
  10834 		 (user-error
  10835 		  (if nump
  10836 		      "Priority must be between `%s' and `%s'"
  10837 		    "Priority must be between `%c' and `%c'")
  10838 		  org-priority-highest org-priority-lowest))))
  10839 	 ((eq action 'up)
  10840 	  (setq new (if have
  10841 			(1- current)  ; normal cycling
  10842 		      ;; last priority was empty
  10843 		      (if (eq last-command this-command)
  10844 			  org-priority-lowest  ; wrap around empty to lowest
  10845 			;; default
  10846 			(if org-priority-start-cycle-with-default
  10847 			    org-priority-default
  10848 			  (1- org-priority-default))))))
  10849 	 ((eq action 'down)
  10850 	  (setq new (if have
  10851 			(1+ current)  ; normal cycling
  10852 		      ;; last priority was empty
  10853 		      (if (eq last-command this-command)
  10854 			  org-priority-highest  ; wrap around empty to highest
  10855 			;; default
  10856 			(if org-priority-start-cycle-with-default
  10857 			    org-priority-default
  10858 			  (1+ org-priority-default))))))
  10859 	 (t (user-error "Invalid action")))
  10860 	(when (or (< (upcase new) org-priority-highest)
  10861 		  (> (upcase new) org-priority-lowest))
  10862 	  (if (and (memq action '(up down))
  10863 		   (not have) (not (eq last-command this-command)))
  10864 	      ;; `new' is from default priority
  10865 	      (error
  10866 	       "The default can not be set, see `org-priority-default' why")
  10867 	    ;; normal cycling: `new' is beyond highest/lowest priority
  10868 	    ;; and is wrapped around to the empty priority
  10869 	    (setq remove t)))
  10870 	;; Numerical priorities are limited to 64, beyond that number,
  10871 	;; assume the priority cookie is a character.
  10872 	(setq news (if (> new 64) (format "%c" new) (format "%s" new)))
  10873 	(if have
  10874 	    (if remove
  10875 		(replace-match "" t t nil 1)
  10876 	      (replace-match news t t nil 2))
  10877 	  (if remove
  10878 	      (user-error "No priority cookie found in line")
  10879 	    (let ((case-fold-search nil)) (looking-at org-todo-line-regexp))
  10880 	    (if (match-end 2)
  10881 		(progn
  10882 		  (goto-char (match-end 2))
  10883 		  (insert " [#" news "]"))
  10884 	      (goto-char (match-beginning 3))
  10885 	      (insert "[#" news "] "))))
  10886 	(org-align-tags))
  10887       (if remove
  10888 	  (message "Priority removed")
  10889 	(message "Priority of current item set to %s" news)))))
  10890 
  10891 (defalias 'org-show-priority 'org-priority-show)
  10892 (defun org-priority-show ()
  10893   "Show the priority of the current item.
  10894 This priority is composed of the main priority given with the [#A] cookies,
  10895 and by additional input from the age of a schedules or deadline entry."
  10896   (interactive)
  10897   (let ((pri (if (eq major-mode 'org-agenda-mode)
  10898 		 (org-get-at-bol 'priority)
  10899 	       (save-excursion
  10900 		 (save-match-data
  10901 		   (beginning-of-line)
  10902 		   (and (looking-at org-heading-regexp)
  10903 			(org-get-priority (match-string 0))))))))
  10904     (message "Priority is %d" (if pri pri -1000))))
  10905 
  10906 (defun org-get-priority (s)
  10907   "Find priority cookie and return priority.
  10908 S is a string against which you can match `org-priority-regexp'.
  10909 If `org-priority-get-priority-function' is set to a custom
  10910 function, use it.  Otherwise process S and output the priority
  10911 value, an integer."
  10912   (save-match-data
  10913     (if (functionp org-priority-get-priority-function)
  10914 	(funcall org-priority-get-priority-function s)
  10915       (if (not (string-match org-priority-regexp s))
  10916 	  (* 1000 (- org-priority-lowest org-priority-default))
  10917 	(* 1000 (- org-priority-lowest
  10918 		   (org-priority-to-value (match-string 2 s))))))))
  10919 
  10920 ;;;; Tags
  10921 
  10922 (defvar org-agenda-archives-mode)
  10923 (defvar org-map-continue-from nil
  10924   "Position from where mapping should continue.
  10925 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
  10926 
  10927 (defvar org-scanner-tags nil
  10928   "The current tag list while the tags scanner is running.")
  10929 
  10930 (defvar org-trust-scanner-tags nil
  10931   "Should `org-get-tags' use the tags for the scanner.
  10932 This is for internal dynamical scoping only.
  10933 When this is non-nil, the function `org-get-tags' will return the value
  10934 of `org-scanner-tags' instead of building the list by itself.  This
  10935 can lead to large speed-ups when the tags scanner is used in a file with
  10936 many entries, and when the list of tags is retrieved, for example to
  10937 obtain a list of properties.  Building the tags list for each entry in such
  10938 a file becomes an N^2 operation - but with this variable set, it scales
  10939 as N.")
  10940 
  10941 (defvar org--matcher-tags-todo-only nil)
  10942 
  10943 (defun org-scan-tags (action matcher todo-only &optional start-level)
  10944   "Scan headline tags with inheritance and produce output ACTION.
  10945 
  10946 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
  10947 or `agenda' to produce an entry list for an agenda view.  It can also be
  10948 a Lisp form or a function that should be called at each matched headline, in
  10949 this case the return value is a list of all return values from these calls.
  10950 
  10951 MATCHER is a function accepting three arguments, returning
  10952 a non-nil value whenever a given set of tags qualifies a headline
  10953 for inclusion.  See `org-make-tags-matcher' for more information.
  10954 As a special case, it can also be set to t (respectively nil) in
  10955 order to match all (respectively none) headline.
  10956 
  10957 When TODO-ONLY is non-nil, only lines with a TODO keyword are
  10958 included in the output.
  10959 
  10960 START-LEVEL can be a string with asterisks, reducing the scope to
  10961 headlines matching this string."
  10962   (require 'org-agenda)
  10963   (let* ((re (concat "^"
  10964 		     (if start-level
  10965 			 ;; Get the correct level to match
  10966 			 (concat "\\*\\{" (number-to-string start-level) "\\} ")
  10967 		       org-outline-regexp)
  10968 		     " *\\(?:\\(" (regexp-opt org-todo-keywords-1 t) "\\) \\)?"
  10969 		     " *\\(.*?\\)\\([ \t]:\\(?:" org-tag-re ":\\)+\\)?[ \t]*$"))
  10970 	 (props (list 'face 'default
  10971 		      'done-face 'org-agenda-done
  10972 		      'undone-face 'default
  10973 		      'mouse-face 'highlight
  10974 		      'org-not-done-regexp org-not-done-regexp
  10975 		      'org-todo-regexp org-todo-regexp
  10976 		      'org-complex-heading-regexp org-complex-heading-regexp
  10977 		      'help-echo
  10978 		      (format "mouse-2 or RET jump to Org file %S"
  10979 			      (abbreviate-file-name
  10980 			       (or (buffer-file-name (buffer-base-buffer))
  10981 				   (buffer-name (buffer-base-buffer)))))))
  10982 	 (org-map-continue-from nil)
  10983          lspos tags tags-list
  10984 	 (tags-alist (list (cons 0 org-file-tags)))
  10985 	 (llast 0) rtn rtn1 level category i txt
  10986 	 todo marker entry priority
  10987 	 ts-date ts-date-type ts-date-pair)
  10988     (unless (or (member action '(agenda sparse-tree)) (functionp action))
  10989       (setq action (list 'lambda nil action)))
  10990     (save-excursion
  10991       (goto-char (point-min))
  10992       (when (eq action 'sparse-tree)
  10993 	(org-cycle-overview)
  10994 	(org-remove-occur-highlights))
  10995       (if (org-element--cache-active-p)
  10996           (let ((fast-re (concat "^"
  10997                                  (if start-level
  10998 		                     ;; Get the correct level to match
  10999 		                     (concat "\\*\\{" (number-to-string start-level) "\\} ")
  11000 		                   org-outline-regexp))))
  11001             (org-element-cache-map
  11002              (lambda (el)
  11003                (goto-char (org-element-property :begin el))
  11004                (setq todo (org-element-property :todo-keyword el)
  11005                      level (org-element-property :level el)
  11006                      category (org-entry-get-with-inheritance "CATEGORY" nil el)
  11007                      tags-list (org-get-tags el)
  11008                      org-scanner-tags tags-list)
  11009                (when (eq action 'agenda)
  11010                  (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  11011 		       ts-date (car ts-date-pair)
  11012 		       ts-date-type (cdr ts-date-pair)))
  11013                (catch :skip
  11014                  (when (and
  11015 
  11016 		        ;; eval matcher only when the todo condition is OK
  11017 		        (and (or (not todo-only) (member todo org-todo-keywords-1))
  11018 		             (if (functionp matcher)
  11019 			         (let ((case-fold-search t) (org-trust-scanner-tags t))
  11020 			           (funcall matcher todo tags-list level))
  11021 			       matcher))
  11022 
  11023 		        ;; Call the skipper, but return t if it does not
  11024 		        ;; skip, so that the `and' form continues evaluating.
  11025 		        (progn
  11026 		          (unless (eq action 'sparse-tree) (org-agenda-skip el))
  11027 		          t)
  11028 
  11029 		        ;; Check if timestamps are deselecting this entry
  11030 		        (or (not todo-only)
  11031 		            (and (member todo org-todo-keywords-1)
  11032 			         (or (not org-agenda-tags-todo-honor-ignore-options)
  11033 			             (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  11034 
  11035 	           ;; select this headline
  11036 	           (cond
  11037 	            ((eq action 'sparse-tree)
  11038 	             (and org-highlight-sparse-tree-matches
  11039 		          (org-get-heading) (match-end 0)
  11040 		          (org-highlight-new-match
  11041 		           (match-beginning 1) (match-end 1)))
  11042 	             (org-fold-show-context 'tags-tree))
  11043 	            ((eq action 'agenda)
  11044                      (let* ((effort (org-entry-get (point) org-effort-property))
  11045                             (effort-minutes (when effort (save-match-data (org-duration-to-minutes effort)))))
  11046 	               (setq txt (org-agenda-format-item
  11047 			          ""
  11048                                   ;; Add `effort' and `effort-minutes'
  11049                                   ;; properties for prefix format.
  11050                                   (org-add-props
  11051                                       (concat
  11052 			               (if (eq org-tags-match-list-sublevels 'indented)
  11053 			                   (make-string (1- level) ?.) "")
  11054 			               (org-get-heading))
  11055                                       nil
  11056                                     'effort effort
  11057                                     'effort-minutes effort-minutes)
  11058 			          (make-string level ?\s)
  11059 			          category
  11060 			          tags-list)
  11061 		             priority (org-get-priority txt))
  11062                        ;; Now add `effort' and `effort-minutes' to
  11063                        ;; full agenda line.
  11064                        (setq txt (org-add-props txt nil
  11065                                    'effort effort
  11066                                    'effort-minutes effort-minutes)))
  11067 	             (goto-char (org-element-property :begin el))
  11068 	             (setq marker (org-agenda-new-marker))
  11069 	             (org-add-props txt props
  11070 		       'org-marker marker 'org-hd-marker marker 'org-category category
  11071 		       'todo-state todo
  11072                        'ts-date ts-date
  11073 		       'priority priority
  11074                        'type (concat "tagsmatch" ts-date-type))
  11075 	             (push txt rtn))
  11076 	            ((functionp action)
  11077 	             (setq org-map-continue-from nil)
  11078 	             (save-excursion
  11079 		       (setq rtn1 (funcall action))
  11080 		       (push rtn1 rtn)))
  11081 	            (t (user-error "Invalid action")))
  11082 
  11083 	           ;; if we are to skip sublevels, jump to end of subtree
  11084 	           (unless org-tags-match-list-sublevels
  11085 	             (goto-char (1- (org-element-property :end el))))))
  11086                ;; Get the correct position from where to continue
  11087 	       (when org-map-continue-from
  11088                  (setq org-element-cache-map-continue-from org-map-continue-from)
  11089 	         (goto-char org-map-continue-from))
  11090                ;; Return nil.
  11091                nil)
  11092              :next-re fast-re
  11093              :fail-re fast-re
  11094              :narrow t))
  11095         (while (let (case-fold-search)
  11096 	         (re-search-forward re nil t))
  11097 	  (setq org-map-continue-from nil)
  11098 	  (catch :skip
  11099 	    ;; Ignore closing parts of inline tasks.
  11100 	    (when (and (fboundp 'org-inlinetask-end-p) (org-inlinetask-end-p))
  11101 	      (throw :skip t))
  11102 	    (setq todo (and (match-end 1) (match-string-no-properties 1)))
  11103             (setq tags (and (match-end 4) (org-trim (match-string-no-properties 4))))
  11104 	    (goto-char (setq lspos (match-beginning 0)))
  11105 	    (setq level (org-reduced-level (org-outline-level))
  11106 		  category (org-get-category))
  11107             (when (eq action 'agenda)
  11108               (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
  11109 		    ts-date (car ts-date-pair)
  11110 		    ts-date-type (cdr ts-date-pair)))
  11111 	    (setq i llast llast level)
  11112 	    ;; remove tag lists from same and sublevels
  11113 	    (while (>= i level)
  11114 	      (when (setq entry (assoc i tags-alist))
  11115 	        (setq tags-alist (delete entry tags-alist)))
  11116 	      (setq i (1- i)))
  11117 	    ;; add the next tags
  11118 	    (when tags
  11119 	      (setq tags (org-split-string tags ":")
  11120 		    tags-alist
  11121 		    (cons (cons level tags) tags-alist)))
  11122 	    ;; compile tags for current headline
  11123 	    (setq tags-list
  11124 		  (if org-use-tag-inheritance
  11125 		      (apply 'append (mapcar 'cdr (reverse tags-alist)))
  11126 		    tags)
  11127 		  org-scanner-tags tags-list)
  11128 	    (when org-use-tag-inheritance
  11129 	      (setcdr (car tags-alist)
  11130 		      (mapcar (lambda (x)
  11131 			        (setq x (copy-sequence x))
  11132 			        (org-add-prop-inherited x))
  11133 			      (cdar tags-alist))))
  11134 	    (when (and tags org-use-tag-inheritance
  11135 		       (or (not (eq t org-use-tag-inheritance))
  11136 			   org-tags-exclude-from-inheritance))
  11137 	      ;; Selective inheritance, remove uninherited ones.
  11138 	      (setcdr (car tags-alist)
  11139 		      (org-remove-uninherited-tags (cdar tags-alist))))
  11140 	    (when (and
  11141 
  11142 		   ;; eval matcher only when the todo condition is OK
  11143 		   (and (or (not todo-only) (member todo org-todo-keywords-1))
  11144 		        (if (functionp matcher)
  11145 			    (let ((case-fold-search t) (org-trust-scanner-tags t))
  11146 			      (funcall matcher todo tags-list level))
  11147 			  matcher))
  11148 
  11149 		   ;; Call the skipper, but return t if it does not
  11150 		   ;; skip, so that the `and' form continues evaluating.
  11151 		   (progn
  11152 		     (unless (eq action 'sparse-tree) (org-agenda-skip))
  11153 		     t)
  11154 
  11155 		   ;; Check if timestamps are deselecting this entry
  11156 		   (or (not todo-only)
  11157 		       (and (member todo org-todo-keywords-1)
  11158 			    (or (not org-agenda-tags-todo-honor-ignore-options)
  11159 			        (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
  11160 
  11161 	      ;; select this headline
  11162 	      (cond
  11163 	       ((eq action 'sparse-tree)
  11164 	        (and org-highlight-sparse-tree-matches
  11165 		     (org-get-heading) (match-end 0)
  11166 		     (org-highlight-new-match
  11167 		      (match-beginning 1) (match-end 1)))
  11168 	        (org-fold-show-context 'tags-tree))
  11169 	       ((eq action 'agenda)
  11170 	        (setq txt (org-agenda-format-item
  11171 			   ""
  11172 			   (concat
  11173 			    (if (eq org-tags-match-list-sublevels 'indented)
  11174 			        (make-string (1- level) ?.) "")
  11175 			    (org-get-heading))
  11176 			   (make-string level ?\s)
  11177 			   category
  11178 			   tags-list)
  11179 		      priority (org-get-priority txt))
  11180 	        (goto-char lspos)
  11181 	        (setq marker (org-agenda-new-marker))
  11182 	        (org-add-props txt props
  11183 		  'org-marker marker 'org-hd-marker marker 'org-category category
  11184 		  'todo-state todo
  11185                   'ts-date ts-date
  11186 		  'priority priority
  11187                   'type (concat "tagsmatch" ts-date-type))
  11188 	        (push txt rtn))
  11189 	       ((functionp action)
  11190 	        (setq org-map-continue-from nil)
  11191 	        (save-excursion
  11192 		  (setq rtn1 (funcall action))
  11193 		  (push rtn1 rtn)))
  11194 	       (t (user-error "Invalid action")))
  11195 
  11196 	      ;; if we are to skip sublevels, jump to end of subtree
  11197 	      (unless org-tags-match-list-sublevels
  11198 	        (org-end-of-subtree t)
  11199 	        (backward-char 1))))
  11200 	  ;; Get the correct position from where to continue
  11201 	  (if org-map-continue-from
  11202 	      (goto-char org-map-continue-from)
  11203 	    (and (= (point) lspos) (end-of-line 1))))))
  11204     (when (and (eq action 'sparse-tree)
  11205 	       (not org-sparse-tree-open-archived-trees))
  11206       (org-fold-hide-archived-subtrees (point-min) (point-max)))
  11207     (nreverse rtn)))
  11208 
  11209 (defun org-remove-uninherited-tags (tags)
  11210   "Remove all tags that are not inherited from the list TAGS."
  11211   (cond
  11212    ((eq org-use-tag-inheritance t)
  11213     (if org-tags-exclude-from-inheritance
  11214 	(org-delete-all org-tags-exclude-from-inheritance tags)
  11215       tags))
  11216    ((not org-use-tag-inheritance) nil)
  11217    ((stringp org-use-tag-inheritance)
  11218     (delq nil (mapcar
  11219 	       (lambda (x)
  11220 		 (if (and (string-match org-use-tag-inheritance x)
  11221 			  (not (member x org-tags-exclude-from-inheritance)))
  11222 		     x nil))
  11223 	       tags)))
  11224    ((listp org-use-tag-inheritance)
  11225     (delq nil (mapcar
  11226 	       (lambda (x)
  11227 		 (if (member x org-use-tag-inheritance) x nil))
  11228 	       tags)))))
  11229 
  11230 (defun org-match-sparse-tree (&optional todo-only match)
  11231   "Create a sparse tree according to tags string MATCH.
  11232 
  11233 MATCH is a string with match syntax.  It can contain a selection
  11234 of tags (\"+work+urgent-boss\"), properties (\"LEVEL>3\"), and
  11235 TODO keywords (\"TODO=\\\"WAITING\\\"\") or a combination of
  11236 those.  See the manual for details.
  11237 
  11238 If optional argument TODO-ONLY is non-nil, only select lines that
  11239 are also TODO tasks."
  11240   (interactive "P")
  11241   (org-agenda-prepare-buffers (list (current-buffer)))
  11242   (let ((org--matcher-tags-todo-only todo-only))
  11243     (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match t))
  11244 		   org--matcher-tags-todo-only)))
  11245 
  11246 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
  11247 
  11248 (defvar org-cached-props nil)
  11249 (defun org-cached-entry-get (pom property)
  11250   (if (or (eq t org-use-property-inheritance)
  11251 	  (and (stringp org-use-property-inheritance)
  11252 	       (let ((case-fold-search t))
  11253 		 (string-match-p org-use-property-inheritance property)))
  11254 	  (and (listp org-use-property-inheritance)
  11255 	       (member-ignore-case property org-use-property-inheritance)))
  11256       ;; Caching is not possible, check it directly.
  11257       (org-entry-get pom property 'inherit)
  11258     ;; Get all properties, so we can do complicated checks easily.
  11259     (cdr (assoc-string property
  11260 		       (or org-cached-props
  11261 			   (setq org-cached-props (org-entry-properties pom)))
  11262 		       t))))
  11263 
  11264 (defun org-global-tags-completion-table (&optional files)
  11265   "Return the list of all tags in all agenda buffer/files.
  11266 Optional FILES argument is a list of files which can be used
  11267 instead of the agenda files."
  11268   (save-excursion
  11269     (org-uniquify
  11270      (delq nil
  11271 	   (apply #'append
  11272 		  (mapcar
  11273 		   (lambda (file)
  11274 		     (set-buffer (find-file-noselect file))
  11275 		     (org--tag-add-to-alist
  11276 		      (org-get-buffer-tags)
  11277 		      (mapcar (lambda (x)
  11278 				(and (stringp (car-safe x))
  11279 				     (list (car-safe x))))
  11280 			      org-current-tag-alist)))
  11281 		   (if (car-safe files) files
  11282 		     (org-agenda-files))))))))
  11283 
  11284 (defun org-make-tags-matcher (match &optional only-local-tags)
  11285   "Create the TAGS/TODO matcher form for the selection string MATCH.
  11286 
  11287 Returns a cons of the selection string MATCH and a function
  11288 implementing the matcher.
  11289 
  11290 The matcher is to be called at an Org entry, with point on the
  11291 headline, and returns non-nil if the entry matches the selection
  11292 string MATCH.  It must be called with three arguments: the TODO
  11293 keyword at the entry (or nil if none), the list of all tags at
  11294 the entry including inherited ones and the reduced level of the
  11295 headline.  Additionally, the category of the entry, if any, must
  11296 be specified as the text property `org-category' on the headline.
  11297 
  11298 This function sets the variable `org--matcher-tags-todo-only' to
  11299 a non-nil value if the matcher restricts matching to TODO
  11300 entries, otherwise it is not touched.
  11301 
  11302 When ONLY-LOCAL-TAGS is non-nil, ignore the global tag completion
  11303 table, only get buffer tags.
  11304 
  11305 See also `org-scan-tags'."
  11306   (unless match
  11307     ;; Get a new match request, with completion against the global
  11308     ;; tags table and the local tags in current buffer.
  11309     (let ((org-last-tags-completion-table
  11310 	   (org--tag-add-to-alist
  11311 	    (org-get-buffer-tags)
  11312 	    (unless only-local-tags
  11313 	      (org-global-tags-completion-table)))))
  11314       (setq match
  11315 	    (completing-read
  11316 	     "Match: "
  11317 	     'org-tags-completion-function nil nil nil 'org-tags-history))))
  11318 
  11319   (let ((match0 match)
  11320 	(re (concat
  11321 	     "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)"
  11322 	     "\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)"
  11323 	     "\\([<>=]\\{1,2\\}\\)"
  11324 	     "\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)"
  11325 	     "\\|" org-tag-re "\\)"))
  11326 	(start 0)
  11327 	tagsmatch todomatch tagsmatcher todomatcher)
  11328 
  11329     ;; Expand group tags.
  11330     (setq match (org-tags-expand match))
  11331 
  11332     ;; Check if there is a TODO part of this match, which would be the
  11333     ;; part after a "/".  To make sure that this slash is not part of
  11334     ;; a property value to be matched against, we also check that
  11335     ;; there is no / after that slash.  First, find the last slash.
  11336     (let ((s 0))
  11337       (while (string-match "/+" match s)
  11338 	(setq start (match-beginning 0))
  11339 	(setq s (match-end 0))))
  11340     (if (and (string-match "/+" match start)
  11341 	     (not (string-match-p "\"" match start)))
  11342 	;; Match contains also a TODO-matching request.
  11343 	(progn
  11344 	  (setq tagsmatch (substring match 0 (match-beginning 0)))
  11345 	  (setq todomatch (substring match (match-end 0)))
  11346 	  (when (string-prefix-p "!" todomatch)
  11347 	    (setq org--matcher-tags-todo-only t)
  11348 	    (setq todomatch (substring todomatch 1)))
  11349 	  (when (string-match "\\`\\s-*\\'" todomatch)
  11350 	    (setq todomatch nil)))
  11351       ;; Only matching tags.
  11352       (setq tagsmatch match)
  11353       (setq todomatch nil))
  11354 
  11355     ;; Make the tags matcher.
  11356     (when (org-string-nw-p tagsmatch)
  11357       (let ((orlist nil)
  11358 	    (orterms (org-split-string tagsmatch "|"))
  11359 	    term)
  11360 	(while (setq term (pop orterms))
  11361 	  (while (and (equal (substring term -1) "\\") orterms)
  11362 	    (setq term (concat term "|" (pop orterms)))) ;repair bad split.
  11363 	  (while (string-match re term)
  11364 	    (let* ((rest (substring term (match-end 0)))
  11365 		   (minus (and (match-end 1)
  11366 			       (equal (match-string 1 term) "-")))
  11367 		   (tag (save-match-data
  11368 			  (replace-regexp-in-string
  11369 			   "\\\\-" "-" (match-string 2 term))))
  11370 		   (regexp (eq (string-to-char tag) ?{))
  11371 		   (levelp (match-end 4))
  11372 		   (propp (match-end 5))
  11373 		   (mm
  11374 		    (cond
  11375 		     (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
  11376 		     (levelp
  11377 		      `(,(org-op-to-function (match-string 3 term))
  11378 			level
  11379 			,(string-to-number (match-string 4 term))))
  11380 		     (propp
  11381 		      (let* ((gv (pcase (upcase (match-string 5 term))
  11382 				   ("CATEGORY"
  11383 				    '(org-get-category (point)))
  11384 				   ("TODO" 'todo)
  11385 				   (p `(org-cached-entry-get nil ,p))))
  11386 			     (pv (match-string 7 term))
  11387 			     (regexp (eq (string-to-char pv) ?{))
  11388 			     (strp (eq (string-to-char pv) ?\"))
  11389 			     (timep (string-match-p "^\"[[<]\\(?:[0-9]+\\|now\\|today\\|tomorrow\\|[+-][0-9]+[dmwy]\\).*[]>]\"$" pv))
  11390 			     (po (org-op-to-function (match-string 6 term)
  11391 						     (if timep 'time strp))))
  11392 			(setq pv (if (or regexp strp) (substring pv 1 -1) pv))
  11393 			(when timep (setq pv (org-matcher-time pv)))
  11394 			(cond ((and regexp (eq po '/=))
  11395 			       `(not (string-match ,pv (or ,gv ""))))
  11396 			      (regexp `(string-match ,pv (or ,gv "")))
  11397 			      (strp `(,po (or ,gv "") ,pv))
  11398 			      (t
  11399 			       `(,po
  11400 				 (string-to-number (or ,gv ""))
  11401 				 ,(string-to-number pv))))))
  11402 		     (t `(member ,tag tags-list)))))
  11403 	      (push (if minus `(not ,mm) mm) tagsmatcher)
  11404 	      (setq term rest)))
  11405 	  (push `(and ,@tagsmatcher) orlist)
  11406 	  (setq tagsmatcher nil))
  11407 	(setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
  11408 
  11409     ;; Make the TODO matcher.
  11410     (when (org-string-nw-p todomatch)
  11411       (let ((orlist nil))
  11412 	(dolist (term (org-split-string todomatch "|"))
  11413 	  (while (string-match re term)
  11414 	    (let* ((minus (and (match-end 1)
  11415 			       (equal (match-string 1 term) "-")))
  11416 		   (kwd (match-string 2 term))
  11417 		   (regexp (eq (string-to-char kwd) ?{))
  11418 		   (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
  11419 			 `(equal todo ,kwd))))
  11420 	      (push (if minus `(not ,mm) mm) todomatcher))
  11421 	    (setq term (substring term (match-end 0))))
  11422 	  (push (if (> (length todomatcher) 1)
  11423 		    (cons 'and todomatcher)
  11424 		  (car todomatcher))
  11425 		orlist)
  11426 	  (setq todomatcher nil))
  11427 	(setq todomatcher (cons 'or orlist))))
  11428 
  11429     ;; Return the string and function of the matcher.  If no
  11430     ;; tags-specific or todo-specific matcher exists, match
  11431     ;; everything.
  11432     (let ((matcher (if (and tagsmatcher todomatcher)
  11433 		       `(and ,tagsmatcher ,todomatcher)
  11434 		     (or tagsmatcher todomatcher t))))
  11435       (when org--matcher-tags-todo-only
  11436 	(setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
  11437       (cons match0 `(lambda (todo tags-list level) ,matcher)))))
  11438 
  11439 (defun org--tags-expand-group (group tag-groups expanded)
  11440   "Recursively expand all tags in GROUP, according to TAG-GROUPS.
  11441 TAG-GROUPS is the list of groups used for expansion.  EXPANDED is
  11442 an accumulator used in recursive calls."
  11443   (dolist (tag group)
  11444     (unless (member tag expanded)
  11445       (let ((group (assoc tag tag-groups)))
  11446 	(push tag expanded)
  11447 	(when group
  11448 	  (setq expanded
  11449 		(org--tags-expand-group (cdr group) tag-groups expanded))))))
  11450   expanded)
  11451 
  11452 (defun org-tags-expand (match &optional single-as-list)
  11453   "Expand group tags in MATCH.
  11454 
  11455 This replaces every group tag in MATCH with a regexp tag search.
  11456 For example, a group tag \"Work\" defined as { Work : Lab Conf }
  11457 will be replaced like this:
  11458 
  11459    Work =>  {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11460   +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11461   -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
  11462 
  11463 Replacing by a regexp preserves the structure of the match.
  11464 E.g., this expansion
  11465 
  11466   Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
  11467 
  11468 will match anything tagged with \"Lab\" and \"Home\", or tagged
  11469 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"Home\".
  11470 
  11471 A group tag in MATCH can contain regular expressions of its own.
  11472 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
  11473 will be replaced like this:
  11474 
  11475    Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
  11476 
  11477 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
  11478 assumed to be a single group tag, and the function will return
  11479 the list of tags in this group."
  11480   (unless (org-string-nw-p match) (error "Invalid match tag: %S" match))
  11481   (let ((tag-groups
  11482          (or org-tag-groups-alist-for-agenda org-tag-groups-alist)))
  11483     (cond
  11484      (single-as-list (org--tags-expand-group (list match) tag-groups nil))
  11485      (org-group-tags
  11486       (let* ((case-fold-search t)
  11487 	     (tag-syntax org-mode-syntax-table)
  11488 	     (group-keys (mapcar #'car tag-groups))
  11489 	     (key-regexp (concat "\\([+-]?\\)" (regexp-opt group-keys 'words)))
  11490 	     (return-match match))
  11491 	;; Mark regexp-expressions in the match-expression so that we
  11492 	;; do not replace them later on.
  11493 	(let ((s 0))
  11494 	  (while (string-match "{.+?}" return-match s)
  11495 	    (setq s (match-end 0))
  11496 	    (add-text-properties
  11497 	     (match-beginning 0) (match-end 0) '(regexp t) return-match)))
  11498 	;; @ and _ are allowed as word-components in tags.
  11499 	(modify-syntax-entry ?@ "w" tag-syntax)
  11500 	(modify-syntax-entry ?_ "w" tag-syntax)
  11501 	;; For each tag token found in MATCH, compute a regexp and  it
  11502 	(with-syntax-table tag-syntax
  11503 	  (replace-regexp-in-string
  11504 	   key-regexp
  11505 	   (lambda (m)
  11506 	     (if (get-text-property (match-beginning 2) 'regexp m)
  11507 		 m			;regexp tag: ignore
  11508 	       (let* ((operator (match-string 1 m))
  11509 		      (tag-token (let ((tag (match-string 2 m)))
  11510 				   (list tag)))
  11511 		      regexp-tags regular-tags)
  11512 		 ;; Partition tags between regexp and regular tags.
  11513 		 ;; Remove curly bracket syntax from regexp tags.
  11514 		 (dolist (tag (org--tags-expand-group tag-token tag-groups nil))
  11515 		   (save-match-data
  11516 		     (if (string-match "{\\(.+?\\)}" tag)
  11517 			 (push (match-string 1 tag) regexp-tags)
  11518 		       (push tag regular-tags))))
  11519 		 ;; Replace tag token by the appropriate regexp.
  11520 		 ;; Regular tags need to be regexp-quoted, whereas
  11521 		 ;; regexp-tags are inserted as-is.
  11522 		 (let ((regular (regexp-opt regular-tags))
  11523 		       (regexp (mapconcat #'identity regexp-tags "\\|")))
  11524 		   (concat operator
  11525 			   (cond
  11526 			    ((null regular-tags) (format "{%s}" regexp))
  11527 			    ((null regexp-tags) (format "{\\<%s\\>}" regular))
  11528 			    (t (format "{\\<%s\\>\\|%s}" regular regexp))))))))
  11529 	   return-match
  11530 	   t t))))
  11531      (t match))))
  11532 
  11533 (defun org-op-to-function (op &optional stringp)
  11534   "Turn an operator into the appropriate function."
  11535   (setq op
  11536 	(cond
  11537 	 ((equal  op   "<"       ) '(<     org-string<  org-time<))
  11538 	 ((equal  op   ">"       ) '(>     org-string>  org-time>))
  11539 	 ((member op '("<=" "=<")) '(<=    org-string<= org-time<=))
  11540 	 ((member op '(">=" "=>")) '(>=    org-string>= org-time>=))
  11541 	 ((member op '("="  "==")) '(=     string=      org-time=))
  11542 	 ((member op '("<>" "!=")) '(/=    org-string<> org-time<>))))
  11543   (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
  11544 
  11545 (defvar org-add-colon-after-tag-completion nil)  ;; dynamically scoped param
  11546 (defvar org-tags-overlay (make-overlay 1 1))
  11547 (delete-overlay org-tags-overlay)
  11548 
  11549 (defun org-add-prop-inherited (s)
  11550   (add-text-properties 0 (length s) '(inherited t) s)
  11551   s)
  11552 
  11553 (defun org-toggle-tag (tag &optional onoff)
  11554   "Toggle the tag TAG for the current line.
  11555 If ONOFF is `on' or `off', don't toggle but set to this state."
  11556   (save-excursion
  11557     (org-back-to-heading t)
  11558     (let ((current
  11559 	   ;; Reverse the tags list so any new tag is appended to the
  11560 	   ;; current list of tags.
  11561 	   (nreverse (org-get-tags nil t)))
  11562 	  res)
  11563       (pcase onoff
  11564 	(`off (setq current (delete tag current)))
  11565 	((or `on (guard (not (member tag current))))
  11566 	 (setq res t)
  11567 	 (cl-pushnew tag current :test #'equal))
  11568 	(_ (setq current (delete tag current))))
  11569       (org-set-tags (nreverse current))
  11570       res)))
  11571 
  11572 (defun org--align-tags-here (to-col)
  11573   "Align tags on the current headline to TO-COL.
  11574 Assume point is on a headline.  Preserve point when aligning
  11575 tags."
  11576   (when (org-match-line org-tag-line-re)
  11577     (let* ((tags-start (match-beginning 1))
  11578 	   (blank-start (save-excursion
  11579 			  (goto-char tags-start)
  11580 			  (skip-chars-backward " \t")
  11581 			  (point)))
  11582 	   (new (max (if (>= to-col 0) to-col
  11583 		       (- (abs to-col) (string-width (match-string 1))))
  11584 		     ;; Introduce at least one space after the heading
  11585 		     ;; or the stars.
  11586 		     (save-excursion
  11587 		       (goto-char blank-start)
  11588 		       (1+ (current-column)))))
  11589 	   (current
  11590 	    (save-excursion (goto-char tags-start) (current-column)))
  11591 	   (origin (point-marker))
  11592 	   (column (current-column))
  11593 	   (in-blank? (and (> origin blank-start) (<= origin tags-start))))
  11594       (when (/= new current)
  11595 	(delete-region blank-start tags-start)
  11596 	(goto-char blank-start)
  11597 	(let ((indent-tabs-mode nil)) (indent-to new))
  11598 	;; Try to move back to original position.  If point was in the
  11599 	;; blanks before the tags, ORIGIN marker is of no use because
  11600 	;; it now points to BLANK-START.  Use COLUMN instead.
  11601 	(if in-blank? (org-move-to-column column) (goto-char origin))))))
  11602 
  11603 (defun org-set-tags-command (&optional arg)
  11604   "Set the tags for the current visible entry.
  11605 
  11606 When called with `\\[universal-argument]' prefix argument ARG, \
  11607 realign all tags
  11608 in the current buffer.
  11609 
  11610 When called with `\\[universal-argument] \\[universal-argument]' prefix argument, \
  11611 unconditionally do not
  11612 offer the fast tag selection interface.
  11613 
  11614 If a region is active, set tags in the region according to the
  11615 setting of `org-loop-over-headlines-in-active-region'.
  11616 
  11617 This function is for interactive use only;
  11618 in Lisp code use `org-set-tags' instead."
  11619   (interactive "P")
  11620   (let ((org-use-fast-tag-selection
  11621 	 (unless (equal '(16) arg) org-use-fast-tag-selection)))
  11622     (cond
  11623      ((equal '(4) arg) (org-align-tags t))
  11624      ((and (org-region-active-p) org-loop-over-headlines-in-active-region)
  11625       (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
  11626 		    'region-start-level 'region))
  11627             org-loop-over-headlines-in-active-region) ;  hint: infinite recursion.
  11628 	(org-map-entries
  11629 	 #'org-set-tags-command
  11630 	 nil cl
  11631 	 (lambda () (when (org-invisible-p) (org-end-of-subtree nil t))))))
  11632      (t
  11633       (save-excursion
  11634 	(org-back-to-heading)
  11635 	(let* ((all-tags (org-get-tags))
  11636                (local-table (or org-current-tag-alist (org-get-buffer-tags)))
  11637 	       (table (setq org-last-tags-completion-table
  11638                             (append
  11639                              ;; Put local tags in front.
  11640                              local-table
  11641                              (cl-set-difference
  11642 			      (org--tag-add-to-alist
  11643 			       (and org-complete-tags-always-offer-all-agenda-tags
  11644 				    (org-global-tags-completion-table
  11645 				     (org-agenda-files)))
  11646 			       local-table)
  11647                               local-table))))
  11648 	       (current-tags
  11649 		(cl-remove-if (lambda (tag) (get-text-property 0 'inherited tag))
  11650 			      all-tags))
  11651 	       (inherited-tags
  11652 		(cl-remove-if-not (lambda (tag) (get-text-property 0 'inherited tag))
  11653 				  all-tags))
  11654 	       (tags
  11655 		(replace-regexp-in-string
  11656 		 ;; Ignore all forbidden characters in tags.
  11657 		 "[^[:alnum:]_@#%]+" ":"
  11658 		 (if (or (eq t org-use-fast-tag-selection)
  11659 			 (and org-use-fast-tag-selection
  11660 			      (delq nil (mapcar #'cdr table))))
  11661 		     (org-fast-tag-selection
  11662 		      current-tags
  11663 		      inherited-tags
  11664 		      table
  11665 		      (and org-fast-tag-selection-include-todo org-todo-key-alist))
  11666 		   (let ((org-add-colon-after-tag-completion (< 1 (length table)))
  11667                          (crm-separator "[ \t]*:[ \t]*"))
  11668 		     (mapconcat #'identity
  11669                                 (completing-read-multiple
  11670 			         "Tags: "
  11671 			         org-last-tags-completion-table
  11672 			         nil nil (org-make-tag-string current-tags)
  11673 			         'org-tags-history)
  11674                                 ":"))))))
  11675 	  (org-set-tags tags)))))
  11676     ;; `save-excursion' may not replace the point at the right
  11677     ;; position.
  11678     (when (and (save-excursion (skip-chars-backward "*") (bolp))
  11679 	       (looking-at-p " "))
  11680       (forward-char))))
  11681 
  11682 (defun org-align-tags (&optional all)
  11683   "Align tags in current entry.
  11684 When optional argument ALL is non-nil, align all tags in the
  11685 visible part of the buffer."
  11686   (let ((get-indent-column
  11687 	 (lambda ()
  11688 	   (let ((offset (if (bound-and-true-p org-indent-mode)
  11689                              (save-excursion
  11690                                (org-back-to-heading-or-point-min)
  11691                                (length
  11692                                 (get-text-property
  11693                                  (line-end-position)
  11694                                  'line-prefix)))
  11695 			   0)))
  11696 	     (+ org-tags-column
  11697 		(if (> org-tags-column 0) (- offset) offset))))))
  11698     (if (and (not all) (org-at-heading-p))
  11699 	(org--align-tags-here (funcall get-indent-column))
  11700       (save-excursion
  11701 	(if all
  11702 	    (progn
  11703 	      (goto-char (point-min))
  11704 	      (while (re-search-forward org-tag-line-re nil t)
  11705 		(org--align-tags-here (funcall get-indent-column))))
  11706 	  (org-back-to-heading t)
  11707 	  (org--align-tags-here (funcall get-indent-column)))))))
  11708 
  11709 (defun org-set-tags (tags)
  11710   "Set the tags of the current entry to TAGS, replacing current tags.
  11711 
  11712 TAGS may be a tags string like \":aa:bb:cc:\", or a list of tags.
  11713 If TAGS is nil or the empty string, all tags are removed.
  11714 
  11715 This function assumes point is on a headline."
  11716   (org-with-wide-buffer
  11717    (org-fold-core-ignore-modifications
  11718      (let ((tags (pcase tags
  11719 		   ((pred listp) tags)
  11720 		   ((pred stringp) (split-string (org-trim tags) ":" t))
  11721 		   (_ (error "Invalid tag specification: %S" tags))))
  11722 	   (old-tags (org-get-tags nil t))
  11723 	   (tags-change? nil))
  11724        (when (functionp org-tags-sort-function)
  11725          (setq tags (sort tags org-tags-sort-function)))
  11726        (setq tags-change? (not (equal tags old-tags)))
  11727        (when tags-change?
  11728          ;; Delete previous tags and any trailing white space.
  11729          (goto-char (if (org-match-line org-tag-line-re) (match-beginning 1)
  11730 		      (line-end-position)))
  11731          (skip-chars-backward " \t")
  11732          (delete-region (point) (line-end-position))
  11733          ;; Deleting white spaces may break an otherwise empty headline.
  11734          ;; Re-introduce one space in this case.
  11735          (unless (org-at-heading-p) (insert " "))
  11736          (when tags
  11737 	   (save-excursion (insert-and-inherit " " (org-make-tag-string tags)))
  11738 	   ;; When text is being inserted on an invisible region
  11739 	   ;; boundary, it can be inadvertently sucked into
  11740 	   ;; invisibility.
  11741 	   (unless (org-invisible-p (line-beginning-position))
  11742 	     (org-fold-region (point) (line-end-position) nil 'outline))))
  11743        ;; Align tags, if any.
  11744        (when tags (org-align-tags))
  11745        (when tags-change? (run-hooks 'org-after-tags-change-hook))))))
  11746 
  11747 (defun org-change-tag-in-region (beg end tag off)
  11748   "Add or remove TAG for each entry in the region.
  11749 This works in the agenda, and also in an Org buffer."
  11750   (interactive
  11751    (list (region-beginning) (region-end)
  11752 	 (let ((org-last-tags-completion-table
  11753 		(if (derived-mode-p 'org-mode)
  11754 		    (org--tag-add-to-alist
  11755 		     (org-get-buffer-tags)
  11756 		     (org-global-tags-completion-table))
  11757 		  (org-global-tags-completion-table))))
  11758 	   (completing-read
  11759 	    "Tag: " org-last-tags-completion-table nil nil nil
  11760 	    'org-tags-history))
  11761 	 (progn
  11762 	   (message "[s]et or [r]emove? ")
  11763 	   (equal (read-char-exclusive) ?r))))
  11764   (deactivate-mark)
  11765   (let ((agendap (equal major-mode 'org-agenda-mode))
  11766 	l1 l2 m buf pos newhead (cnt 0))
  11767     (goto-char end)
  11768     (setq l2 (1- (org-current-line)))
  11769     (goto-char beg)
  11770     (setq l1 (org-current-line))
  11771     (cl-loop for l from l1 to l2 do
  11772 	     (org-goto-line l)
  11773 	     (setq m (get-text-property (point) 'org-hd-marker))
  11774 	     (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
  11775 		       (and agendap m))
  11776 	       (setq buf (if agendap (marker-buffer m) (current-buffer))
  11777 		     pos (if agendap m (point)))
  11778 	       (with-current-buffer buf
  11779 		 (save-excursion
  11780 		   (save-restriction
  11781 		     (goto-char pos)
  11782 		     (setq cnt (1+ cnt))
  11783 		     (org-toggle-tag tag (if off 'off 'on))
  11784 		     (setq newhead (org-get-heading)))))
  11785 	       (and agendap (org-agenda-change-all-lines newhead m))))
  11786     (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
  11787 
  11788 (defun org-tags-completion-function (string _predicate &optional flag)
  11789   "Complete tag STRING.
  11790 FLAG specifies the type of completion operation to perform.  This
  11791 function is passed as a collection function to `completing-read',
  11792 which see."
  11793   (let ((completion-ignore-case nil)	;tags are case-sensitive
  11794 	(confirm (lambda (x) (stringp (car x))))
  11795 	(prefix ""))
  11796     (when (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
  11797       (setq prefix (match-string 1 string))
  11798       (setq string (match-string 2 string)))
  11799     (pcase flag
  11800       (`t (all-completions string org-last-tags-completion-table confirm))
  11801       (`lambda (assoc string org-last-tags-completion-table)) ;exact match?
  11802       (`nil
  11803        (pcase (try-completion string org-last-tags-completion-table confirm)
  11804 	 ((and completion (pred stringp))
  11805 	  (concat prefix
  11806 		  completion
  11807 		  (if (and org-add-colon-after-tag-completion
  11808 			   (assoc completion org-last-tags-completion-table))
  11809 		      ":"
  11810 		    "")))
  11811 	 (completion completion)))
  11812       (_ nil))))
  11813 
  11814 (defun org-fast-tag-insert (kwd tags face &optional end)
  11815   "Insert KWD, and the TAGS, the latter with face FACE.
  11816 Also insert END."
  11817   (insert (format "%-12s" (concat kwd ":"))
  11818 	  (org-add-props (mapconcat 'identity tags " ") nil 'face face)
  11819 	  (or end "")))
  11820 
  11821 (defun org-fast-tag-show-exit (flag)
  11822   (save-excursion
  11823     (org-goto-line 3)
  11824     (when (re-search-forward "[ \t]+Next change exits" (line-end-position) t)
  11825       (replace-match ""))
  11826     (when flag
  11827       (end-of-line 1)
  11828       (org-move-to-column (- (window-width) 19) t)
  11829       (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
  11830 
  11831 (defun org-set-current-tags-overlay (current prefix)
  11832   "Add an overlay to CURRENT tag with PREFIX."
  11833   (let ((s (org-make-tag-string current)))
  11834     (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
  11835     (org-overlay-display org-tags-overlay (concat prefix s))))
  11836 
  11837 (defvar org-last-tag-selection-key nil)
  11838 (defun org-fast-tag-selection (current inherited table &optional todo-table)
  11839   "Fast tag selection with single keys.
  11840 CURRENT is the current list of tags in the headline, INHERITED is the
  11841 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
  11842 possibly with grouping information.  TODO-TABLE is a similar table with
  11843 TODO keywords, should these have keys assigned to them.
  11844 If the keys are nil, a-z are automatically assigned.
  11845 Returns the new tags string, or nil to not change the current settings."
  11846   (let* ((fulltable (append table todo-table))
  11847 	 (maxlen (if (null fulltable) 0
  11848 		   (apply #'max
  11849 			  (mapcar (lambda (x)
  11850 				    (if (stringp (car x)) (string-width (car x))
  11851 				      0))
  11852 				  fulltable))))
  11853 	 (buf (current-buffer))
  11854 	 (expert (eq org-fast-tag-selection-single-key 'expert))
  11855 	 (tab-tags nil)
  11856 	 (fwidth (+ maxlen 3 1 3))
  11857 	 (ncol (/ (- (window-width) 4) fwidth))
  11858 	 (i-face 'org-done)
  11859 	 (c-face 'org-todo)
  11860 	 tg cnt e c char c1 c2 ntable tbl rtn
  11861 	 ov-start ov-end ov-prefix
  11862 	 (exit-after-next org-fast-tag-selection-single-key)
  11863 	 (done-keywords org-done-keywords)
  11864 	 groups ingroup intaggroup)
  11865     (save-excursion
  11866       (beginning-of-line)
  11867       (if (looking-at org-tag-line-re)
  11868 	  (setq ov-start (match-beginning 1)
  11869 		ov-end (match-end 1)
  11870 		ov-prefix "")
  11871         (setq ov-start (1- (line-end-position))
  11872 	      ov-end (1+ ov-start))
  11873 	(skip-chars-forward "^\n\r")
  11874 	(setq ov-prefix
  11875 	      (concat
  11876 	       (buffer-substring (1- (point)) (point))
  11877 	       (if (> (current-column) org-tags-column)
  11878 		   " "
  11879 		 (make-string (- org-tags-column (current-column)) ?\ ))))))
  11880     (move-overlay org-tags-overlay ov-start ov-end)
  11881     (save-excursion
  11882       (save-window-excursion
  11883 	(if expert
  11884 	    (set-buffer (get-buffer-create " *Org tags*"))
  11885 	  (delete-other-windows)
  11886 	  (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
  11887 	  (org-switch-to-buffer-other-window " *Org tags*"))
  11888 	(erase-buffer)
  11889 	(setq-local org-done-keywords done-keywords)
  11890 	(org-fast-tag-insert "Inherited" inherited i-face "\n")
  11891 	(org-fast-tag-insert "Current" current c-face "\n\n")
  11892 	(org-fast-tag-show-exit exit-after-next)
  11893 	(org-set-current-tags-overlay current ov-prefix)
  11894 	(setq tbl fulltable char ?a cnt 0)
  11895 	(while (setq e (pop tbl))
  11896 	  (cond
  11897 	   ((eq (car e) :startgroup)
  11898 	    (push '() groups) (setq ingroup t)
  11899 	    (unless (zerop cnt)
  11900 	      (setq cnt 0)
  11901 	      (insert "\n"))
  11902 	    (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
  11903 	   ((eq (car e) :endgroup)
  11904 	    (setq ingroup nil cnt 0)
  11905 	    (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
  11906 	   ((eq (car e) :startgrouptag)
  11907 	    (setq intaggroup t)
  11908 	    (unless (zerop cnt)
  11909 	      (setq cnt 0)
  11910 	      (insert "\n"))
  11911 	    (insert "[ "))
  11912 	   ((eq (car e) :endgrouptag)
  11913 	    (setq intaggroup nil cnt 0)
  11914 	    (insert "]\n"))
  11915 	   ((equal e '(:newline))
  11916 	    (unless (zerop cnt)
  11917 	      (setq cnt 0)
  11918 	      (insert "\n")
  11919 	      (setq e (car tbl))
  11920 	      (while (equal (car tbl) '(:newline))
  11921 		(insert "\n")
  11922 		(setq tbl (cdr tbl)))))
  11923 	   ((equal e '(:grouptags))
  11924             (delete-char -3)
  11925             (insert " : "))
  11926 	   (t
  11927 	    (setq tg (copy-sequence (car e)) c2 nil)
  11928 	    (if (cdr e)
  11929 		(setq c (cdr e))
  11930 	      ;; automatically assign a character.
  11931 	      (setq c1 (string-to-char
  11932 			(downcase (substring
  11933 				   tg (if (= (string-to-char tg) ?@) 1 0)))))
  11934 	      (if (or (rassoc c1 ntable) (rassoc c1 table))
  11935 		  (while (or (rassoc char ntable) (rassoc char table))
  11936 		    (setq char (1+ char)))
  11937 		(setq c2 c1))
  11938 	      (setq c (or c2
  11939                           (if (> char ?~)
  11940                               ?\s
  11941                             char)))
  11942               ;; Consider characters A-Z after a-z.
  11943               (if (equal char ?z)
  11944                   (setq char ?A)))
  11945 	    (when ingroup (push tg (car groups)))
  11946 	    (setq tg (org-add-props tg nil 'face
  11947 				    (cond
  11948 				     ((not (assoc tg table))
  11949 				      (org-get-todo-face tg))
  11950 				     ((member tg current) c-face)
  11951 				     ((member tg inherited) i-face))))
  11952 	    (when (equal (caar tbl) :grouptags)
  11953 	      (org-add-props tg nil 'face 'org-tag-group))
  11954 	    (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert "  "))
  11955 	    (insert "[" c "] " tg (make-string
  11956 				   (- fwidth 4 (length tg)) ?\ ))
  11957 	    (push (cons tg c) ntable)
  11958 	    (when (= (cl-incf cnt) ncol)
  11959 	      (unless (memq (caar tbl) '(:endgroup :endgrouptag))
  11960 		(insert "\n")
  11961 		(when (or ingroup intaggroup) (insert "  ")))
  11962 	      (setq cnt 0)))))
  11963 	(setq ntable (nreverse ntable))
  11964 	(insert "\n")
  11965 	(goto-char (point-min))
  11966 	(unless expert (org-fit-window-to-buffer))
  11967 	(setq rtn
  11968 	      (catch 'exit
  11969 		(while t
  11970 		  (message "[a-z..]:toggle [SPC]:clear [RET]:accept [TAB]:edit [!] %sgroups%s"
  11971 			   (if (not groups) "no " "")
  11972 			   (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
  11973 		  (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
  11974 		  (setq org-last-tag-selection-key c)
  11975 		  (cond
  11976 		   ((= c ?\r) (throw 'exit t))
  11977 		   ((= c ?!)
  11978 		    (setq groups (not groups))
  11979 		    (goto-char (point-min))
  11980 		    (while (re-search-forward "[{}]" nil t) (replace-match " ")))
  11981 		   ((= c ?\C-c)
  11982 		    (if (not expert)
  11983 			(org-fast-tag-show-exit
  11984 			 (setq exit-after-next (not exit-after-next)))
  11985 		      (setq expert nil)
  11986 		      (delete-other-windows)
  11987 		      (set-window-buffer (split-window-vertically) " *Org tags*")
  11988 		      (org-switch-to-buffer-other-window " *Org tags*")
  11989 		      (org-fit-window-to-buffer)))
  11990 		   ((or (= c ?\C-g)
  11991 			(and (= c ?q) (not (rassoc c ntable))))
  11992 		    (delete-overlay org-tags-overlay)
  11993 		    (setq quit-flag t))
  11994 		   ((= c ?\ )
  11995 		    (setq current nil)
  11996 		    (when exit-after-next (setq exit-after-next 'now)))
  11997 		   ((= c ?\t)
  11998                     (condition-case nil
  11999                         (unless tab-tags
  12000                           (setq tab-tags
  12001                                 (delq nil
  12002                                       (mapcar (lambda (x)
  12003                                                 (let ((item (car-safe x)))
  12004                                                   (and (stringp item)
  12005                                                        (list item))))
  12006                                               (org--tag-add-to-alist
  12007                                                (with-current-buffer buf
  12008                                                  (org-get-buffer-tags))
  12009                                                table))))))
  12010                     (setq tg (completing-read "Tag: " tab-tags))
  12011 		    (when (string-match "\\S-" tg)
  12012 		      (cl-pushnew (list tg) tab-tags :test #'equal)
  12013 		      (if (member tg current)
  12014 			  (setq current (delete tg current))
  12015 			(push tg current)))
  12016 		    (when exit-after-next (setq exit-after-next 'now)))
  12017 		   ((setq e (rassoc c todo-table) tg (car e))
  12018 		    (with-current-buffer buf
  12019 		      (save-excursion (org-todo tg)))
  12020 		    (when exit-after-next (setq exit-after-next 'now)))
  12021 		   ((setq e (rassoc c ntable) tg (car e))
  12022 		    (if (member tg current)
  12023 			(setq current (delete tg current))
  12024 		      (cl-loop for g in groups do
  12025 			       (when (member tg g)
  12026 				 (dolist (x g) (setq current (delete x current)))))
  12027 		      (push tg current))
  12028 		    (when exit-after-next (setq exit-after-next 'now))))
  12029 
  12030 		  ;; Create a sorted list
  12031 		  (setq current
  12032 			(sort current
  12033 			      (lambda (a b)
  12034 				(assoc b (cdr (memq (assoc a ntable) ntable))))))
  12035 		  (when (eq exit-after-next 'now) (throw 'exit t))
  12036 		  (goto-char (point-min))
  12037 		  (beginning-of-line 2)
  12038                   (delete-region (point) (line-end-position))
  12039 		  (org-fast-tag-insert "Current" current c-face)
  12040 		  (org-set-current-tags-overlay current ov-prefix)
  12041 		  (let ((tag-re (concat "\\[.\\] \\(" org-tag-re "\\)")))
  12042 		    (while (re-search-forward tag-re nil t)
  12043 		      (let ((tag (match-string 1)))
  12044 			(add-text-properties
  12045 			 (match-beginning 1) (match-end 1)
  12046 			 (list 'face
  12047 			       (cond
  12048 				((member tag current) c-face)
  12049 				((member tag inherited) i-face)
  12050 				(t 'default)))))))
  12051 		  (goto-char (point-min)))))
  12052 	(delete-overlay org-tags-overlay)
  12053 	(if rtn
  12054 	    (mapconcat 'identity current ":")
  12055 	  nil)))))
  12056 
  12057 (defun org-make-tag-string (tags)
  12058   "Return string associated to TAGS.
  12059 TAGS is a list of strings."
  12060   (if (null tags) ""
  12061     (format ":%s:" (mapconcat #'identity tags ":"))))
  12062 
  12063 (defun org--get-local-tags ()
  12064   "Return list of tags for the current headline.
  12065 Assume point is at the beginning of the headline."
  12066   (let* ((cached (and (org-element--cache-active-p) (org-element-at-point nil 'cached)))
  12067          (cached-tags (org-element-property :tags cached)))
  12068     (if cached
  12069         ;; If we do not explicitly copy the result, reference would
  12070         ;; be returned and cache element might be modified directly.
  12071         (mapcar #'copy-sequence cached-tags)
  12072       ;; Parse tags manually.
  12073       (and (looking-at org-tag-line-re)
  12074            (split-string (match-string-no-properties 2) ":" t)))))
  12075 
  12076 (defun org-get-tags (&optional pos-or-element local)
  12077   "Get the list of tags specified in the current headline.
  12078 
  12079 When argument POS-OR-ELEMENT is non-nil, retrieve tags for headline at
  12080 POS.
  12081 
  12082 According to `org-use-tag-inheritance', tags may be inherited
  12083 from parent headlines, and from the whole document, through
  12084 `org-file-tags'.  In this case, the returned list of tags
  12085 contains tags in this order: file tags, tags inherited from
  12086 parent headlines, local tags.  If a tag appears multiple times,
  12087 only the most local tag is returned.
  12088 
  12089 However, when optional argument LOCAL is non-nil, only return
  12090 tags specified at the headline.
  12091 
  12092 Inherited tags have the `inherited' text property."
  12093   (save-match-data
  12094     (if (and org-trust-scanner-tags
  12095              (or (not pos-or-element) (eq pos-or-element (point)))
  12096              (not local))
  12097         org-scanner-tags
  12098       (org-with-point-at (unless (org-element-type pos-or-element)
  12099                         (or pos-or-element (point)))
  12100         (unless (or (org-element-type pos-or-element)
  12101                     (org-before-first-heading-p))
  12102           (org-back-to-heading t))
  12103         (let ((ltags (if (org-element-type pos-or-element)
  12104                          (org-element-property :tags (org-element-lineage pos-or-element '(headline inlinetask) t))
  12105                        (org--get-local-tags)))
  12106               itags)
  12107           (if (or local (not org-use-tag-inheritance)) ltags
  12108             (let ((cached (and (org-element--cache-active-p)
  12109                                (if (org-element-type pos-or-element)
  12110                                    (org-element-lineage pos-or-element '(headline org-data inlinetask) t)
  12111                                  (org-element-at-point nil 'cached)))))
  12112               (if cached
  12113                   (while (setq cached (org-element-property :parent cached))
  12114                     (setq itags (nconc (mapcar #'org-add-prop-inherited
  12115                                                ;; If we do explicitly copy the result, reference would
  12116                                                ;; be returned and cache element might be modified directly.
  12117                                                (mapcar #'copy-sequence (org-element-property :tags cached)))
  12118                                        itags)))
  12119                 (while (org-up-heading-safe)
  12120                   (setq itags (nconc (mapcar #'org-add-prop-inherited
  12121 					     (org--get-local-tags))
  12122 				     itags)))))
  12123             (setq itags (append org-file-tags itags))
  12124             (nreverse
  12125 	     (delete-dups
  12126 	      (nreverse (nconc (org-remove-uninherited-tags itags) ltags))))))))))
  12127 
  12128 (defun org-get-buffer-tags ()
  12129   "Get a table of all tags used in the buffer, for completion."
  12130   (if (org-element--cache-active-p)
  12131       ;; `org-element-cache-map' is about 2x faster compared to regexp
  12132       ;; search.
  12133       (let ((hashed (make-hash-table :test #'equal)))
  12134         (org-element-cache-map
  12135          (lambda (el)
  12136            (dolist (tag (org-element-property :tags el))
  12137              ;; Do not carry over the text properties.  They may look
  12138              ;; ugly in the completion.
  12139              (puthash (list (substring-no-properties tag)) t hashed))))
  12140         (dolist (tag org-file-tags) (puthash (list tag) t hashed))
  12141         (hash-table-keys hashed))
  12142     (org-with-point-at 1
  12143       (let (tags)
  12144         (while (re-search-forward org-tag-line-re nil t)
  12145 	  (setq tags (nconc (split-string (match-string-no-properties 2) ":")
  12146 			    tags)))
  12147         (mapcar #'list (delete-dups (append org-file-tags tags)))))))
  12148 
  12149 ;;;; The mapping API
  12150 
  12151 (defvar org-agenda-skip-comment-trees)
  12152 (defvar org-agenda-skip-function)
  12153 (defun org-map-entries (func &optional match scope &rest skip)
  12154   "Call FUNC at each headline selected by MATCH in SCOPE.
  12155 
  12156 FUNC is a function or a Lisp form.  The function will be called without
  12157 arguments, with the cursor positioned at the beginning of the headline.
  12158 The return values of all calls to the function will be collected and
  12159 returned as a list.
  12160 
  12161 The call to FUNC will be wrapped into a `save-excursion' form, so FUNC
  12162 does not need to preserve point.  After evaluation, the cursor will be
  12163 moved to the end of the line (presumably of the headline of the
  12164 processed entry) and search continues from there.  Under some
  12165 circumstances, this may not produce the wanted results.  For example,
  12166 if you have removed (e.g. archived) the current (sub)tree it could
  12167 mean that the next entry will be skipped entirely.  In such cases, you
  12168 can specify the position from where search should continue by making
  12169 FUNC set the variable `org-map-continue-from' to the desired buffer
  12170 position.
  12171 
  12172 MATCH is a tags/property/todo match as it is used in the agenda tags view.
  12173 Only headlines that are matched by this query will be considered during
  12174 the iteration.  When MATCH is nil or t, all headlines will be
  12175 visited by the iteration.
  12176 
  12177 SCOPE determines the scope of this command.  It can be any of:
  12178 
  12179 nil     The current buffer, respecting the restriction if any
  12180 tree    The subtree started with the entry at point
  12181 region  The entries within the active region, if any
  12182 region-start-level
  12183         The entries within the active region, but only those at
  12184         the same level than the first one.
  12185 file    The current buffer, without restriction
  12186 file-with-archives
  12187         The current buffer, and any archives associated with it
  12188 agenda  All agenda files
  12189 agenda-with-archives
  12190         All agenda files with any archive files associated with them
  12191 \(file1 file2 ...)
  12192         If this is a list, all files in the list will be scanned
  12193 
  12194 The remaining args are treated as settings for the skipping facilities of
  12195 the scanner.  The following items can be given here:
  12196 
  12197   archive    skip trees with the archive tag
  12198   comment    skip trees with the COMMENT keyword
  12199   function or Emacs Lisp form:
  12200              will be used as value for `org-agenda-skip-function', so
  12201              whenever the function returns a position, FUNC will not be
  12202              called for that entry and search will continue from the
  12203              position returned
  12204 
  12205 If your function needs to retrieve the tags including inherited tags
  12206 at the *current* entry, you can use the value of the variable
  12207 `org-scanner-tags' which will be much faster than getting the value
  12208 with `org-get-tags'.  If your function gets properties with
  12209 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
  12210 to t around the call to `org-entry-properties' to get the same speedup.
  12211 Note that if your function moves around to retrieve tags and properties at
  12212 a *different* entry, you cannot use these techniques."
  12213   (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
  12214 	       (not (org-region-active-p)))
  12215     (let* ((org-agenda-archives-mode nil) ; just to make sure
  12216 	   (org-agenda-skip-archived-trees (memq 'archive skip))
  12217 	   (org-agenda-skip-comment-trees (memq 'comment skip))
  12218 	   (org-agenda-skip-function
  12219 	    (car (org-delete-all '(comment archive) skip)))
  12220 	   (org-tags-match-list-sublevels t)
  12221 	   (start-level (eq scope 'region-start-level))
  12222 	   matcher res
  12223 	   org-todo-keywords-for-agenda
  12224 	   org-done-keywords-for-agenda
  12225 	   org-todo-keyword-alist-for-agenda
  12226 	   org-tag-alist-for-agenda
  12227 	   org--matcher-tags-todo-only)
  12228 
  12229       (cond
  12230        ((eq match t)   (setq matcher t))
  12231        ((eq match nil) (setq matcher t))
  12232        (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
  12233 
  12234       (save-excursion
  12235 	(save-restriction
  12236 	  (cond ((eq scope 'tree)
  12237 		 (org-back-to-heading t)
  12238 		 (org-narrow-to-subtree)
  12239 		 (setq scope nil))
  12240 		((and (or (eq scope 'region) (eq scope 'region-start-level))
  12241 		      (org-region-active-p))
  12242 		 ;; If needed, set start-level to a string like "2"
  12243 		 (when start-level
  12244 		   (save-excursion
  12245 		     (goto-char (region-beginning))
  12246 		     (unless (org-at-heading-p) (outline-next-heading))
  12247 		     (setq start-level (org-current-level))))
  12248 		 (narrow-to-region (region-beginning)
  12249 				   (save-excursion
  12250 				     (goto-char (region-end))
  12251 				     (unless (and (bolp) (org-at-heading-p))
  12252 				       (outline-next-heading))
  12253 				     (point)))
  12254 		 (setq scope nil)))
  12255 
  12256 	  (if (not scope)
  12257 	      (progn
  12258                 ;; Agenda expects a file buffer.  Skip over refreshing
  12259                 ;; agenda cache for non-file buffers.
  12260                 (when buffer-file-name
  12261 		  (org-agenda-prepare-buffers
  12262 		   (and buffer-file-name (list buffer-file-name))))
  12263 		(setq res
  12264 		      (org-scan-tags
  12265 		       func matcher org--matcher-tags-todo-only start-level)))
  12266 	    ;; Get the right scope
  12267 	    (cond
  12268 	     ((and scope (listp scope) (symbolp (car scope)))
  12269 	      (setq scope (eval scope t)))
  12270 	     ((eq scope 'agenda)
  12271 	      (setq scope (org-agenda-files t)))
  12272 	     ((eq scope 'agenda-with-archives)
  12273 	      (setq scope (org-agenda-files t))
  12274 	      (setq scope (org-add-archive-files scope)))
  12275 	     ((eq scope 'file)
  12276 	      (setq scope (and buffer-file-name (list buffer-file-name))))
  12277 	     ((eq scope 'file-with-archives)
  12278 	      (setq scope (org-add-archive-files (list (buffer-file-name))))))
  12279 	    (org-agenda-prepare-buffers scope)
  12280 	    (dolist (file scope)
  12281 	      (with-current-buffer (org-find-base-buffer-visiting file)
  12282 		(org-with-wide-buffer
  12283 		 (goto-char (point-min))
  12284 		 (setq res
  12285 		       (append
  12286 			res
  12287 			(org-scan-tags
  12288 			 func matcher org--matcher-tags-todo-only)))))))))
  12289       res)))
  12290 
  12291 ;;; Properties API
  12292 
  12293 (defconst org-special-properties
  12294   '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
  12295     "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
  12296   "The special properties valid in Org mode.
  12297 These are properties that are not defined in the property drawer,
  12298 but in some other way.")
  12299 
  12300 (defconst org-default-properties
  12301   '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
  12302     "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
  12303     "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
  12304     "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
  12305     "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
  12306     "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
  12307     "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS"
  12308     "ORG-IMAGE-ACTUAL-WIDTH")
  12309   "Some properties that are used by Org mode for various purposes.
  12310 Being in this list makes sure that they are offered for completion.")
  12311 
  12312 (defun org--valid-property-p (property)
  12313   "Non-nil when string PROPERTY is a valid property name."
  12314   (not
  12315    (or (equal property "")
  12316        (string-match-p "\\s-" property))))
  12317 
  12318 (defun org--update-property-plist (key val props)
  12319   "Associate KEY to VAL in alist PROPS.
  12320 Modifications are made by side-effect.  Return new alist."
  12321   (let* ((appending (string= (substring key -1) "+"))
  12322 	 (key (if appending (substring key 0 -1) key))
  12323 	 (old (assoc-string key props t)))
  12324     (if (not old) (cons (cons key val) props)
  12325       (setcdr old (if appending (concat (cdr old) " " val) val))
  12326       props)))
  12327 
  12328 (defun org-get-property-block (&optional beg force)
  12329   "Return the (beg . end) range of the body of the property drawer.
  12330 BEG is the beginning of the current subtree or the beginning of
  12331 the document if before the first headline.  If it is not given,
  12332 it will be found.  If the drawer does not exist, create it if
  12333 FORCE is non-nil, or return nil."
  12334   (org-with-wide-buffer
  12335    (let ((beg (cond (beg (goto-char beg))
  12336 		    ((or (not (featurep 'org-inlinetask))
  12337 			 (org-inlinetask-in-task-p))
  12338 		     (org-back-to-heading-or-point-min t) (point))
  12339 		    (t (org-with-limited-levels
  12340 			(org-back-to-heading-or-point-min t))
  12341 		       (point)))))
  12342      ;; Move point to its position according to its positional rules.
  12343      (cond ((org-before-first-heading-p)
  12344 	    (while (and (org-at-comment-p) (bolp)) (forward-line)))
  12345 	   (t (forward-line)
  12346 	      (when (looking-at-p org-planning-line-re) (forward-line))))
  12347      (cond ((looking-at org-property-drawer-re)
  12348 	    (forward-line)
  12349 	    (cons (point) (progn (goto-char (match-end 0))
  12350 				 (line-beginning-position))))
  12351 	   (force
  12352 	    (goto-char beg)
  12353 	    (org-insert-property-drawer)
  12354 	    (let ((pos (save-excursion (re-search-forward org-property-drawer-re)
  12355 				       (line-beginning-position))))
  12356 	      (cons pos pos)))))))
  12357 
  12358 (defun org-at-property-drawer-p ()
  12359   "Non-nil when point is at the first line of a property drawer."
  12360   (org-with-wide-buffer
  12361    (beginning-of-line)
  12362    (and (looking-at org-property-drawer-re)
  12363 	(or (bobp)
  12364 	    (progn
  12365 	      (forward-line -1)
  12366 	      (cond ((org-at-heading-p))
  12367 		    ((looking-at org-planning-line-re)
  12368 		     (forward-line -1)
  12369 		     (org-at-heading-p))
  12370 		    ((looking-at org-comment-regexp)
  12371 		     (forward-line -1)
  12372 		     (while (and (not (bobp)) (looking-at org-comment-regexp))
  12373 		       (forward-line -1))
  12374 		     (looking-at org-comment-regexp))
  12375 		    (t nil)))))))
  12376 
  12377 (defun org-at-property-p ()
  12378   "Non-nil when point is inside a property drawer.
  12379 See `org-property-re' for match data, if applicable."
  12380   (save-excursion
  12381     (beginning-of-line)
  12382     (and (looking-at org-property-re)
  12383 	 (let ((property-drawer (save-match-data (org-get-property-block))))
  12384 	   (and property-drawer
  12385 		(>= (point) (car property-drawer))
  12386 		(< (point) (cdr property-drawer)))))))
  12387 
  12388 (defun org-property-action ()
  12389   "Do an action on properties."
  12390   (interactive)
  12391   (message "Property Action:  [s]et  [d]elete  [D]elete globally  [c]ompute")
  12392   (let ((c (read-char-exclusive)))
  12393     (cl-case c
  12394       (?s (call-interactively #'org-set-property))
  12395       (?d (call-interactively #'org-delete-property))
  12396       (?D (call-interactively #'org-delete-property-globally))
  12397       (?c (call-interactively #'org-compute-property-at-point))
  12398       (otherwise (user-error "No such property action %c" c)))))
  12399 
  12400 (defun org-inc-effort ()
  12401   "Increment the value of the effort property in the current entry."
  12402   (interactive)
  12403   (org-set-effort t))
  12404 
  12405 (defvar org-clock-effort)       ; Defined in org-clock.el.
  12406 (defvar org-clock-current-task) ; Defined in org-clock.el.
  12407 (defun org-set-effort (&optional increment value)
  12408   "Set the effort property of the current entry.
  12409 If INCREMENT is non-nil, set the property to the next allowed
  12410 value.  Otherwise, if optional argument VALUE is provided, use
  12411 it.  Eventually, prompt for the new value if none of the previous
  12412 variables is set."
  12413   (interactive "P")
  12414   (let* ((allowed (org-property-get-allowed-values nil org-effort-property t))
  12415 	 (current (org-entry-get nil org-effort-property))
  12416 	 (value
  12417 	  (cond
  12418 	   (increment
  12419 	    (unless allowed (user-error "Allowed effort values are not set"))
  12420 	    (or (cl-caadr (member (list current) allowed))
  12421 		(user-error "Unknown value %S among allowed values" current)))
  12422 	   (value
  12423 	    (if (stringp value) value
  12424 	      (error "Invalid effort value: %S" value)))
  12425 	   (t
  12426 	    (let ((must-match
  12427 		   (and allowed
  12428 			(not (get-text-property 0 'org-unrestricted
  12429 						(caar allowed))))))
  12430 	      (completing-read "Effort: " allowed nil must-match))))))
  12431     ;; Test whether the value can be interpreted as a duration before
  12432     ;; inserting it in the buffer:
  12433     (org-duration-to-minutes value)
  12434     ;; Maybe update the effort value:
  12435     (unless (equal current value)
  12436       (org-entry-put nil org-effort-property value))
  12437     (unless (org-element--cache-active-p)
  12438       (org-refresh-property '((effort . identity)
  12439 			   (effort-minutes . org-duration-to-minutes))
  12440 		         value))
  12441     (when (equal (org-get-heading t t t t)
  12442 		 (bound-and-true-p org-clock-current-task))
  12443       (setq org-clock-effort value)
  12444       (org-clock-update-mode-line))
  12445     (message "%s is now %s" org-effort-property value)))
  12446 
  12447 (defun org-entry-properties (&optional pom which)
  12448   "Get all properties of the current entry.
  12449 
  12450 When POM is a buffer position, get all properties from the entry
  12451 there instead.
  12452 
  12453 This includes the TODO keyword, the tags, time strings for
  12454 deadline, scheduled, and clocking, and any additional properties
  12455 defined in the entry.
  12456 
  12457 If WHICH is nil or `all', get all properties.  If WHICH is
  12458 `special' or `standard', only get that subclass.  If WHICH is
  12459 a string, only get that property.
  12460 
  12461 Return value is an alist.  Keys are properties, as upcased
  12462 strings."
  12463   (org-with-point-at pom
  12464     (when (and (derived-mode-p 'org-mode)
  12465 	       (org-back-to-heading-or-point-min t))
  12466       (catch 'exit
  12467 	(let* ((beg (point))
  12468 	       (specific (and (stringp which) (upcase which)))
  12469 	       (which (cond ((not specific) which)
  12470 			    ((member specific org-special-properties) 'special)
  12471 			    (t 'standard)))
  12472 	       props)
  12473 	  ;; Get the special properties, like TODO and TAGS.
  12474 	  (when (memq which '(nil all special))
  12475 	    (when (or (not specific) (string= specific "CLOCKSUM"))
  12476 	      (let ((clocksum (get-text-property (point) :org-clock-minutes)))
  12477 		(when clocksum
  12478 		  (push (cons "CLOCKSUM" (org-duration-from-minutes clocksum))
  12479 			props)))
  12480 	      (when specific (throw 'exit props)))
  12481 	    (when (or (not specific) (string= specific "CLOCKSUM_T"))
  12482 	      (let ((clocksumt (get-text-property (point)
  12483 						  :org-clock-minutes-today)))
  12484 		(when clocksumt
  12485 		  (push (cons "CLOCKSUM_T"
  12486 			      (org-duration-from-minutes clocksumt))
  12487 			props)))
  12488 	      (when specific (throw 'exit props)))
  12489 	    (when (or (not specific) (string= specific "ITEM"))
  12490 	      (let ((case-fold-search nil))
  12491 		(when (looking-at org-complex-heading-regexp)
  12492 		  (push (cons "ITEM"
  12493 			      (let ((title (match-string-no-properties 4)))
  12494 				(if (org-string-nw-p title)
  12495 				    (org-remove-tabs title)
  12496 				  "")))
  12497 			props)))
  12498 	      (when specific (throw 'exit props)))
  12499 	    (when (or (not specific) (string= specific "TODO"))
  12500 	      (let ((case-fold-search nil))
  12501 		(when (and (looking-at org-todo-line-regexp) (match-end 2))
  12502 		  (push (cons "TODO" (match-string-no-properties 2)) props)))
  12503 	      (when specific (throw 'exit props)))
  12504 	    (when (or (not specific) (string= specific "PRIORITY"))
  12505 	      (push (cons "PRIORITY"
  12506 			  (if (looking-at org-priority-regexp)
  12507 			      (match-string-no-properties 2)
  12508 			    (char-to-string org-priority-default)))
  12509 		    props)
  12510 	      (when specific (throw 'exit props)))
  12511 	    (when (or (not specific) (string= specific "FILE"))
  12512 	      (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
  12513 		    props)
  12514 	      (when specific (throw 'exit props)))
  12515 	    (when (or (not specific) (string= specific "TAGS"))
  12516 	      (let ((tags (org-get-tags nil t)))
  12517 		(when tags
  12518 		  (push (cons "TAGS" (org-make-tag-string tags))
  12519 			props)))
  12520 	      (when specific (throw 'exit props)))
  12521 	    (when (or (not specific) (string= specific "ALLTAGS"))
  12522 	      (let ((tags (org-get-tags)))
  12523 		(when tags
  12524 		  (push (cons "ALLTAGS" (org-make-tag-string tags))
  12525 			props)))
  12526 	      (when specific (throw 'exit props)))
  12527 	    (when (or (not specific) (string= specific "BLOCKED"))
  12528 	      (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
  12529 	      (when specific (throw 'exit props)))
  12530 	    (when (or (not specific)
  12531 		      (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
  12532 	      (forward-line)
  12533 	      (when (looking-at-p org-planning-line-re)
  12534 		(end-of-line)
  12535 		(let ((bol (line-beginning-position))
  12536 		      ;; Backward compatibility: time keywords used to
  12537 		      ;; be configurable (before 8.3).  Make sure we
  12538 		      ;; get the correct keyword.
  12539 		      (key-assoc `(("CLOSED" . ,org-closed-string)
  12540 				   ("DEADLINE" . ,org-deadline-string)
  12541 				   ("SCHEDULED" . ,org-scheduled-string))))
  12542 		  (dolist (pair (if specific (list (assoc specific key-assoc))
  12543 				  key-assoc))
  12544 		    (save-excursion
  12545 		      (when (search-backward (cdr pair) bol t)
  12546 			(goto-char (match-end 0))
  12547 			(skip-chars-forward " \t")
  12548 			(and (looking-at org-ts-regexp-both)
  12549 			     (push (cons (car pair)
  12550 					 (match-string-no-properties 0))
  12551 				   props)))))))
  12552 	      (when specific (throw 'exit props)))
  12553 	    (when (or (not specific)
  12554 		      (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
  12555 	      (let ((find-ts
  12556 		     (lambda (end ts)
  12557 		       ;; Fix next time-stamp before END.  TS is the
  12558 		       ;; list of time-stamps found so far.
  12559 		       (let ((ts ts)
  12560 			     (regexp (cond
  12561 				      ((string= specific "TIMESTAMP")
  12562 				       org-ts-regexp)
  12563 				      ((string= specific "TIMESTAMP_IA")
  12564 				       org-ts-regexp-inactive)
  12565 				      ((assoc "TIMESTAMP_IA" ts)
  12566 				       org-ts-regexp)
  12567 				      ((assoc "TIMESTAMP" ts)
  12568 				       org-ts-regexp-inactive)
  12569 				      (t org-ts-regexp-both))))
  12570 			 (catch 'next
  12571 			   (while (re-search-forward regexp end t)
  12572 			     (backward-char)
  12573 			     (let ((object (org-element-context)))
  12574 			       ;; Accept to match timestamps in node
  12575 			       ;; properties, too.
  12576 			       (when (memq (org-element-type object)
  12577 					   '(node-property timestamp))
  12578 				 (let ((type
  12579 					(org-element-property :type object)))
  12580 				   (cond
  12581 				    ((and (memq type '(active active-range))
  12582 					  (not (equal specific "TIMESTAMP_IA")))
  12583 				     (unless (assoc "TIMESTAMP" ts)
  12584 				       (push (cons "TIMESTAMP"
  12585 						   (org-element-property
  12586 						    :raw-value object))
  12587 					     ts)
  12588 				       (when specific (throw 'exit ts))))
  12589 				    ((and (memq type '(inactive inactive-range))
  12590 					  (not (string= specific "TIMESTAMP")))
  12591 				     (unless (assoc "TIMESTAMP_IA" ts)
  12592 				       (push (cons "TIMESTAMP_IA"
  12593 						   (org-element-property
  12594 						    :raw-value object))
  12595 					     ts)
  12596 				       (when specific (throw 'exit ts))))))
  12597 				 ;; Both timestamp types are found,
  12598 				 ;; move to next part.
  12599 				 (when (= (length ts) 2) (throw 'next ts)))))
  12600 			   ts)))))
  12601 		(goto-char beg)
  12602 		;; First look for timestamps within headline.
  12603 		(let ((ts (funcall find-ts (line-end-position) nil)))
  12604 		  (if (= (length ts) 2) (setq props (nconc ts props))
  12605 		    ;; Then find timestamps in the section, skipping
  12606 		    ;; planning line.
  12607 		    (let ((end (save-excursion (outline-next-heading))))
  12608 		      (forward-line)
  12609 		      (when (looking-at-p org-planning-line-re) (forward-line))
  12610 		      (setq props (nconc (funcall find-ts end ts) props))))))))
  12611 	  ;; Get the standard properties, like :PROP:.
  12612 	  (when (memq which '(nil all standard))
  12613 	    ;; If we are looking after a specific property, delegate
  12614 	    ;; to `org-entry-get', which is faster.  However, make an
  12615 	    ;; exception for "CATEGORY", since it can be also set
  12616 	    ;; through keywords (i.e. #+CATEGORY).
  12617 	    (if (and specific (not (equal specific "CATEGORY")))
  12618 		(let ((value (org-entry-get beg specific nil t)))
  12619 		  (throw 'exit (and value (list (cons specific value)))))
  12620 	      (let ((range (org-get-property-block beg)))
  12621 		(when range
  12622 		  (let ((end (cdr range)) seen-base)
  12623 		    (goto-char (car range))
  12624 		    ;; Unlike to `org--update-property-plist', we
  12625 		    ;; handle the case where base values is found
  12626 		    ;; after its extension.  We also forbid standard
  12627 		    ;; properties to be named as special properties.
  12628 		    (while (re-search-forward org-property-re end t)
  12629 		      (let* ((key (upcase (match-string-no-properties 2)))
  12630 			     (extendp (string-match-p "\\+\\'" key))
  12631 			     (key-base (if extendp (substring key 0 -1) key))
  12632 			     (value (match-string-no-properties 3)))
  12633 			(cond
  12634 			 ((member-ignore-case key-base org-special-properties))
  12635 			 (extendp
  12636 			  (setq props
  12637 				(org--update-property-plist key value props)))
  12638 			 ((member key seen-base))
  12639 			 (t (push key seen-base)
  12640 			    (let ((p (assoc-string key props t)))
  12641 			      (if p (setcdr p (concat value " " (cdr p)))
  12642 				(push (cons key value) props))))))))))))
  12643 	  (unless (assoc "CATEGORY" props)
  12644 	    (push (cons "CATEGORY" (org-get-category beg)) props)
  12645 	    (when (string= specific "CATEGORY") (throw 'exit props)))
  12646 	  ;; Return value.
  12647 	  props)))))
  12648 
  12649 (defun org--property-local-values (property literal-nil &optional element)
  12650   "Return value for PROPERTY in current entry or ELEMENT.
  12651 Value is a list whose car is the base value for PROPERTY and cdr
  12652 a list of accumulated values.  Return nil if neither is found in
  12653 the entry.  Also return nil when PROPERTY is set to \"nil\",
  12654 unless LITERAL-NIL is non-nil."
  12655   (let ((element (or element
  12656                      (and (org-element--cache-active-p)
  12657                           (org-element-at-point nil 'cached)))))
  12658     (if element
  12659         (let* ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self))
  12660                (base-value (org-element-property (intern (concat ":" (upcase property))) element))
  12661                (base-value (if literal-nil base-value (org-not-nil base-value)))
  12662                (extra-value (org-element-property (intern (concat ":" (upcase property) "+")) element))
  12663                (extra-value (if (listp extra-value) extra-value (list extra-value)))
  12664                (value (cons base-value extra-value)))
  12665           (and (not (equal value '(nil))) value))
  12666       (let ((range (org-get-property-block)))
  12667         (when range
  12668           (goto-char (car range))
  12669           (let* ((case-fold-search t)
  12670 	         (end (cdr range))
  12671 	         (value
  12672 	          ;; Base value.
  12673 	          (save-excursion
  12674 		    (let ((v (and (re-search-forward
  12675 			           (org-re-property property nil t) end t)
  12676 			          (match-string-no-properties 3))))
  12677 		      (list (if literal-nil v (org-not-nil v)))))))
  12678 	    ;; Find additional values.
  12679 	    (let* ((property+ (org-re-property (concat property "+") nil t)))
  12680 	      (while (re-search-forward property+ end t)
  12681 	        (push (match-string-no-properties 3) value)))
  12682 	    ;; Return final values.
  12683 	    (and (not (equal value '(nil))) (nreverse value))))))))
  12684 
  12685 (defun org--property-global-or-keyword-value (property literal-nil)
  12686   "Return value for PROPERTY as defined by global properties or by keyword.
  12687 Return value is a string.  Return nil if property is not set
  12688 globally or by keyword.  Also return nil when PROPERTY is set to
  12689 \"nil\", unless LITERAL-NIL is non-nil."
  12690   (let ((global
  12691 	 (cdr (or (assoc-string property org-keyword-properties t)
  12692 		  (assoc-string property org-global-properties t)
  12693 		  (assoc-string property org-global-properties-fixed t)))))
  12694     (if literal-nil global (org-not-nil global))))
  12695 
  12696 (defun org-entry-get (pom property &optional inherit literal-nil)
  12697   "Get value of PROPERTY for entry or content at point-or-marker POM.
  12698 
  12699 If INHERIT is non-nil and the entry does not have the property,
  12700 then also check higher levels of the hierarchy.  If INHERIT is
  12701 the symbol `selective', use inheritance only if the setting in
  12702 `org-use-property-inheritance' selects PROPERTY for inheritance.
  12703 
  12704 If the property is present but empty, the return value is the
  12705 empty string.  If the property is not present at all, nil is
  12706 returned.  In any other case, return the value as a string.
  12707 Search is case-insensitive.
  12708 
  12709 If LITERAL-NIL is set, return the string value \"nil\" as
  12710 a string, do not interpret it as the list atom nil.  This is used
  12711 for inheritance when a \"nil\" value can supersede a non-nil
  12712 value higher up the hierarchy."
  12713   (org-with-point-at pom
  12714     (cond
  12715      ((member-ignore-case property (cons "CATEGORY" org-special-properties))
  12716       ;; We need a special property.  Use `org-entry-properties' to
  12717       ;; retrieve it, but specify the wanted property.
  12718       (cdr (assoc-string property (org-entry-properties nil property))))
  12719      ((and inherit
  12720 	   (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
  12721       (org-entry-get-with-inheritance property literal-nil))
  12722      (t
  12723       (let* ((local (org--property-local-values property literal-nil))
  12724 	     (value (and local (mapconcat #'identity
  12725                                           (delq nil local)
  12726                                           (org--property-get-separator property)))))
  12727 	(if literal-nil value (org-not-nil value)))))))
  12728 
  12729 (defun org-property-or-variable-value (var &optional inherit)
  12730   "Check if there is a property fixing the value of VAR.
  12731 If yes, return this value.  If not, return the current value of the variable."
  12732   (let ((prop (org-entry-get nil (symbol-name var) inherit)))
  12733     (if (and prop (stringp prop) (string-match "\\S-" prop))
  12734 	(read prop)
  12735       (symbol-value var))))
  12736 
  12737 (defun org-entry-delete (pom property)
  12738   "Delete PROPERTY from entry at point-or-marker POM.
  12739 Accumulated properties, i.e. PROPERTY+, are also removed.  Return
  12740 non-nil when a property was removed."
  12741   (org-with-point-at pom
  12742     (pcase (org-get-property-block)
  12743       (`(,begin . ,origin)
  12744        (let* ((end (copy-marker origin))
  12745 	      (re (org-re-property
  12746 		   (concat (regexp-quote property) "\\+?") t t)))
  12747 	 (goto-char begin)
  12748 	 (while (re-search-forward re end t)
  12749 	   (delete-region (match-beginning 0) (line-beginning-position 2)))
  12750 	 ;; If drawer is empty, remove it altogether.
  12751 	 (when (= begin end)
  12752 	   (delete-region (line-beginning-position 0)
  12753 			  (line-beginning-position 2)))
  12754 	 ;; Return non-nil if some property was removed.
  12755 	 (prog1 (/= end origin) (set-marker end nil))))
  12756       (_ nil))))
  12757 
  12758 ;; Multi-values properties are properties that contain multiple values
  12759 ;; These values are assumed to be single words, separated by whitespace.
  12760 (defun org-entry-add-to-multivalued-property (pom property value)
  12761   "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
  12762   (let* ((old (org-entry-get pom property))
  12763 	 (values (and old (split-string old))))
  12764     (setq value (org-entry-protect-space value))
  12765     (unless (member value values)
  12766       (setq values (append values (list value)))
  12767       (org-entry-put pom property (mapconcat #'identity values " ")))))
  12768 
  12769 (defun org-entry-remove-from-multivalued-property (pom property value)
  12770   "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
  12771   (let* ((old (org-entry-get pom property))
  12772 	 (values (and old (split-string old))))
  12773     (setq value (org-entry-protect-space value))
  12774     (when (member value values)
  12775       (setq values (delete value values))
  12776       (org-entry-put pom property (mapconcat #'identity values " ")))))
  12777 
  12778 (defun org-entry-member-in-multivalued-property (pom property value)
  12779   "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
  12780   (let* ((old (org-entry-get pom property))
  12781 	 (values (and old (split-string old))))
  12782     (setq value (org-entry-protect-space value))
  12783     (member value values)))
  12784 
  12785 (defun org-entry-get-multivalued-property (pom property)
  12786   "Return a list of values in a multivalued property."
  12787   (let* ((value (org-entry-get pom property))
  12788 	 (values (and value (split-string value))))
  12789     (mapcar #'org-entry-restore-space values)))
  12790 
  12791 (defun org-entry-put-multivalued-property (pom property &rest values)
  12792   "Set multivalued PROPERTY at point-or-marker POM to VALUES.
  12793 VALUES should be a list of strings.  Spaces will be protected."
  12794   (org-entry-put pom property (mapconcat #'org-entry-protect-space values " "))
  12795   (let* ((value (org-entry-get pom property))
  12796 	 (values (and value (split-string value))))
  12797     (mapcar #'org-entry-restore-space values)))
  12798 
  12799 (defun org-entry-protect-space (s)
  12800   "Protect spaces and newline in string S."
  12801   (while (string-match " " s)
  12802     (setq s (replace-match "%20" t t s)))
  12803   (while (string-match "\n" s)
  12804     (setq s (replace-match "%0A" t t s)))
  12805   s)
  12806 
  12807 (defun org-entry-restore-space (s)
  12808   "Restore spaces and newline in string S."
  12809   (while (string-match "%20" s)
  12810     (setq s (replace-match " " t t s)))
  12811   (while (string-match "%0A" s)
  12812     (setq s (replace-match "\n" t t s)))
  12813   s)
  12814 
  12815 (defvar org-entry-property-inherited-from (make-marker)
  12816   "Marker pointing to the entry from where a property was inherited.
  12817 Each call to `org-entry-get-with-inheritance' will set this marker to the
  12818 location of the entry where the inheritance search matched.  If there was
  12819 no match, the marker will point nowhere.
  12820 Note that also `org-entry-get' calls this function, if the INHERIT flag
  12821 is set.")
  12822 
  12823 (defun org-entry-get-with-inheritance (property &optional literal-nil element)
  12824   "Get PROPERTY of entry or content at point, search higher levels if needed.
  12825 The search will stop at the first ancestor which has the property defined.
  12826 If the value found is \"nil\", return nil to show that the property
  12827 should be considered as undefined (this is the meaning of nil here).
  12828 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
  12829   (move-marker org-entry-property-inherited-from nil)
  12830   (org-with-wide-buffer
  12831    (let (value at-bob-no-heading)
  12832      (catch 'exit
  12833        (let ((element (or element
  12834                           (and (org-element--cache-active-p)
  12835                                (org-element-at-point nil 'cached))))
  12836              (separator (org--property-get-separator property)))
  12837          (if element
  12838              (let ((element (org-element-lineage element '(headline org-data inlinetask) 'with-self)))
  12839                (while t
  12840                  (let* ((v (org--property-local-values property literal-nil element))
  12841                         (v (if (listp v) v (list v))))
  12842                    (when v
  12843                      (setq value
  12844                            (concat (mapconcat #'identity (delq nil v) separator)
  12845                                    (and value separator)
  12846                                    value)))
  12847                    (cond
  12848 	            ((car v)
  12849 	             (move-marker org-entry-property-inherited-from (org-element-property :begin element))
  12850 	             (throw 'exit nil))
  12851 	            ((org-element-property :parent element)
  12852                      (setq element (org-element-property :parent element)))
  12853 	            (t
  12854 	             (let ((global (org--property-global-or-keyword-value property literal-nil)))
  12855 	               (cond ((not global))
  12856 		             (value (setq value (concat global separator value)))
  12857 		             (t (setq value global))))
  12858 	             (throw 'exit nil))))))
  12859            (while t
  12860 	     (let ((v (org--property-local-values property literal-nil)))
  12861 	       (when v
  12862 	         (setq value
  12863 		       (concat (mapconcat #'identity (delq nil v) separator)
  12864 			       (and value separator)
  12865 			       value)))
  12866 	       (cond
  12867 	        ((car v)
  12868 	         (org-back-to-heading-or-point-min t)
  12869 	         (move-marker org-entry-property-inherited-from (point))
  12870 	         (throw 'exit nil))
  12871 	        ((or (org-up-heading-safe)
  12872                      (and (not (bobp))
  12873                           (goto-char (point-min))
  12874                           nil)
  12875                      ;; `org-up-heading-safe' returned nil.  We are at low
  12876                      ;; level heading or bob.  If there is headline
  12877                      ;; there, do not try to fetch its properties.
  12878                      (and (bobp)
  12879                           (not at-bob-no-heading)
  12880                           (not (org-at-heading-p))
  12881                           (setq at-bob-no-heading t))))
  12882 	        (t
  12883 	         (let ((global (org--property-global-or-keyword-value property literal-nil)))
  12884 	           (cond ((not global))
  12885 		         (value (setq value (concat global separator value)))
  12886 		         (t (setq value global))))
  12887 	         (throw 'exit nil))))))))
  12888      (if literal-nil value (org-not-nil value)))))
  12889 
  12890 (defvar org-property-changed-functions nil
  12891   "Hook called when the value of a property has changed.
  12892 Each hook function should accept two arguments, the name of the property
  12893 and the new value.")
  12894 
  12895 (defun org-entry-put (pom property value)
  12896   "Set PROPERTY to VALUE for entry at point-or-marker POM.
  12897 
  12898 If the value is nil, it is converted to the empty string.  If it
  12899 is not a string, an error is raised.  Also raise an error on
  12900 invalid property names.
  12901 
  12902 PROPERTY can be any regular property (see
  12903 `org-special-properties').  It can also be \"TODO\",
  12904 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
  12905 
  12906 For the last two properties, VALUE may have any of the special
  12907 values \"earlier\" and \"later\".  The function then increases or
  12908 decreases scheduled or deadline date by one day."
  12909   (cond ((null value) (setq value ""))
  12910 	((not (stringp value)) (error "Properties values should be strings"))
  12911 	((not (org--valid-property-p property))
  12912 	 (user-error "Invalid property name: \"%s\"" property)))
  12913   (org-no-read-only
  12914    (org-with-point-at pom
  12915      (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  12916 	 (org-back-to-heading-or-point-min t)
  12917        (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  12918      (let ((beg (point)))
  12919        (cond
  12920         ((equal property "TODO")
  12921 	 (cond ((not (org-string-nw-p value)) (setq value 'none))
  12922 	       ((not (member value org-todo-keywords-1))
  12923 	        (user-error "\"%s\" is not a valid TODO state" value)))
  12924 	 (org-todo value)
  12925 	 (org-align-tags))
  12926         ((equal property "PRIORITY")
  12927 	 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
  12928 	 (org-align-tags))
  12929         ((equal property "SCHEDULED")
  12930 	 (forward-line)
  12931 	 (if (and (looking-at-p org-planning-line-re)
  12932 		  (re-search-forward
  12933 		   org-scheduled-time-regexp (line-end-position) t))
  12934 	     (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12935 		   ((string= value "later") (org-timestamp-change 1 'day))
  12936 		   ((string= value "") (org-schedule '(4)))
  12937 		   (t (org-schedule nil value)))
  12938 	   (if (member value '("earlier" "later" ""))
  12939 	       (call-interactively #'org-schedule)
  12940 	     (org-schedule nil value))))
  12941         ((equal property "DEADLINE")
  12942 	 (forward-line)
  12943 	 (if (and (looking-at-p org-planning-line-re)
  12944 		  (re-search-forward
  12945 		   org-deadline-time-regexp (line-end-position) t))
  12946 	     (cond ((string= value "earlier") (org-timestamp-change -1 'day))
  12947 		   ((string= value "later") (org-timestamp-change 1 'day))
  12948 		   ((string= value "") (org-deadline '(4)))
  12949 		   (t (org-deadline nil value)))
  12950 	   (if (member value '("earlier" "later" ""))
  12951 	       (call-interactively #'org-deadline)
  12952 	     (org-deadline nil value))))
  12953         ((member property org-special-properties)
  12954 	 (error "The %s property cannot be set with `org-entry-put'" property))
  12955         (t
  12956          (org-fold-core-ignore-modifications
  12957 	   (let* ((range (org-get-property-block beg 'force))
  12958 	          (end (cdr range))
  12959 	          (case-fold-search t))
  12960 	     (goto-char (car range))
  12961 	     (if (re-search-forward (org-re-property property nil t) end t)
  12962 	         (progn (delete-region (match-beginning 0) (match-end 0))
  12963 		        (goto-char (match-beginning 0)))
  12964 	       (goto-char end)
  12965 	       (insert-and-inherit "\n")
  12966 	       (backward-char))
  12967 	     (insert-and-inherit ":" property ":")
  12968 	     (when value (insert-and-inherit " " value))
  12969 	     (org-indent-line))))))
  12970      (run-hook-with-args 'org-property-changed-functions property value))))
  12971 
  12972 (defun org-buffer-property-keys (&optional specials defaults columns)
  12973   "Get all property keys in the current buffer.
  12974 
  12975 When SPECIALS is non-nil, also list the special properties that
  12976 reflect things like tags and TODO state.
  12977 
  12978 When DEFAULTS is non-nil, also include properties that has
  12979 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
  12980 DESCRIPTION, LOCATION, and LOGGING and others.
  12981 
  12982 When COLUMNS in non-nil, also include property names given in
  12983 COLUMN formats in the current buffer."
  12984   (let ((case-fold-search t)
  12985 	(props (append
  12986 		(and specials org-special-properties)
  12987 		(and defaults (cons org-effort-property org-default-properties))
  12988 		;; Get property names from #+PROPERTY keywords as well
  12989 		(mapcar (lambda (s)
  12990 			  (nth 0 (split-string s)))
  12991 			(cdar (org-collect-keywords '("PROPERTY")))))))
  12992     (org-with-wide-buffer
  12993      (goto-char (point-min))
  12994      (while (re-search-forward org-property-start-re nil t)
  12995        (catch :skip
  12996 	 (let ((range (org-get-property-block)))
  12997 	   (unless range (throw :skip nil))
  12998 	   (goto-char (car range))
  12999 	   (let ((begin (car range))
  13000 		 (end (cdr range)))
  13001 	     ;; Make sure that found property block is not located
  13002 	     ;; before current point, as it would generate an infloop.
  13003 	     ;; It can happen, for example, in the following
  13004 	     ;; situation:
  13005 	     ;;
  13006 	     ;; * Headline
  13007 	     ;;   :PROPERTIES:
  13008 	     ;;   ...
  13009 	     ;;   :END:
  13010 	     ;; *************** Inlinetask
  13011 	     ;; #+BEGIN_EXAMPLE
  13012 	     ;; :PROPERTIES:
  13013 	     ;; #+END_EXAMPLE
  13014 	     ;;
  13015 	     (if (< begin (point)) (throw :skip nil) (goto-char begin))
  13016 	     (while (< (point) end)
  13017 	       (let ((p (progn (looking-at org-property-re)
  13018 			       (match-string-no-properties 2))))
  13019 		 ;; Only add true property name, not extension symbol.
  13020 		 (push (if (not (string-match-p "\\+\\'" p)) p
  13021 			 (substring p 0 -1))
  13022 		       props))
  13023 	       (forward-line))))
  13024 	 (outline-next-heading)))
  13025      (when columns
  13026        (goto-char (point-min))
  13027        (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
  13028 	 (let ((element (org-element-at-point)))
  13029 	   (when (memq (org-element-type element) '(keyword node-property))
  13030 	     (let ((value (org-element-property :value element))
  13031 		   (start 0))
  13032 	       (while (string-match "%[0-9]*\\([[:alnum:]_-]+\\)\\(([^)]+)\\)?\
  13033 \\(?:{[^}]+}\\)?"
  13034 				    value start)
  13035 		 (setq start (match-end 0))
  13036 		 (let ((p (match-string-no-properties 1 value)))
  13037 		   (unless (member-ignore-case p org-special-properties)
  13038 		     (push p props))))))))))
  13039     (sort (delete-dups
  13040 	   (append props
  13041 		   ;; for each xxx_ALL property, make sure the bare
  13042 		   ;; xxx property is also included
  13043 		   (delq nil (mapcar (lambda (p)
  13044 				       (and (string-match-p "._ALL\\'" p)
  13045 					    (substring p 0 -4)))
  13046 				     props))))
  13047 	  (lambda (a b) (string< (upcase a) (upcase b))))))
  13048 
  13049 (defun org-property-values (key)
  13050   "List all non-nil values of property KEY in current buffer."
  13051   (org-with-wide-buffer
  13052    (goto-char (point-min))
  13053    (let ((case-fold-search t)
  13054 	 (re (org-re-property key))
  13055 	 values)
  13056      (while (re-search-forward re nil t)
  13057        (push (org-entry-get (point) key) values))
  13058      (delete-dups values))))
  13059 
  13060 (defun org-insert-property-drawer ()
  13061   "Insert a property drawer into the current entry.
  13062 Do nothing if the drawer already exists.  The newly created
  13063 drawer is immediately hidden."
  13064   (org-with-wide-buffer
  13065    ;; Set point to the position where the drawer should be inserted.
  13066    (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
  13067        (org-back-to-heading-or-point-min t)
  13068      (org-with-limited-levels (org-back-to-heading-or-point-min t)))
  13069    (if (org-before-first-heading-p)
  13070        (while (and (org-at-comment-p) (bolp)) (forward-line))
  13071      (forward-line)
  13072      (when (looking-at-p org-planning-line-re) (forward-line)))
  13073    (unless (looking-at-p org-property-drawer-re)
  13074      ;; Make sure we start editing a line from current entry, not from
  13075      ;; next one.  It prevents extending text properties or overlays
  13076      ;; belonging to the latter.
  13077      (when (and (bolp) (> (point) (point-min))) (backward-char))
  13078      (let ((begin (if (bobp) (point) (1+ (point))))
  13079 	   (inhibit-read-only t))
  13080        (unless (bobp) (insert "\n"))
  13081        (insert ":PROPERTIES:\n:END:")
  13082        (org-fold-region (line-end-position 0) (point) t (if (eq org-fold-core-style 'text-properties) 'drawer 'outline))
  13083        (when (or (eobp) (= begin (point-min))) (insert "\n"))
  13084        (org-indent-region begin (point))))))
  13085 
  13086 (defun org-insert-drawer (&optional arg drawer)
  13087   "Insert a drawer at point.
  13088 
  13089 When optional argument ARG is non-nil, insert a property drawer.
  13090 
  13091 Optional argument DRAWER, when non-nil, is a string representing
  13092 drawer's name.  Otherwise, the user is prompted for a name.
  13093 
  13094 If a region is active, insert the drawer around that region
  13095 instead.
  13096 
  13097 Point is left between drawer's boundaries."
  13098   (interactive "P")
  13099   (let* ((drawer (if arg "PROPERTIES"
  13100 		   (or drawer (read-from-minibuffer "Drawer: ")))))
  13101     (cond
  13102      ;; With C-u, fall back on `org-insert-property-drawer'
  13103      (arg (org-insert-property-drawer))
  13104      ;; Check validity of suggested drawer's name.
  13105      ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
  13106       (user-error "Invalid drawer name"))
  13107      ;; With an active region, insert a drawer at point.
  13108      ((not (org-region-active-p))
  13109       (progn
  13110 	(unless (bolp) (insert "\n"))
  13111 	(insert (format ":%s:\n\n:END:\n" drawer))
  13112 	(forward-line -2)))
  13113      ;; Otherwise, insert the drawer at point
  13114      (t
  13115       (let ((rbeg (region-beginning))
  13116 	    (rend (copy-marker (region-end))))
  13117 	(unwind-protect
  13118 	    (progn
  13119 	      (goto-char rbeg)
  13120 	      (beginning-of-line)
  13121 	      (when (save-excursion
  13122 		      (re-search-forward org-outline-regexp-bol rend t))
  13123 		(user-error "Drawers cannot contain headlines"))
  13124 	      ;; Position point at the beginning of the first
  13125 	      ;; non-blank line in region.  Insert drawer's opening
  13126 	      ;; there, then indent it.
  13127 	      (org-skip-whitespace)
  13128 	      (beginning-of-line)
  13129 	      (insert ":" drawer ":\n")
  13130 	      (forward-line -1)
  13131 	      (indent-for-tab-command)
  13132 	      ;; Move point to the beginning of the first blank line
  13133 	      ;; after the last non-blank line in region.  Insert
  13134 	      ;; drawer's closing, then indent it.
  13135 	      (goto-char rend)
  13136 	      (skip-chars-backward " \r\t\n")
  13137 	      (insert "\n:END:")
  13138 	      (deactivate-mark t)
  13139 	      (indent-for-tab-command)
  13140 	      (unless (eolp) (insert "\n")))
  13141 	  ;; Clear marker, whatever the outcome of insertion is.
  13142 	  (set-marker rend nil)))))))
  13143 
  13144 (defvar org-property-set-functions-alist nil
  13145   "Property set function alist.
  13146 Each entry should have the following format:
  13147 
  13148  (PROPERTY . READ-FUNCTION)
  13149 
  13150 The read function will be called with the same argument as
  13151 `org-completing-read'.")
  13152 
  13153 (defun org-set-property-function (property)
  13154   "Get the function that should be used to set PROPERTY.
  13155 This is computed according to `org-property-set-functions-alist'."
  13156   (or (cdr (assoc property org-property-set-functions-alist))
  13157       'org-completing-read))
  13158 
  13159 (defun org-read-property-value (property &optional pom default)
  13160   "Read value for PROPERTY, as a string.
  13161 When optional argument POM is non-nil, completion uses additional
  13162 information, i.e., allowed or existing values at point or marker
  13163 POM.
  13164 Optional argument DEFAULT provides a default value for PROPERTY."
  13165   (let* ((completion-ignore-case t)
  13166 	 (allowed
  13167 	  (or (org-property-get-allowed-values nil property 'table)
  13168 	      (and pom (org-property-get-allowed-values pom property 'table))))
  13169 	 (current (org-entry-get nil property))
  13170 	 (prompt (format "%s value%s: "
  13171 			 property
  13172 			 (if (org-string-nw-p current)
  13173 			     (format " [%s]" current)
  13174 			   "")))
  13175 	 (set-function (org-set-property-function property)))
  13176     (org-trim
  13177      (if allowed
  13178 	 (funcall set-function
  13179 		  prompt allowed nil
  13180 		  (not (get-text-property 0 'org-unrestricted (caar allowed)))
  13181 		  default nil default)
  13182        (let ((all (mapcar #'list
  13183 			  (append (org-property-values property)
  13184 				  (and pom
  13185 				       (org-with-point-at pom
  13186 					 (org-property-values property)))))))
  13187 	 (funcall set-function prompt all nil nil "" nil current))))))
  13188 
  13189 (defvar org-last-set-property nil)
  13190 (defvar org-last-set-property-value nil)
  13191 (defun org-read-property-name ()
  13192   "Read a property name."
  13193   (let ((completion-ignore-case t)
  13194 	(default-prop (or (and (org-at-property-p)
  13195 			       (match-string-no-properties 2))
  13196 			  org-last-set-property)))
  13197     (org-completing-read
  13198      (concat "Property"
  13199 	     (if default-prop (concat " [" default-prop "]") "")
  13200 	     ": ")
  13201      (mapcar #'list (org-buffer-property-keys nil t t))
  13202      nil nil nil nil default-prop)))
  13203 
  13204 (defun org-set-property-and-value (use-last)
  13205   "Allow to set [PROPERTY]: [value] direction from prompt.
  13206 When use-default, don't even ask, just use the last
  13207 \"[PROPERTY]: [value]\" string from the history."
  13208   (interactive "P")
  13209   (let* ((completion-ignore-case t)
  13210 	 (pv (or (and use-last org-last-set-property-value)
  13211 		 (org-completing-read
  13212 		  "Enter a \"[Property]: [value]\" pair: "
  13213 		  nil nil nil nil nil
  13214 		  org-last-set-property-value)))
  13215 	 prop val)
  13216     (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
  13217       (setq prop (match-string 1 pv)
  13218 	    val (match-string 2 pv))
  13219       (org-set-property prop val))))
  13220 
  13221 (defun org-set-property (property value)
  13222   "In the current entry, set PROPERTY to VALUE.
  13223 
  13224 When called interactively, this will prompt for a property name, offering
  13225 completion on existing and default properties.  And then it will prompt
  13226 for a value, offering completion either on allowed values (via an inherited
  13227 xxx_ALL property) or on existing values in other instances of this property
  13228 in the current file.
  13229 
  13230 Throw an error when trying to set a property with an invalid name."
  13231   (interactive (list nil nil))
  13232   (let ((property (or property (org-read-property-name))))
  13233     ;; `org-entry-put' also makes the following check, but this one
  13234     ;; avoids polluting `org-last-set-property' and
  13235     ;; `org-last-set-property-value' needlessly.
  13236     (unless (org--valid-property-p property)
  13237       (user-error "Invalid property name: \"%s\"" property))
  13238     (let ((value (or value (org-read-property-value property)))
  13239 	  (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
  13240       (setq org-last-set-property property)
  13241       (setq org-last-set-property-value (concat property ": " value))
  13242       ;; Possibly postprocess the inserted value:
  13243       (when fn (setq value (funcall fn value)))
  13244       (unless (equal (org-entry-get nil property) value)
  13245 	(org-entry-put nil property value)))))
  13246 
  13247 (defun org-find-property (property &optional value)
  13248   "Find first entry in buffer that sets PROPERTY.
  13249 
  13250 When optional argument VALUE is non-nil, only consider an entry
  13251 if it contains PROPERTY set to this value.  If PROPERTY should be
  13252 explicitly set to nil, use string \"nil\" for VALUE.
  13253 
  13254 Return position where the entry begins, or nil if there is no
  13255 such entry.  If narrowing is in effect, only search the visible
  13256 part of the buffer."
  13257   (save-excursion
  13258     (goto-char (point-min))
  13259     (let ((case-fold-search t)
  13260 	  (re (org-re-property property nil (not value) value)))
  13261       (catch 'exit
  13262 	(while (re-search-forward re nil t)
  13263 	  (when (if value (org-at-property-p)
  13264 		  (org-entry-get (point) property nil t))
  13265 	    (throw 'exit (progn (org-back-to-heading-or-point-min t)
  13266 				(point)))))))))
  13267 
  13268 (defun org-delete-property (property)
  13269   "In the current entry, delete PROPERTY."
  13270   (interactive
  13271    (let* ((completion-ignore-case t)
  13272 	  (cat (org-entry-get (point) "CATEGORY"))
  13273 	  (props0 (org-entry-properties nil 'standard))
  13274 	  (props (if cat props0
  13275 		   (delete `("CATEGORY" . ,(org-get-category)) props0)))
  13276 	  (prop (if (< 1 (length props))
  13277 		    (completing-read "Property: " props nil t)
  13278 		  (caar props))))
  13279      (list prop)))
  13280   (if (not property)
  13281       (message "No property to delete in this entry")
  13282     (org-entry-delete nil property)
  13283     (message "Property \"%s\" deleted" property)))
  13284 
  13285 (defun org-delete-property-globally (property)
  13286   "Remove PROPERTY globally, from all entries.
  13287 This function ignores narrowing, if any."
  13288   (interactive
  13289    (let* ((completion-ignore-case t)
  13290 	  (prop (completing-read
  13291 		 "Globally remove property: "
  13292 		 (mapcar #'list (org-buffer-property-keys)))))
  13293      (list prop)))
  13294   (org-with-wide-buffer
  13295    (goto-char (point-min))
  13296    (let ((count 0)
  13297 	 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
  13298      (while (re-search-forward re nil t)
  13299        (when (org-entry-delete (point) property) (cl-incf count)))
  13300      (message "Property \"%s\" removed from %d entries" property count))))
  13301 
  13302 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
  13303 
  13304 (defun org-compute-property-at-point ()
  13305   "Compute the property at point.
  13306 This looks for an enclosing column format, extracts the operator and
  13307 then applies it to the property in the column format's scope."
  13308   (interactive)
  13309   (unless (org-at-property-p)
  13310     (user-error "Not at a property"))
  13311   (let ((prop (match-string-no-properties 2)))
  13312     (org-columns-get-format-and-top-level)
  13313     (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
  13314       (user-error "No operator defined for property %s" prop))
  13315     (org-columns-compute prop)))
  13316 
  13317 (defvar org-property-allowed-value-functions nil
  13318   "Hook for functions supplying allowed values for a specific property.
  13319 The functions must take a single argument, the name of the property, and
  13320 return a flat list of allowed values.  If \":ETC\" is one of
  13321 the values, this means that these values are intended as defaults for
  13322 completion, but that other values should be allowed too.
  13323 The functions must return nil if they are not responsible for this
  13324 property.")
  13325 
  13326 (defun org-property-get-allowed-values (pom property &optional table)
  13327   "Get allowed values for the property PROPERTY.
  13328 When TABLE is non-nil, return an alist that can directly be used for
  13329 completion."
  13330   (let (vals)
  13331     (cond
  13332      ((equal property "TODO")
  13333       (setq vals (org-with-point-at pom
  13334 		   (append org-todo-keywords-1 '("")))))
  13335      ((equal property "PRIORITY")
  13336       (let ((n org-priority-lowest))
  13337 	(while (>= n org-priority-highest)
  13338 	  (push (char-to-string n) vals)
  13339 	  (setq n (1- n)))))
  13340      ((equal property "CATEGORY"))
  13341      ((member property org-special-properties))
  13342      ((setq vals (run-hook-with-args-until-success
  13343 		  'org-property-allowed-value-functions property)))
  13344      (t
  13345       (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
  13346       (when (and vals (string-match "\\S-" vals))
  13347 	(setq vals (car (read-from-string (concat "(" vals ")"))))
  13348 	(setq vals (mapcar (lambda (x)
  13349 			     (cond ((stringp x) x)
  13350 				   ((numberp x) (number-to-string x))
  13351 				   ((symbolp x) (symbol-name x))
  13352 				   (t "???")))
  13353 			   vals)))))
  13354     (when (member ":ETC" vals)
  13355       (setq vals (remove ":ETC" vals))
  13356       (org-add-props (car vals) '(org-unrestricted t)))
  13357     (if table (mapcar 'list vals) vals)))
  13358 
  13359 (defun org-property-previous-allowed-value (&optional _previous)
  13360   "Switch to the next allowed value for this property."
  13361   (interactive)
  13362   (org-property-next-allowed-value t))
  13363 
  13364 (defun org-property-next-allowed-value (&optional previous)
  13365   "Switch to the next allowed value for this property."
  13366   (interactive)
  13367   (unless (org-at-property-p)
  13368     (user-error "Not at a property"))
  13369   (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
  13370 	 (key (match-string 2))
  13371 	 (value (match-string 3))
  13372 	 (allowed (or (org-property-get-allowed-values (point) key)
  13373 		      (and (member value  '("[ ]" "[-]" "[X]"))
  13374 			   '("[ ]" "[X]"))))
  13375 	 (heading (save-match-data (nth 4 (org-heading-components))))
  13376 	 nval)
  13377     (unless allowed
  13378       (user-error "Allowed values for this property have not been defined"))
  13379     (when previous (setq allowed (reverse allowed)))
  13380     (when (member value allowed)
  13381       (setq nval (car (cdr (member value allowed)))))
  13382     (setq nval (or nval (car allowed)))
  13383     (when (equal nval value)
  13384       (user-error "Only one allowed value for this property"))
  13385     (org-at-property-p)
  13386     (replace-match (concat " :" key ": " nval) t t)
  13387     (org-indent-line)
  13388     (beginning-of-line 1)
  13389     (skip-chars-forward " \t")
  13390     (when (equal prop org-effort-property)
  13391       (unless (org-element--cache-active-p)
  13392         (org-refresh-property
  13393          '((effort . identity)
  13394 	   (effort-minutes . org-duration-to-minutes))
  13395          nval))
  13396       (when (string= org-clock-current-task heading)
  13397 	(setq org-clock-effort nval)
  13398 	(org-clock-update-mode-line)))
  13399     (run-hook-with-args 'org-property-changed-functions key nval)))
  13400 
  13401 (defun org-find-olp (path &optional this-buffer)
  13402   "Return a marker pointing to the entry at outline path OLP.
  13403 If anything goes wrong, throw an error, and if you need to do
  13404 something based on this error, you can catch it with
  13405 `condition-case'.
  13406 
  13407 If THIS-BUFFER is set, the outline path does not contain a file,
  13408 only headings."
  13409   (let* ((file (if this-buffer buffer-file-name (pop path)))
  13410 	 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
  13411 	 (level 1)
  13412 	 (lmin 1)
  13413 	 (lmax 1)
  13414 	 end found flevel)
  13415     (unless buffer (error "File not found :%s" file))
  13416     (with-current-buffer buffer
  13417       (unless (derived-mode-p 'org-mode)
  13418 	(error "Buffer %s needs to be in Org mode" buffer))
  13419       (org-with-wide-buffer
  13420        (goto-char (point-min))
  13421        (dolist (heading path)
  13422 	 (let ((re (format org-complex-heading-regexp-format
  13423 			   (regexp-quote heading)))
  13424 	       (cnt 0))
  13425 	   (while (re-search-forward re end t)
  13426 	     (setq level (- (match-end 1) (match-beginning 1)))
  13427 	     (when (and (>= level lmin) (<= level lmax))
  13428 	       (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
  13429 	   (when (= cnt 0)
  13430 	     (error "Heading not found on level %d: %s" lmax heading))
  13431 	   (when (> cnt 1)
  13432 	     (error "Heading not unique on level %d: %s" lmax heading))
  13433 	   (goto-char found)
  13434 	   (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
  13435 	   (setq end (save-excursion (org-end-of-subtree t t)))))
  13436        (when (org-at-heading-p)
  13437 	 (point-marker))))))
  13438 
  13439 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
  13440   "Find node HEADING in BUFFER.
  13441 Return a marker to the heading if it was found, or nil if not.
  13442 If POS-ONLY is set, return just the position instead of a marker.
  13443 
  13444 The heading text must match exact, but it may have a TODO keyword,
  13445 a priority cookie and tags in the standard locations."
  13446   (with-current-buffer (or buffer (current-buffer))
  13447     (org-with-wide-buffer
  13448      (goto-char (point-min))
  13449      (let (case-fold-search)
  13450        (when (re-search-forward
  13451 	      (format org-complex-heading-regexp-format
  13452 		      (regexp-quote heading)) nil t)
  13453 	 (if pos-only
  13454 	     (match-beginning 0)
  13455 	   (move-marker (make-marker) (match-beginning 0))))))))
  13456 
  13457 (defun org-find-exact-heading-in-directory (heading &optional dir)
  13458   "Find Org node headline HEADING in all \".org\" files in directory DIR.
  13459 When the target headline is found, return a marker to this location."
  13460   (let ((files (directory-files (or dir default-directory)
  13461 				t "\\`[^.#].*\\.org\\'"))
  13462 	visiting m buffer)
  13463     (catch 'found
  13464       (dolist (file files)
  13465         (message "trying %s" file)
  13466         (setq visiting (org-find-base-buffer-visiting file))
  13467         (setq buffer (or visiting (find-file-noselect file)))
  13468         (setq m (org-find-exact-headline-in-buffer
  13469                  heading buffer))
  13470         (when (and (not m) (not visiting)) (kill-buffer buffer))
  13471         (and m (throw 'found m))))))
  13472 
  13473 (defun org-find-entry-with-id (ident)
  13474   "Locate the entry that contains the ID property with exact value IDENT.
  13475 IDENT can be a string, a symbol or a number, this function will search for
  13476 the string representation of it.
  13477 Return the position where this entry starts, or nil if there is no such entry."
  13478   (interactive "sID: ")
  13479   (let ((id (cond
  13480 	     ((stringp ident) ident)
  13481 	     ((symbolp ident) (symbol-name ident))
  13482 	     ((numberp ident) (number-to-string ident))
  13483 	     (t (error "IDENT %s must be a string, symbol or number" ident)))))
  13484     (org-with-wide-buffer (org-find-property "ID" id))))
  13485 
  13486 ;;;; Timestamps
  13487 
  13488 (defvar org-last-changed-timestamp nil)
  13489 (defvar org-last-inserted-timestamp nil
  13490   "The last time stamp inserted with `org-insert-time-stamp'.")
  13491 
  13492 (defun org-time-stamp (arg &optional inactive)
  13493   "Prompt for a date/time and insert a time stamp.
  13494 
  13495 If the user specifies a time like HH:MM or if this command is
  13496 called with at least one prefix argument, the time stamp contains
  13497 the date and the time.  Otherwise, only the date is included.
  13498 
  13499 All parts of a date not specified by the user are filled in from
  13500 the timestamp at point, if any, or the current date/time
  13501 otherwise.
  13502 
  13503 If there is already a timestamp at the cursor, it is replaced.
  13504 
  13505 With two universal prefix arguments, insert an active timestamp
  13506 with the current time without prompting the user.
  13507 
  13508 When called from Lisp, the timestamp is inactive if INACTIVE is
  13509 non-nil."
  13510   (interactive "P")
  13511   (let* ((ts (cond
  13512 	      ((org-at-date-range-p t)
  13513 	       (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
  13514 	      ((org-at-timestamp-p 'lax) (match-string 0))))
  13515 	 ;; Default time is either the timestamp at point or today.
  13516 	 ;; When entering a range, only the range start is considered.
  13517          (default-time (and ts (org-time-string-to-time ts)))
  13518          (default-input (and ts (org-get-compact-tod ts)))
  13519          (repeater (and ts
  13520 			(string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
  13521 			(match-string 0 ts)))
  13522 	 org-time-was-given
  13523 	 org-end-time-was-given
  13524 	 (time
  13525 	  (if (equal arg '(16)) (current-time)
  13526 	    ;; Preserve `this-command' and `last-command'.
  13527 	    (let ((this-command this-command)
  13528 		  (last-command last-command))
  13529 	      (org-read-date
  13530 	       arg 'totime nil nil default-time default-input
  13531 	       inactive)))))
  13532     (cond
  13533      ((and ts
  13534            (memq last-command '(org-time-stamp org-time-stamp-inactive))
  13535            (memq this-command '(org-time-stamp org-time-stamp-inactive)))
  13536       (insert "--")
  13537       (org-insert-time-stamp time (or org-time-was-given arg) inactive))
  13538      (ts
  13539       ;; Make sure we're on a timestamp.  When in the middle of a date
  13540       ;; range, move arbitrarily to range end.
  13541       (unless (org-at-timestamp-p 'lax)
  13542 	(skip-chars-forward "-")
  13543 	(org-at-timestamp-p 'lax))
  13544       (replace-match "")
  13545       (setq org-last-changed-timestamp
  13546 	    (org-insert-time-stamp
  13547 	     time (or org-time-was-given arg)
  13548 	     inactive nil nil (list org-end-time-was-given)))
  13549       (when repeater
  13550 	(backward-char)
  13551 	(insert " " repeater)
  13552 	(setq org-last-changed-timestamp
  13553 	      (concat (substring org-last-inserted-timestamp 0 -1)
  13554 		      " " repeater ">")))
  13555       (message "Timestamp updated"))
  13556      ((equal arg '(16)) (org-insert-time-stamp time t inactive))
  13557      (t (org-insert-time-stamp
  13558 	 time (or org-time-was-given arg) inactive nil nil
  13559 	 (list org-end-time-was-given))))))
  13560 
  13561 ;; FIXME: can we use this for something else, like computing time differences?
  13562 (defun org-get-compact-tod (s)
  13563   (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
  13564     (let* ((t1 (match-string 1 s))
  13565 	   (h1 (string-to-number (match-string 2 s)))
  13566 	   (m1 (string-to-number (match-string 3 s)))
  13567 	   (t2 (and (match-end 4) (match-string 5 s)))
  13568 	   (h2 (and t2 (string-to-number (match-string 6 s))))
  13569 	   (m2 (and t2 (string-to-number (match-string 7 s))))
  13570 	   dh dm)
  13571       (if (not t2)
  13572 	  t1
  13573 	(setq dh (- h2 h1) dm (- m2 m1))
  13574 	(when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
  13575 	(concat t1 "+" (number-to-string dh)
  13576 		(and (/= 0 dm) (format ":%02d" dm)))))))
  13577 
  13578 (defun org-time-stamp-inactive (&optional arg)
  13579   "Insert an inactive time stamp.
  13580 
  13581 An inactive time stamp is enclosed in square brackets instead of
  13582 angle brackets.  It is inactive in the sense that it does not
  13583 trigger agenda entries.  So these are more for recording a
  13584 certain time/date.
  13585 
  13586 If the user specifies a time like HH:MM or if this command is called with
  13587 at least one prefix argument, the time stamp contains the date and the time.
  13588 Otherwise, only the date is included.
  13589 
  13590 When called with two universal prefix arguments, insert an inactive time stamp
  13591 with the current time without prompting the user."
  13592   (interactive "P")
  13593   (org-time-stamp arg 'inactive))
  13594 
  13595 (defvar org-date-ovl (make-overlay 1 1))
  13596 (overlay-put org-date-ovl 'face 'org-date-selected)
  13597 (delete-overlay org-date-ovl)
  13598 
  13599 (defvar org-ans1) ; dynamically scoped parameter
  13600 (defvar org-ans2) ; dynamically scoped parameter
  13601 
  13602 (defvar org-plain-time-of-day-regexp) ; defined below
  13603 
  13604 (defvar org-overriding-default-time nil) ; dynamically scoped
  13605 (defvar org-read-date-overlay nil)
  13606 (defvar org-read-date-history nil)
  13607 (defvar org-read-date-final-answer nil)
  13608 (defvar org-read-date-analyze-futurep nil)
  13609 (defvar org-read-date-analyze-forced-year nil)
  13610 (defvar org-read-date-inactive)
  13611 (defvar org-def)
  13612 (defvar org-defdecode)
  13613 (defvar org-with-time)
  13614 
  13615 (defvar calendar-setup)			; Dynamically scoped.
  13616 (defun org-read-date (&optional with-time to-time from-string prompt
  13617 				default-time default-input inactive)
  13618   "Read a date, possibly a time, and make things smooth for the user.
  13619 The prompt will suggest to enter an ISO date, but you can also enter anything
  13620 which will at least partially be understood by `parse-time-string'.
  13621 Unrecognized parts of the date will default to the current day, month, year,
  13622 hour and minute.  If this command is called to replace a timestamp at point,
  13623 or to enter the second timestamp of a range, the default time is taken
  13624 from the existing stamp.  Furthermore, the command prefers the future,
  13625 so if you are giving a date where the year is not given, and the day-month
  13626 combination is already past in the current year, it will assume you
  13627 mean next year.  For details, see the manual.  A few examples:
  13628 
  13629   3-2-5         --> 2003-02-05
  13630   feb 15        --> currentyear-02-15
  13631   2/15          --> currentyear-02-15
  13632   sep 12 9      --> 2009-09-12
  13633   12:45         --> today 12:45
  13634   22 sept 0:34  --> currentyear-09-22 0:34
  13635   12            --> currentyear-currentmonth-12
  13636   Fri           --> nearest Friday after today
  13637   -Tue          --> last Tuesday
  13638   etc.
  13639 
  13640 Furthermore you can specify a relative date by giving, as the *first* thing
  13641 in the input:  a plus/minus sign, a number and a letter [hdwmy] to indicate
  13642 change in days weeks, months, years.
  13643 With a single plus or minus, the date is relative to today.  With a double
  13644 plus or minus, it is relative to the date in DEFAULT-TIME.  E.g.
  13645   +4d           --> four days from today
  13646   +4            --> same as above
  13647   +2w           --> two weeks from today
  13648   ++5           --> five days from default date
  13649 
  13650 The function understands only English month and weekday abbreviations.
  13651 
  13652 While prompting, a calendar is popped up - you can also select the
  13653 date with the mouse (button 1).  The calendar shows a period of three
  13654 months.  To scroll it to other months, use the keys `>' and `<'.
  13655 There are many other calendar navigation commands available, see
  13656 Info node `(org) The date/time prompt' for a full list.
  13657 
  13658 If you don't like the calendar, turn it off with
  13659        (setq org-read-date-popup-calendar nil)
  13660 
  13661 With optional argument TO-TIME, the date will immediately be converted
  13662 to an internal time.
  13663 With an optional argument WITH-TIME, the prompt will suggest to
  13664 also insert a time.  Note that when WITH-TIME is not set, you can
  13665 still enter a time, and this function will inform the calling routine
  13666 about this change.  The calling routine may then choose to change the
  13667 format used to insert the time stamp into the buffer to include the time.
  13668 With optional argument FROM-STRING, read from this string instead from
  13669 the user.  PROMPT can overwrite the default prompt.  DEFAULT-TIME is
  13670 the time/date that is used for everything that is not specified by the
  13671 user."
  13672   (require 'parse-time)
  13673   (let* ((org-with-time with-time)
  13674 	 (org-time-stamp-rounding-minutes
  13675 	  (if (equal org-with-time '(16))
  13676 	      '(0 0)
  13677 	    org-time-stamp-rounding-minutes))
  13678 	 (ct (org-current-time))
  13679 	 (org-def (or org-overriding-default-time default-time ct))
  13680 	 (org-defdecode (decode-time org-def))
  13681          (cur-frame (selected-frame))
  13682 	 (mouse-autoselect-window nil)	; Don't let the mouse jump
  13683 	 (calendar-setup
  13684 	  (and (eq calendar-setup 'calendar-only) 'calendar-only))
  13685 	 (calendar-move-hook nil)
  13686 	 (calendar-view-diary-initially-flag nil)
  13687 	 (calendar-view-holidays-initially-flag nil)
  13688 	 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
  13689     ;; Rationalize `org-def' and `org-defdecode', if required.
  13690     (when (< (nth 2 org-defdecode) org-extend-today-until)
  13691       (setf (nth 2 org-defdecode) -1)
  13692       (setf (nth 1 org-defdecode) 59)
  13693       (setq org-def (org-encode-time org-defdecode))
  13694       (setq org-defdecode (decode-time org-def)))
  13695     (let* ((timestr (format-time-string
  13696 		     (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
  13697 		     org-def))
  13698 	   (prompt (concat (if prompt (concat prompt " ") "")
  13699 			   (format "Date+time [%s]: " timestr))))
  13700       (cond
  13701        (from-string (setq ans from-string))
  13702        (org-read-date-popup-calendar
  13703 	(save-excursion
  13704 	  (save-window-excursion
  13705 	    (calendar)
  13706 	    (when (eq calendar-setup 'calendar-only)
  13707 	      (setq cal-frame
  13708 		    (window-frame (get-buffer-window "*Calendar*" 'visible)))
  13709 	      (select-frame cal-frame))
  13710 	    (org-eval-in-calendar '(setq cursor-type nil) t)
  13711 	    (unwind-protect
  13712 		(progn
  13713 		  (calendar-forward-day (- (time-to-days org-def)
  13714 					   (calendar-absolute-from-gregorian
  13715 					    (calendar-current-date))))
  13716 		  (org-eval-in-calendar nil t)
  13717 		  (let* ((old-map (current-local-map))
  13718 			 (map (copy-keymap calendar-mode-map))
  13719 			 (minibuffer-local-map
  13720 			  (copy-keymap org-read-date-minibuffer-local-map)))
  13721 		    (org-defkey map (kbd "RET") 'org-calendar-select)
  13722 		    (org-defkey map [mouse-1] 'org-calendar-select-mouse)
  13723 		    (org-defkey map [mouse-2] 'org-calendar-select-mouse)
  13724 		    (unwind-protect
  13725 			(progn
  13726 			  (use-local-map map)
  13727 			  (setq org-read-date-inactive inactive)
  13728 			  (add-hook 'post-command-hook 'org-read-date-display)
  13729 			  (setq org-ans0
  13730 				(read-string prompt
  13731 					     default-input
  13732 					     'org-read-date-history
  13733 					     nil))
  13734 			  ;; org-ans0: from prompt
  13735 			  ;; org-ans1: from mouse click
  13736 			  ;; org-ans2: from calendar motion
  13737 			  (setq ans
  13738 				(concat org-ans0 " " (or org-ans1 org-ans2))))
  13739 		      (remove-hook 'post-command-hook 'org-read-date-display)
  13740 		      (use-local-map old-map)
  13741 		      (when org-read-date-overlay
  13742 			(delete-overlay org-read-date-overlay)
  13743 			(setq org-read-date-overlay nil)))))
  13744 	      (bury-buffer "*Calendar*")
  13745 	      (when cal-frame
  13746 		(delete-frame cal-frame)
  13747 		(select-frame-set-input-focus cur-frame))))))
  13748 
  13749        (t				; Naked prompt only
  13750 	(unwind-protect
  13751 	    (setq ans (read-string prompt default-input
  13752 				   'org-read-date-history timestr))
  13753 	  (when org-read-date-overlay
  13754 	    (delete-overlay org-read-date-overlay)
  13755 	    (setq org-read-date-overlay nil))))))
  13756 
  13757     (setq final (org-read-date-analyze ans org-def org-defdecode))
  13758 
  13759     (when org-read-date-analyze-forced-year
  13760       (message "Year was forced into %s"
  13761 	       (if org-read-date-force-compatible-dates
  13762 		   "compatible range (1970-2037)"
  13763 		 "range representable on this machine"))
  13764       (ding))
  13765 
  13766     (setq final (org-encode-time final))
  13767 
  13768     (setq org-read-date-final-answer ans)
  13769 
  13770     (if to-time
  13771 	final
  13772       ;; This round-trip gets rid of 34th of August and stuff like that....
  13773       (setq final (decode-time final))
  13774       (if (and (boundp 'org-time-was-given) org-time-was-given)
  13775 	  (format "%04d-%02d-%02d %02d:%02d"
  13776 		  (nth 5 final) (nth 4 final) (nth 3 final)
  13777 		  (nth 2 final) (nth 1 final))
  13778 	(format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
  13779 
  13780 (defun org-read-date-display ()
  13781   "Display the current date prompt interpretation in the minibuffer."
  13782   (when org-read-date-display-live
  13783     (when org-read-date-overlay
  13784       (delete-overlay org-read-date-overlay))
  13785     (when (minibufferp (current-buffer))
  13786       (save-excursion
  13787 	(end-of-line 1)
  13788 	(while (not (equal (buffer-substring
  13789 			  (max (point-min) (- (point) 4)) (point))
  13790 			 "    "))
  13791 	  (insert " ")))
  13792       (let* ((ans (concat (buffer-substring (line-beginning-position)
  13793                                             (point-max))
  13794 			  " " (or org-ans1 org-ans2)))
  13795 	     (org-end-time-was-given nil)
  13796 	     (f (org-read-date-analyze ans org-def org-defdecode))
  13797 	     (fmt (org-time-stamp-format
  13798                    (or org-with-time
  13799                        (and (boundp 'org-time-was-given) org-time-was-given))
  13800                    org-read-date-inactive
  13801                    org-display-custom-times))
  13802 	     (txt (format-time-string fmt (org-encode-time f)))
  13803 	     (txt (concat "=> " txt)))
  13804 	(when (and org-end-time-was-given
  13805 		   (string-match org-plain-time-of-day-regexp txt))
  13806 	  (setq txt (concat (substring txt 0 (match-end 0)) "-"
  13807 			    org-end-time-was-given
  13808 			    (substring txt (match-end 0)))))
  13809 	(when org-read-date-analyze-futurep
  13810 	  (setq txt (concat txt " (=>F)")))
  13811 	(setq org-read-date-overlay
  13812               (make-overlay (1- (line-end-position)) (line-end-position)))
  13813 	(org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
  13814 
  13815 (defun org-read-date-analyze (ans def defdecode)
  13816   "Analyze the combined answer of the date prompt."
  13817   ;; FIXME: cleanup and comment
  13818   (let ((org-def def)
  13819 	(org-defdecode defdecode)
  13820 	(nowdecode (decode-time))
  13821 	delta deltan deltaw deltadef year month day
  13822 	hour minute second wday pm h2 m2 tl wday1
  13823 	iso-year iso-weekday iso-week iso-date futurep kill-year)
  13824     (setq org-read-date-analyze-futurep nil
  13825 	  org-read-date-analyze-forced-year nil)
  13826     (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
  13827       (setq ans "+0"))
  13828 
  13829     (when (setq delta (org-read-date-get-relative ans nil org-def))
  13830       (setq ans (replace-match "" t t ans)
  13831 	    deltan (car delta)
  13832 	    deltaw (nth 1 delta)
  13833 	    deltadef (nth 2 delta)))
  13834 
  13835     ;; Check if there is an iso week date in there.  If yes, store the
  13836     ;; info and postpone interpreting it until the rest of the parsing
  13837     ;; is done.
  13838     (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
  13839       (setq iso-year (when (match-end 1)
  13840 		       (org-small-year-to-year
  13841 			(string-to-number (match-string 1 ans))))
  13842 	    iso-weekday (when (match-end 3)
  13843 			  (string-to-number (match-string 3 ans)))
  13844 	    iso-week (string-to-number (match-string 2 ans)))
  13845       (setq ans (replace-match "" t t ans)))
  13846 
  13847     ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
  13848     (when (string-match
  13849 	   "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
  13850       (setq year (if (match-end 2)
  13851 		     (string-to-number (match-string 2 ans))
  13852 		   (progn (setq kill-year t)
  13853 			  (string-to-number (format-time-string "%Y"))))
  13854 	    month (string-to-number (match-string 3 ans))
  13855 	    day (string-to-number (match-string 4 ans)))
  13856       (setq year (org-small-year-to-year year))
  13857       (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13858 			       t nil ans)))
  13859 
  13860     ;; Help matching dotted european dates
  13861     (when (string-match
  13862 	   "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
  13863       (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
  13864 		   (setq kill-year t)
  13865 		   (string-to-number (format-time-string "%Y")))
  13866 	    day (string-to-number (match-string 1 ans))
  13867 	    month (string-to-number (match-string 2 ans))
  13868 	    ans (replace-match (format "%04d-%02d-%02d" year month day)
  13869 			       t nil ans)))
  13870 
  13871     ;; Help matching american dates, like 5/30 or 5/30/7
  13872     (when (string-match
  13873 	   "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
  13874       (setq year (if (match-end 4)
  13875 		     (string-to-number (match-string 4 ans))
  13876 		   (progn (setq kill-year t)
  13877 			  (string-to-number (format-time-string "%Y"))))
  13878 	    month (string-to-number (match-string 1 ans))
  13879 	    day (string-to-number (match-string 2 ans)))
  13880       (setq year (org-small-year-to-year year))
  13881       (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
  13882 			       t nil ans)))
  13883     ;; Help matching am/pm times, because `parse-time-string' does not do that.
  13884     ;; If there is a time with am/pm, and *no* time without it, we convert
  13885     ;; so that matching will be successful.
  13886     (cl-loop for i from 1 to 2 do	; twice, for end time as well
  13887 	     (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13888 			(string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
  13889 	       (setq hour (string-to-number (match-string 1 ans))
  13890 		     minute (if (match-end 3)
  13891 				(string-to-number (match-string 3 ans))
  13892 			      0)
  13893 		     pm (equal ?p
  13894 			       (string-to-char (downcase (match-string 4 ans)))))
  13895 	       (if (and (= hour 12) (not pm))
  13896 		   (setq hour 0)
  13897 		 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
  13898 	       (setq ans (replace-match (format "%02d:%02d" hour minute)
  13899 					t t ans))))
  13900 
  13901     ;; Help matching HHhMM times, similarly as for am/pm times.
  13902     (cl-loop for i from 1 to 2 do	; twice, for end time as well
  13903 	     (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
  13904 			(string-match "\\(?:\\(?1:[012]?[0-9]\\)?h\\(?2:[0-5][0-9]\\)\\)\\|\\(?:\\(?1:[012]?[0-9]\\)h\\(?2:[0-5][0-9]\\)?\\)\\>" ans))
  13905 	       (setq hour (if (match-end 1)
  13906 			      (string-to-number (match-string 1 ans))
  13907 			    0)
  13908 		     minute (if (match-end 2)
  13909 				(string-to-number (match-string 2 ans))
  13910 			      0))
  13911 	       (setq ans (replace-match (format "%02d:%02d" hour minute)
  13912 					t t ans))))
  13913 
  13914     ;; Check if a time range is given as a duration
  13915     (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
  13916       (setq hour (string-to-number (match-string 1 ans))
  13917 	    h2 (+ hour (string-to-number (match-string 3 ans)))
  13918 	    minute (string-to-number (match-string 2 ans))
  13919 	    m2 (+ minute (if (match-end 5) (string-to-number
  13920 					    (match-string 5 ans))0)))
  13921       (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
  13922       (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
  13923 			       t t ans)))
  13924 
  13925     ;; Check if there is a time range
  13926     (when (boundp 'org-end-time-was-given)
  13927       (setq org-time-was-given nil)
  13928       (when (and (string-match org-plain-time-of-day-regexp ans)
  13929 		 (match-end 8))
  13930 	(setq org-end-time-was-given (match-string 8 ans))
  13931 	(setq ans (concat (substring ans 0 (match-beginning 7))
  13932 			  (substring ans (match-end 7))))))
  13933 
  13934     (setq tl (parse-time-string ans)
  13935 	  day (or (nth 3 tl) (nth 3 org-defdecode))
  13936 	  month
  13937 	  (cond ((nth 4 tl))
  13938 		((not org-read-date-prefer-future) (nth 4 org-defdecode))
  13939 		;; Day was specified.  Make sure DAY+MONTH
  13940 		;; combination happens in the future.
  13941 		((nth 3 tl)
  13942 		 (setq futurep t)
  13943 		 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
  13944 		   (nth 4 nowdecode)))
  13945 		(t (nth 4 org-defdecode)))
  13946 	  year
  13947 	  (cond ((and (not kill-year) (nth 5 tl)))
  13948 		((not org-read-date-prefer-future) (nth 5 org-defdecode))
  13949 		;; Month was guessed in the future and is at least
  13950 		;; equal to NOWDECODE's.  Fix year accordingly.
  13951 		(futurep
  13952 		 (if (or (> month (nth 4 nowdecode))
  13953 			 (>= day (nth 3 nowdecode)))
  13954 		     (nth 5 nowdecode)
  13955 		   (1+ (nth 5 nowdecode))))
  13956 		;; Month was specified.  Make sure MONTH+YEAR
  13957 		;; combination happens in the future.
  13958 		((nth 4 tl)
  13959 		 (setq futurep t)
  13960 		 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
  13961 		       ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
  13962 		       ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
  13963 		       (t (nth 5 nowdecode))))
  13964 		(t (nth 5 org-defdecode)))
  13965 	  hour (or (nth 2 tl) (nth 2 org-defdecode))
  13966 	  minute (or (nth 1 tl) (nth 1 org-defdecode))
  13967 	  second (or (nth 0 tl) 0)
  13968 	  wday (nth 6 tl))
  13969 
  13970     (when (and (eq org-read-date-prefer-future 'time)
  13971 	       (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
  13972 	       (equal day (nth 3 nowdecode))
  13973 	       (equal month (nth 4 nowdecode))
  13974 	       (equal year (nth 5 nowdecode))
  13975 	       (nth 2 tl)
  13976 	       (or (< (nth 2 tl) (nth 2 nowdecode))
  13977 		   (and (= (nth 2 tl) (nth 2 nowdecode))
  13978 			(nth 1 tl)
  13979 			(< (nth 1 tl) (nth 1 nowdecode)))))
  13980       (setq day (1+ day)
  13981 	    futurep t))
  13982 
  13983     ;; Special date definitions below
  13984     (cond
  13985      (iso-week
  13986       ;; There was an iso week
  13987       (require 'cal-iso)
  13988       (setq futurep nil)
  13989       (setq year (or iso-year year)
  13990 	    day (or iso-weekday wday 1)
  13991 	    wday nil ; to make sure that the trigger below does not match
  13992 	    iso-date (calendar-gregorian-from-absolute
  13993 		      (calendar-iso-to-absolute
  13994 		       (list iso-week day year))))
  13995 					; FIXME:  Should we also push ISO weeks into the future?
  13996 					;      (when (and org-read-date-prefer-future
  13997 					;		 (not iso-year)
  13998 					;		 (< (calendar-absolute-from-gregorian iso-date)
  13999 					;		    (time-to-days nil)))
  14000 					;	(setq year (1+ year)
  14001 					;	      iso-date (calendar-gregorian-from-absolute
  14002 					;			(calendar-iso-to-absolute
  14003 					;			 (list iso-week day year)))))
  14004       (setq month (car iso-date)
  14005 	    year (nth 2 iso-date)
  14006 	    day (nth 1 iso-date)))
  14007      (deltan
  14008       (setq futurep nil)
  14009       (unless deltadef
  14010 	(let ((now (decode-time)))
  14011 	  (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
  14012       (cond ((member deltaw '("h" ""))
  14013              (when (boundp 'org-time-was-given)
  14014                (setq org-time-was-given t))
  14015              (setq hour (+ hour deltan)))
  14016             ((member deltaw '("d" "")) (setq day (+ day deltan)))
  14017             ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
  14018             ((equal deltaw "m") (setq month (+ month deltan)))
  14019             ((equal deltaw "y") (setq year (+ year deltan)))))
  14020      ((and wday (not (nth 3 tl)))
  14021       ;; Weekday was given, but no day, so pick that day in the week
  14022       ;; on or after the derived date.
  14023       (setq wday1 (nth 6 (decode-time (org-encode-time 0 0 0 day month year))))
  14024       (unless (equal wday wday1)
  14025 	(setq day (+ day (% (- wday wday1 -7) 7))))))
  14026     (when (and (boundp 'org-time-was-given)
  14027 	       (nth 2 tl))
  14028       (setq org-time-was-given t))
  14029     (when (< year 100) (setq year (+ 2000 year)))
  14030     ;; Check of the date is representable
  14031     (if org-read-date-force-compatible-dates
  14032 	(progn
  14033 	  (when (< year 1970)
  14034 	    (setq year 1970 org-read-date-analyze-forced-year t))
  14035 	  (when (> year 2037)
  14036 	    (setq year 2037 org-read-date-analyze-forced-year t)))
  14037       (condition-case nil
  14038 	  (ignore (org-encode-time second minute hour day month year))
  14039 	(error
  14040 	 (setq year (nth 5 org-defdecode))
  14041 	 (setq org-read-date-analyze-forced-year t))))
  14042     (setq org-read-date-analyze-futurep futurep)
  14043     (list second minute hour day month year nil -1 nil)))
  14044 
  14045 (defvar parse-time-weekdays)
  14046 (defun org-read-date-get-relative (s today default)
  14047   "Check string S for special relative date string.
  14048 TODAY and DEFAULT are internal times, for today and for a default.
  14049 Return shift list (N what def-flag)
  14050 WHAT       is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
  14051 N          is the number of WHATs to shift.
  14052 DEF-FLAG   is t when a double ++ or -- indicates shift relative to
  14053            the DEFAULT date rather than TODAY."
  14054   (require 'parse-time)
  14055   (when (and
  14056          ;; Force case-insensitive.
  14057          (let ((case-fold-search t))
  14058 	   (string-match
  14059 	    (concat
  14060 	     "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
  14061 	     "\\([0-9]+\\)?"
  14062 	     "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
  14063 	     "\\([ \t]\\|$\\)") s))
  14064 	 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
  14065     (let* ((dir (if (> (match-end 1) (match-beginning 1))
  14066 		    (string-to-char (substring (match-string 1 s) -1))
  14067 		  ?+))
  14068 	   (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
  14069 	   (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
  14070 	   (what (if (match-end 3) (match-string 3 s) "d"))
  14071 	   (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
  14072 	   (date (if rel default today))
  14073 	   (wday (nth 6 (decode-time date)))
  14074 	   delta)
  14075       (if wday1
  14076 	  (progn
  14077 	    (setq delta (mod (+ 7 (- wday1 wday)) 7))
  14078 	    (when (= delta 0) (setq delta 7))
  14079 	    (when (= dir ?-)
  14080 	      (setq delta (- delta 7))
  14081 	      (when (= delta 0) (setq delta -7)))
  14082 	    (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
  14083 	    (list delta "d" rel))
  14084 	(list (* n (if (= dir ?-) -1 1)) what rel)))))
  14085 
  14086 (defun org-order-calendar-date-args (arg1 arg2 arg3)
  14087   "Turn a user-specified date into the internal representation.
  14088 The internal representation needed by the calendar is (month day year).
  14089 This is a wrapper to handle the brain-dead convention in calendar that
  14090 user function argument order change dependent on argument order."
  14091   (pcase calendar-date-style
  14092     (`american (list arg1 arg2 arg3))
  14093     (`european (list arg2 arg1 arg3))
  14094     (`iso (list arg2 arg3 arg1))))
  14095 
  14096 (defun org-eval-in-calendar (form &optional keepdate)
  14097   "Eval FORM in the calendar window and return to current window.
  14098 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
  14099   (let ((sf (selected-frame))
  14100 	(sw (selected-window)))
  14101     (select-window (get-buffer-window "*Calendar*" t))
  14102     (eval form t)
  14103     (when (and (not keepdate) (calendar-cursor-to-date))
  14104       (let* ((date (calendar-cursor-to-date))
  14105 	     (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  14106 	(setq org-ans2 (format-time-string "%Y-%m-%d" time))))
  14107     (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
  14108     (select-window sw)
  14109     (select-frame-set-input-focus sf)))
  14110 
  14111 (defun org-calendar-select ()
  14112   "Return to `org-read-date' with the date currently selected.
  14113 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  14114   (interactive)
  14115   (when (calendar-cursor-to-date)
  14116     (let* ((date (calendar-cursor-to-date))
  14117 	   (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  14118       (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  14119     (when (active-minibuffer-window) (exit-minibuffer))))
  14120 
  14121 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
  14122   "Insert a date stamp for the date given by the internal TIME.
  14123 See `format-time-string' for the format of TIME.
  14124 WITH-HM means use the stamp format that includes the time of the day.
  14125 INACTIVE means use square brackets instead of angular ones, so that the
  14126 stamp will not contribute to the agenda.
  14127 PRE and POST are optional strings to be inserted before and after the
  14128 stamp.
  14129 The command returns the inserted time stamp."
  14130   (org-fold-core-ignore-modifications
  14131     (let ((fmt (org-time-stamp-format with-hm inactive))
  14132 	  stamp)
  14133       (insert-before-markers-and-inherit (or pre ""))
  14134       (when (listp extra)
  14135         (setq extra (car extra))
  14136         (if (and (stringp extra)
  14137 	         (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
  14138 	    (setq extra (format "-%02d:%02d"
  14139 			        (string-to-number (match-string 1 extra))
  14140 			        (string-to-number (match-string 2 extra))))
  14141 	  (setq extra nil)))
  14142       (when extra
  14143         (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
  14144       (insert-before-markers-and-inherit (setq stamp (format-time-string fmt time)))
  14145       (insert-before-markers-and-inherit (or post ""))
  14146       (setq org-last-inserted-timestamp stamp))))
  14147 
  14148 (defun org-toggle-time-stamp-overlays ()
  14149   "Toggle the use of custom time stamp formats."
  14150   (interactive)
  14151   (setq org-display-custom-times (not org-display-custom-times))
  14152   (unless org-display-custom-times
  14153     (let ((p (point-min)) (bmp (buffer-modified-p)))
  14154       (while (setq p (next-single-property-change p 'display))
  14155 	(when (and (get-text-property p 'display)
  14156 		   (eq (get-text-property p 'face) 'org-date))
  14157 	  (remove-text-properties
  14158 	   p (setq p (next-single-property-change p 'display))
  14159 	   '(display t))))
  14160       (set-buffer-modified-p bmp)))
  14161   (org-restart-font-lock)
  14162   (setq org-table-may-need-update t)
  14163   (if org-display-custom-times
  14164       (message "Time stamps are overlaid with custom format")
  14165     (message "Time stamp overlays removed")))
  14166 
  14167 (defun org-display-custom-time (beg end)
  14168   "Overlay modified time stamp format over timestamp between BEG and END."
  14169   (let* ((ts (buffer-substring beg end))
  14170 	 t1 with-hm tf time str (off 0))
  14171     (save-match-data
  14172       (setq t1 (org-parse-time-string ts t))
  14173       (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
  14174 	(setq off (- (match-end 0) (match-beginning 0)))))
  14175     (setq end (- end off))
  14176     (setq with-hm (and (nth 1 t1) (nth 2 t1))
  14177 	  tf (org-time-stamp-format with-hm 'no-brackets 'custom)
  14178 	  time (org-fix-decoded-time t1)
  14179 	  str (org-add-props
  14180 		  (format-time-string tf (org-encode-time time))
  14181 		  nil 'mouse-face 'highlight))
  14182     (put-text-property beg end 'display str)))
  14183 
  14184 (defun org-fix-decoded-time (time)
  14185   "Set 0 instead of nil for the first 6 elements of time.
  14186 Don't touch the rest."
  14187   (let ((n 0))
  14188     (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
  14189 
  14190 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
  14191   "Difference between TIMESTAMP-STRING and now in days.
  14192 If SECONDS is non-nil, return the difference in seconds."
  14193   (let ((fdiff (if seconds #'float-time #'time-to-days)))
  14194     (- (funcall fdiff (org-time-string-to-time timestamp-string))
  14195        (funcall fdiff nil))))
  14196 
  14197 (defun org-deadline-close-p (timestamp-string &optional ndays)
  14198   "Is the time in TIMESTAMP-STRING close to the current date?"
  14199   (setq ndays (or ndays (org-get-wdays timestamp-string)))
  14200   (and (<= (org-time-stamp-to-now timestamp-string) ndays)
  14201        (not (org-entry-is-done-p))))
  14202 
  14203 (defun org-get-wdays (ts &optional delay zero-delay)
  14204   "Get the deadline lead time appropriate for timestring TS.
  14205 When DELAY is non-nil, get the delay time for scheduled items
  14206 instead of the deadline lead time.  When ZERO-DELAY is non-nil
  14207 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
  14208 don't try to find the delay cookie in the scheduled timestamp."
  14209   (let ((tv (if delay org-scheduled-delay-days
  14210 	      org-deadline-warning-days)))
  14211     (cond
  14212      ((or (and delay (< tv 0))
  14213 	  (and delay zero-delay (<= tv 0))
  14214 	  (and (not delay) (<= tv 0)))
  14215       ;; Enforce this value no matter what
  14216       (- tv))
  14217      ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
  14218       ;; lead time is specified.
  14219       (floor (* (string-to-number (match-string 1 ts))
  14220 		(cdr (assoc (match-string 2 ts)
  14221 			    '(("d" . 1)    ("w" . 7)
  14222 			      ("m" . 30.4) ("y" . 365.25)
  14223 			      ("h" . 0.041667)))))))
  14224      ;; go for the default.
  14225      (t tv))))
  14226 
  14227 (defun org-calendar-select-mouse (ev)
  14228   "Return to `org-read-date' with the date currently selected.
  14229 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
  14230   (interactive "e")
  14231   (mouse-set-point ev)
  14232   (when (calendar-cursor-to-date)
  14233     (let* ((date (calendar-cursor-to-date))
  14234 	   (time (org-encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
  14235       (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
  14236     (when (active-minibuffer-window) (exit-minibuffer))))
  14237 
  14238 (defun org-check-deadlines (ndays)
  14239   "Check if there are any deadlines due or past due.
  14240 A deadline is considered due if it happens within `org-deadline-warning-days'
  14241 days from today's date.  If the deadline appears in an entry marked DONE,
  14242 it is not shown.  A numeric prefix argument NDAYS can be used to test that
  14243 many days.  If the prefix is a raw `\\[universal-argument]', all deadlines \
  14244 are shown."
  14245   (interactive "P")
  14246   (let* ((org-warn-days
  14247 	  (cond
  14248 	   ((equal ndays '(4)) 100000)
  14249 	   (ndays (prefix-numeric-value ndays))
  14250 	   (t (abs org-deadline-warning-days))))
  14251 	 (case-fold-search nil)
  14252 	 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
  14253 	 (callback
  14254 	  (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
  14255     (message "%d deadlines past-due or due within %d days"
  14256 	     (org-occur regexp nil callback)
  14257 	     org-warn-days)))
  14258 
  14259 (defsubst org-re-timestamp (type)
  14260   "Return a regexp for timestamp TYPE.
  14261 Allowed values for TYPE are:
  14262 
  14263         all: all timestamps
  14264      active: only active timestamps (<...>)
  14265    inactive: only inactive timestamps ([...])
  14266   scheduled: only scheduled timestamps
  14267    deadline: only deadline timestamps
  14268      closed: only closed time-stamps
  14269 
  14270 When TYPE is nil, fall back on returning a regexp that matches
  14271 both scheduled and deadline timestamps."
  14272   (cl-case type
  14273     (all org-ts-regexp-both)
  14274     (active org-ts-regexp)
  14275     (inactive org-ts-regexp-inactive)
  14276     (scheduled org-scheduled-time-regexp)
  14277     (deadline org-deadline-time-regexp)
  14278     (closed org-closed-time-regexp)
  14279     (otherwise
  14280      (concat "\\<"
  14281 	     (regexp-opt (list org-deadline-string org-scheduled-string))
  14282 	     " *<\\([^>]+\\)>"))))
  14283 
  14284 (defun org-check-before-date (d)
  14285   "Check if there are deadlines or scheduled entries before date D."
  14286   (interactive (list (org-read-date)))
  14287   (let* ((case-fold-search nil)
  14288 	 (regexp (org-re-timestamp org-ts-type))
  14289 	 (ts-type org-ts-type)
  14290 	 (callback
  14291 	  (lambda ()
  14292 	    (let ((match (match-string 1)))
  14293 	      (and (if (memq ts-type '(active inactive all))
  14294 		       (eq (org-element-type (save-excursion
  14295 					       (backward-char)
  14296 					       (org-element-context)))
  14297 			   'timestamp)
  14298 		     (org-at-planning-p))
  14299 		   (time-less-p
  14300 		    (org-time-string-to-time match)
  14301 		    (org-time-string-to-time d)))))))
  14302     (message "%d entries before %s"
  14303 	     (org-occur regexp nil callback)
  14304 	     d)))
  14305 
  14306 (defun org-check-after-date (d)
  14307   "Check if there are deadlines or scheduled entries after date D."
  14308   (interactive (list (org-read-date)))
  14309   (let* ((case-fold-search nil)
  14310 	 (regexp (org-re-timestamp org-ts-type))
  14311 	 (ts-type org-ts-type)
  14312 	 (callback
  14313 	  (lambda ()
  14314 	    (let ((match (match-string 1)))
  14315 	      (and (if (memq ts-type '(active inactive all))
  14316 		       (eq (org-element-type (save-excursion
  14317 					       (backward-char)
  14318 					       (org-element-context)))
  14319 			   'timestamp)
  14320 		     (org-at-planning-p))
  14321 		   (not (time-less-p
  14322 			 (org-time-string-to-time match)
  14323 			 (org-time-string-to-time d))))))))
  14324     (message "%d entries after %s"
  14325 	     (org-occur regexp nil callback)
  14326 	     d)))
  14327 
  14328 (defun org-check-dates-range (start-date end-date)
  14329   "Check for deadlines/scheduled entries between START-DATE and END-DATE."
  14330   (interactive (list (org-read-date nil nil nil "Range starts")
  14331 		     (org-read-date nil nil nil "Range end")))
  14332   (let ((case-fold-search nil)
  14333 	(regexp (org-re-timestamp org-ts-type))
  14334 	(callback
  14335 	 (let ((type org-ts-type))
  14336 	   (lambda ()
  14337 	     (let ((match (match-string 1)))
  14338 	       (and
  14339 		(if (memq type '(active inactive all))
  14340 		    (eq (org-element-type (save-excursion
  14341 					    (backward-char)
  14342 					    (org-element-context)))
  14343 			'timestamp)
  14344 		  (org-at-planning-p))
  14345 		(not (time-less-p
  14346 		      (org-time-string-to-time match)
  14347 		      (org-time-string-to-time start-date)))
  14348 		(time-less-p
  14349 		 (org-time-string-to-time match)
  14350 		 (org-time-string-to-time end-date))))))))
  14351     (message "%d entries between %s and %s"
  14352 	     (org-occur regexp nil callback) start-date end-date)))
  14353 
  14354 (defun org-evaluate-time-range (&optional to-buffer)
  14355   "Evaluate a time range by computing the difference between start and end.
  14356 Normally the result is just printed in the echo area, but with prefix arg
  14357 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
  14358 If the time range is actually in a table, the result is inserted into the
  14359 next column.
  14360 For time difference computation, a year is assumed to be exactly 365
  14361 days in order to avoid rounding problems."
  14362   (interactive "P")
  14363   (or
  14364    (org-clock-update-time-maybe)
  14365    (save-excursion
  14366      (unless (org-at-date-range-p t)
  14367        (goto-char (line-beginning-position))
  14368        (re-search-forward org-tr-regexp-both (line-end-position) t))
  14369      (unless (org-at-date-range-p t)
  14370        (user-error "Not at a time-stamp range, and none found in current line")))
  14371    (let* ((ts1 (match-string 1))
  14372 	  (ts2 (match-string 2))
  14373 	  (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
  14374 	  (match-end (match-end 0))
  14375 	  (time1 (org-time-string-to-time ts1))
  14376 	  (time2 (org-time-string-to-time ts2))
  14377 	  (diff (abs (float-time (time-subtract time2 time1))))
  14378 	  (negative (time-less-p time2 time1))
  14379 	  ;; (ys (floor (* 365 24 60 60)))
  14380 	  (ds (* 24 60 60))
  14381 	  (hs (* 60 60))
  14382 	  (fy "%dy %dd %02d:%02d")
  14383 	  (fy1 "%dy %dd")
  14384 	  (fd "%dd %02d:%02d")
  14385 	  (fd1 "%dd")
  14386 	  (fh "%02d:%02d")
  14387 	  y d h m align)
  14388      (if havetime
  14389 	 (setq ; y (floor diff ys)  diff (mod diff ys)
  14390 	  y 0
  14391 	  d (floor diff ds)  diff (mod diff ds)
  14392 	  h (floor diff hs)  diff (mod diff hs)
  14393 	  m (floor diff 60))
  14394        (setq ; y (floor diff ys)  diff (mod diff ys)
  14395 	y 0
  14396 	d (round diff ds)
  14397 	h 0 m 0))
  14398      (if (not to-buffer)
  14399 	 (message "%s" (org-make-tdiff-string y d h m))
  14400        (if (org-at-table-p)
  14401 	   (progn
  14402 	     (goto-char match-end)
  14403 	     (setq align t)
  14404 	     (and (looking-at " *|") (goto-char (match-end 0))))
  14405 	 (goto-char match-end))
  14406        (when (looking-at
  14407 	      "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
  14408 	 (replace-match ""))
  14409        (when negative (insert " -"))
  14410        (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
  14411 	 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
  14412 	   (insert " " (format fh h m))))
  14413        (when align (org-table-align))
  14414        (message "Time difference inserted")))))
  14415 
  14416 (defun org-make-tdiff-string (y d h m)
  14417   (let ((fmt "")
  14418 	(l nil))
  14419     (when (> y 0)
  14420       (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
  14421       (push y l))
  14422     (when (> d 0)
  14423       (setq fmt (concat fmt "%d day"  (if (> d 1) "s" "") " "))
  14424       (push d l))
  14425     (when (> h 0)
  14426       (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
  14427       (push h l))
  14428     (when (> m 0)
  14429       (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
  14430       (push m l))
  14431     (apply 'format fmt (nreverse l))))
  14432 
  14433 (defun org-time-string-to-time (s)
  14434   "Convert timestamp string S into internal time."
  14435   (org-encode-time (org-parse-time-string s)))
  14436 
  14437 (defun org-time-string-to-seconds (s)
  14438   "Convert a timestamp string S into a number of seconds."
  14439   (float-time (org-time-string-to-time s)))
  14440 
  14441 (define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
  14442 
  14443 (defun org-time-string-to-absolute (s &optional daynr prefer buffer pos)
  14444   "Convert time stamp S to an absolute day number.
  14445 
  14446 If DAYNR in non-nil, and there is a specifier for a cyclic time
  14447 stamp, get the closest date to DAYNR.  If PREFER is
  14448 `past' (respectively `future') return a date past (respectively
  14449 after) or equal to DAYNR.
  14450 
  14451 POS is the location of time stamp S, as a buffer position in
  14452 BUFFER.
  14453 
  14454 Diary sexp timestamps are matched against DAYNR, when non-nil.
  14455 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
  14456 signaled."
  14457   (cond
  14458    ((string-match "\\`%%\\((.*)\\)" s)
  14459     ;; Sexp timestamp: try to match DAYNR, if available, since we're
  14460     ;; only able to match individual dates.  If it fails, raise an
  14461     ;; error.
  14462     (if (and daynr
  14463 	     (org-diary-sexp-entry
  14464 	      (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
  14465 	daynr
  14466       (signal 'org-diary-sexp-no-match (list s))))
  14467    (daynr (org-closest-date s daynr prefer))
  14468    (t (time-to-days
  14469        (condition-case errdata
  14470 	   (org-time-string-to-time s)
  14471 	 (error (error "Bad timestamp `%s'%s\nError was: %s"
  14472 		       s
  14473 		       (if (not (and buffer pos)) ""
  14474 			 (format-message " at %d in buffer `%s'" pos buffer))
  14475 		       (cdr errdata))))))))
  14476 
  14477 (defun org-days-to-iso-week (days)
  14478   "Return the ISO week number."
  14479   (require 'cal-iso)
  14480   (car (calendar-iso-from-absolute days)))
  14481 
  14482 (defun org-small-year-to-year (year)
  14483   "Convert 2-digit years into 4-digit years.
  14484 YEAR is expanded into one of the 30 next years, if possible, or
  14485 into a past one.  Any year larger than 99 is returned unchanged."
  14486   (if (>= year 100) year
  14487     (let* ((current (string-to-number (format-time-string "%Y")))
  14488 	   (century (/ current 100))
  14489 	   (offset (- year (% current 100))))
  14490       (cond ((> offset 30) (+ (* (1- century) 100) year))
  14491 	    ((> offset -70) (+ (* century 100) year))
  14492 	    (t (+ (* (1+ century) 100) year))))))
  14493 
  14494 (defun org-time-from-absolute (d)
  14495   "Return the time corresponding to date D.
  14496 D may be an absolute day number, or a calendar-type list (month day year)."
  14497   (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
  14498   (org-encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
  14499 
  14500 (defvar org-agenda-current-date)
  14501 (defun org-calendar-holiday ()
  14502   "List of holidays, for Diary display in Org mode."
  14503   (require 'holidays)
  14504   (let ((hl (calendar-check-holidays org-agenda-current-date)))
  14505     (and hl (mapconcat #'identity hl "; "))))
  14506 
  14507 (defvar org--diary-sexp-entry-cache (make-hash-table :test #'equal)
  14508   "Hash table holding return values of `org-diary-sexp-entry'.")
  14509 (defun org-diary-sexp-entry (sexp entry d)
  14510   "Process a SEXP diary ENTRY for date D."
  14511   (require 'diary-lib)
  14512   ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
  14513   ;; dynamically.
  14514   (let ((cached (gethash (list sexp entry d) org--diary-sexp-entry-cache 'none)))
  14515     (if (not (eq 'none cached)) cached
  14516       (puthash (list sexp entry d)
  14517                (let* ((sexp `(let ((entry ,entry)
  14518 		                   (date ',d))
  14519 		               ,(car (read-from-string sexp))))
  14520                       ;; FIXME: Do not use (eval ... t) in the following sexp as
  14521                       ;; diary vars are still using dynamic scope.
  14522 	              (result (if calendar-debug-sexp (eval sexp)
  14523 		                (condition-case nil
  14524 		                    (eval sexp)
  14525 		                  (error
  14526 		                   (beep)
  14527 		                   (message "Bad sexp at line %d in %s: %s"
  14528 			                    (org-current-line)
  14529 			                    (buffer-file-name) sexp)
  14530 		                   (sleep-for 2))))))
  14531                  (cond ((stringp result) (split-string result "; "))
  14532 	               ((and (consp result)
  14533 		             (not (consp (cdr result)))
  14534 		             (stringp (cdr result)))
  14535 	                (cdr result))
  14536 	               ((and (consp result)
  14537 		             (stringp (car result)))
  14538 	                result)
  14539 	               (result entry)))
  14540                org--diary-sexp-entry-cache))))
  14541 
  14542 (defun org-diary-to-ical-string (frombuf)
  14543   "Get iCalendar entries from diary entries in buffer FROMBUF.
  14544 This uses the icalendar.el library."
  14545   (let* ((tmpdir temporary-file-directory)
  14546 	 (tmpfile (make-temp-name
  14547 		   (expand-file-name "orgics" tmpdir)))
  14548 	 buf rtn b e)
  14549     (with-current-buffer frombuf
  14550       (icalendar-export-region (point-min) (point-max) tmpfile)
  14551       (setq buf (find-buffer-visiting tmpfile))
  14552       (set-buffer buf)
  14553       (goto-char (point-min))
  14554       (when (re-search-forward "^BEGIN:VEVENT" nil t)
  14555 	(setq b (match-beginning 0)))
  14556       (goto-char (point-max))
  14557       (when (re-search-backward "^END:VEVENT" nil t)
  14558 	(setq e (match-end 0)))
  14559       (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
  14560     (kill-buffer buf)
  14561     (delete-file tmpfile)
  14562     rtn))
  14563 
  14564 (defun org-closest-date (start current prefer)
  14565   "Return closest date to CURRENT starting from START.
  14566 
  14567 CURRENT and START are both time stamps.
  14568 
  14569 When PREFER is `past', return a date that is either CURRENT or
  14570 past.  When PREFER is `future', return a date that is either
  14571 CURRENT or future.
  14572 
  14573 Only time stamps with a repeater are modified.  Any other time
  14574 stamp stay unchanged.  In any case, return value is an absolute
  14575 day number."
  14576   (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
  14577       ;; No repeater.  Do not shift time stamp.
  14578       (time-to-days (org-time-string-to-time start))
  14579     (let ((value (string-to-number (match-string 1 start)))
  14580 	  (type (match-string 2 start)))
  14581       (if (= 0 value)
  14582 	  ;; Repeater with a 0-value is considered as void.
  14583 	  (time-to-days (org-time-string-to-time start))
  14584 	(let* ((base (org-date-to-gregorian start))
  14585 	       (target (org-date-to-gregorian current))
  14586 	       (sday (calendar-absolute-from-gregorian base))
  14587 	       (cday (calendar-absolute-from-gregorian target))
  14588 	       n1 n2)
  14589 	  ;; If START is already past CURRENT, just return START.
  14590 	  (if (<= cday sday) sday
  14591 	    ;; Compute closest date before (N1) and closest date past
  14592 	    ;; (N2) CURRENT.
  14593 	    (pcase type
  14594 	      ("h"
  14595 	       (let ((missing-hours
  14596 		      (mod (+ (- (* 24 (- cday sday))
  14597 				 (nth 2 (org-parse-time-string start)))
  14598 			      org-extend-today-until)
  14599 			   value)))
  14600 		 (setf n1 (if (= missing-hours 0) cday
  14601 			    (- cday (1+ (/ missing-hours 24)))))
  14602 		 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
  14603 	      ((or "d" "w")
  14604 	       (let ((value (if (equal type "w") (* 7 value) value)))
  14605 		 (setf n1 (+ sday (* value (/ (- cday sday) value))))
  14606 		 (setf n2 (+ n1 value))))
  14607 	      ("m"
  14608 	       (let* ((add-months
  14609 		       (lambda (d n)
  14610 			 ;; Add N months to gregorian date D, i.e.,
  14611 			 ;; a list (MONTH DAY YEAR).  Return a valid
  14612 			 ;; gregorian date.
  14613 			 (let ((m (+ (nth 0 d) n)))
  14614 			   (list (mod m 12)
  14615 				 (nth 1 d)
  14616 				 (+ (/ m 12) (nth 2 d))))))
  14617 		      (months		; Complete months to TARGET.
  14618 		       (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
  14619 				(- (nth 0 target) (nth 0 base))
  14620 				;; If START's day is greater than
  14621 				;; TARGET's, remove incomplete month.
  14622 				(if (> (nth 1 target) (nth 1 base)) 0 -1))
  14623 			     value)
  14624 			  value))
  14625 		      (before (funcall add-months base months)))
  14626 		 (setf n1 (calendar-absolute-from-gregorian before))
  14627 		 (setf n2
  14628 		       (calendar-absolute-from-gregorian
  14629 			(funcall add-months before value)))))
  14630 	      (_
  14631 	       (let* ((d (nth 1 base))
  14632 		      (m (nth 0 base))
  14633 		      (y (nth 2 base))
  14634 		      (years		; Complete years to TARGET.
  14635 		       (* (/ (- (nth 2 target)
  14636 				y
  14637 				;; If START's month and day are
  14638 				;; greater than TARGET's, remove
  14639 				;; incomplete year.
  14640 				(if (or (> (nth 0 target) m)
  14641 					(and (= (nth 0 target) m)
  14642 					     (> (nth 1 target) d)))
  14643 				    0
  14644 				  1))
  14645 			     value)
  14646 			  value))
  14647 		      (before (list m d (+ y years))))
  14648 		 (setf n1 (calendar-absolute-from-gregorian before))
  14649 		 (setf n2 (calendar-absolute-from-gregorian
  14650 			   (list m d (+ (nth 2 before) value)))))))
  14651 	    ;; Handle PREFER parameter, if any.
  14652 	    (cond
  14653 	     ((eq prefer 'past)   (if (= cday n2) n2 n1))
  14654 	     ((eq prefer 'future) (if (= cday n1) n1 n2))
  14655 	     (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
  14656 
  14657 (defun org-date-to-gregorian (d)
  14658   "Turn any specification of date D into a Gregorian date for the calendar."
  14659   (cond ((integerp d) (calendar-gregorian-from-absolute d))
  14660 	((and (listp d) (= (length d) 3)) d)
  14661 	((stringp d)
  14662 	 (let ((d (org-parse-time-string d)))
  14663 	   (list (nth 4 d) (nth 3 d) (nth 5 d))))
  14664 	((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
  14665 
  14666 (defun org-timestamp-up (&optional arg)
  14667   "Increase the date item at the cursor by one.
  14668 If the cursor is on the year, change the year.  If it is on the month,
  14669 the day or the time, change that.  If the cursor is on the enclosing
  14670 bracket, change the timestamp type.
  14671 With prefix ARG, change by that many units."
  14672   (interactive "p")
  14673   (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
  14674 
  14675 (defun org-timestamp-down (&optional arg)
  14676   "Decrease the date item at the cursor by one.
  14677 If the cursor is on the year, change the year.  If it is on the month,
  14678 the day or the time, change that.  If the cursor is on the enclosing
  14679 bracket, change the timestamp type.
  14680 With prefix ARG, change by that many units."
  14681   (interactive "p")
  14682   (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
  14683 
  14684 (defun org-timestamp-up-day (&optional arg)
  14685   "Increase the date in the time stamp by one day.
  14686 With prefix ARG, change that many days."
  14687   (interactive "p")
  14688   (if (and (not (org-at-timestamp-p 'lax))
  14689 	   (org-at-heading-p))
  14690       (org-todo 'up)
  14691     (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
  14692 
  14693 (defun org-timestamp-down-day (&optional arg)
  14694   "Decrease the date in the time stamp by one day.
  14695 With prefix ARG, change that many days."
  14696   (interactive "p")
  14697   (if (and (not (org-at-timestamp-p 'lax))
  14698 	   (org-at-heading-p))
  14699       (org-todo 'down)
  14700     (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
  14701 
  14702 (defun org-at-timestamp-p (&optional extended)
  14703   "Non-nil if point is inside a timestamp.
  14704 
  14705 By default, the function only consider syntactically valid active
  14706 timestamps.  However, the caller may have a broader definition
  14707 for timestamps.  As a consequence, optional argument EXTENDED can
  14708 be set to the following values
  14709 
  14710   `inactive'
  14711 
  14712     Include also syntactically valid inactive timestamps.
  14713 
  14714   `agenda'
  14715 
  14716     Include timestamps allowed in Agenda, i.e., those in
  14717     properties drawers, planning lines and clock lines.
  14718 
  14719   `lax'
  14720 
  14721     Ignore context.  The function matches any part of the
  14722     document looking like a timestamp.  This includes comments,
  14723     example blocks...
  14724 
  14725 For backward-compatibility with Org 9.0, every other non-nil
  14726 value is equivalent to `inactive'.
  14727 
  14728 When at a timestamp, return the position of the point as a symbol
  14729 among `bracket', `after', `year', `month', `hour', `minute',
  14730 `day' or a number of character from the last know part of the
  14731 time stamp.  If diary sexp timestamps, any point inside the timestamp
  14732 is considered `day' (i.e. only `bracket', `day', and `after' return
  14733 values are possible).
  14734 
  14735 When matching, the match groups are the following:
  14736   group 1: year, if any
  14737   group 2: month, if any
  14738   group 3: day number, if any
  14739   group 4: day name, if any
  14740   group 5: hours, if any
  14741   group 6: minutes, if any"
  14742   (let* ((regexp
  14743           (if extended
  14744               (if (eq extended 'agenda)
  14745                   (rx-to-string
  14746                    `(or (regexp ,org-ts-regexp3)
  14747                         (regexp ,org-element--timestamp-regexp)))
  14748 		org-ts-regexp3)
  14749             org-ts-regexp2))
  14750 	 (pos (point))
  14751 	 (match?
  14752 	  (let ((boundaries (org-in-regexp regexp)))
  14753 	    (save-match-data
  14754 	      (cond ((null boundaries) nil)
  14755 		    ((eq extended 'lax) t)
  14756 		    (t
  14757 		     (or (and (eq extended 'agenda)
  14758 			      (or (org-at-planning-p)
  14759 				  (org-at-property-p)
  14760 				  (and (bound-and-true-p
  14761 					org-agenda-include-inactive-timestamps)
  14762 				       (org-at-clock-log-p))))
  14763 			 (eq 'timestamp
  14764 			     (save-excursion
  14765 			       (when (= pos (cdr boundaries)) (forward-char -1))
  14766 			       (org-element-type (org-element-context)))))))))))
  14767     (cond
  14768      ((not match?)                        nil)
  14769      ((= pos (match-beginning 0))         'bracket)
  14770      ;; Distinguish location right before the closing bracket from
  14771      ;; right after it.
  14772      ((= pos (1- (match-end 0)))          'bracket)
  14773      ((= pos (match-end 0))               'after)
  14774      ((org-pos-in-match-range pos 2)      'year)
  14775      ((org-pos-in-match-range pos 3)      'month)
  14776      ((org-pos-in-match-range pos 7)      'hour)
  14777      ((org-pos-in-match-range pos 8)      'minute)
  14778      ((or (org-pos-in-match-range pos 4)
  14779 	  (org-pos-in-match-range pos 5)) 'day)
  14780      ((and (or (match-end 8) (match-end 5))
  14781            (> pos (or (match-end 8) (match-end 5)))
  14782 	   (< pos (match-end 0)))
  14783       (- pos (or (match-end 8) (match-end 5))))
  14784      (t                                   'day))))
  14785 
  14786 (defun org-toggle-timestamp-type ()
  14787   "Toggle the type (<active> or [inactive]) of a time stamp."
  14788   (interactive)
  14789   (when (org-at-timestamp-p 'lax)
  14790     (let ((beg (match-beginning 0)) (end (match-end 0))
  14791 	  (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
  14792       (save-excursion
  14793 	(goto-char beg)
  14794 	(while (re-search-forward "[][<>]" end t)
  14795 	  (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
  14796 			 t t)))
  14797       (message "Timestamp is now %sactive"
  14798 	       (if (equal (char-after beg) ?<) "" "in")))))
  14799 
  14800 (defun org-at-clock-log-p ()
  14801   "Non-nil if point is on a clock log line."
  14802   (and (org-match-line org-clock-line-re)
  14803        (eq (org-element-type (save-match-data (org-element-at-point))) 'clock)))
  14804 
  14805 (defvar org-clock-history)                     ; defined in org-clock.el
  14806 (defvar org-clock-adjust-closest nil)          ; defined in org-clock.el
  14807 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
  14808   "Change the date in the time stamp at point.
  14809 
  14810 The date is changed by N times WHAT.  WHAT can be `day', `month',
  14811 `year', `hour', or `minute'.  If WHAT is not given, the cursor
  14812 position in the timestamp determines what is changed.
  14813 
  14814 When optional argument UPDOWN is non-nil, minutes are rounded
  14815 according to `org-time-stamp-rounding-minutes'.
  14816 
  14817 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like
  14818 \"--2d\"."
  14819   (let ((origin (point))
  14820 	(timestamp? (org-at-timestamp-p 'lax))
  14821 	origin-cat
  14822 	with-hm inactive
  14823 	(dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
  14824 	extra rem
  14825 	ts time time0 fixnext clrgx)
  14826     (unless timestamp? (user-error "Not at a timestamp"))
  14827     (if (and (not what) (eq timestamp? 'bracket))
  14828 	(org-toggle-timestamp-type)
  14829       ;; Point isn't on brackets.  Remember the part of the time-stamp
  14830       ;; the point was in.  Indeed, size of time-stamps may change,
  14831       ;; but point must be kept in the same category nonetheless.
  14832       (setq origin-cat timestamp?)
  14833       (when (and (not what) (not (eq timestamp? 'day))
  14834 		 org-display-custom-times
  14835 		 (get-text-property (point) 'display)
  14836 		 (not (get-text-property (1- (point)) 'display)))
  14837 	(setq timestamp? 'day))
  14838       (setq timestamp? (or what timestamp?)
  14839 	    inactive (= (char-after (match-beginning 0)) ?\[)
  14840 	    ts (match-string 0))
  14841       (replace-match "")
  14842       (when (string-match
  14843 	     "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
  14844 	     ts)
  14845 	(setq extra (match-string 1 ts))
  14846 	(when suppress-tmp-delay
  14847 	  (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
  14848       (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
  14849 	(setq with-hm t))
  14850       (setq time0 (org-parse-time-string ts))
  14851       (when (and updown
  14852 		 (eq timestamp? 'minute)
  14853 		 (not current-prefix-arg))
  14854 	;; This looks like s-up and s-down.  Change by one rounding step.
  14855 	(setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
  14856 	(unless (= 0 (setq rem (% (nth 1 time0) dm)))
  14857 	  (setcar (cdr time0) (+ (nth 1 time0)
  14858 				 (if (> n 0) (- rem) (- dm rem))))))
  14859       (setq time
  14860 	    (org-encode-time
  14861              (apply #'list
  14862                     (or (car time0) 0)
  14863                     (+ (if (eq timestamp? 'minute) n 0) (nth 1 time0))
  14864                     (+ (if (eq timestamp? 'hour) n 0)   (nth 2 time0))
  14865                     (+ (if (eq timestamp? 'day) n 0)    (nth 3 time0))
  14866                     (+ (if (eq timestamp? 'month) n 0)  (nth 4 time0))
  14867                     (+ (if (eq timestamp? 'year) n 0)   (nth 5 time0))
  14868                     (nthcdr 6 time0))))
  14869       (when (and (memq timestamp? '(hour minute))
  14870 		 extra
  14871 		 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
  14872 	(setq extra (org-modify-ts-extra
  14873 		     extra
  14874 		     (if (eq timestamp? 'hour) 2 5)
  14875 		     n dm)))
  14876       (when (integerp timestamp?)
  14877 	(setq extra (org-modify-ts-extra extra timestamp? n dm)))
  14878       (when (eq what 'calendar)
  14879 	(let ((cal-date (org-get-date-from-calendar)))
  14880 	  (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
  14881 	  (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
  14882 	  (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
  14883 	  (setcar time0 (or (car time0) 0))
  14884 	  (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
  14885 	  (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
  14886 	  (setq time (org-encode-time time0))))
  14887       ;; Insert the new time-stamp, and ensure point stays in the same
  14888       ;; category as before (i.e. not after the last position in that
  14889       ;; category).
  14890       (let ((pos (point)))
  14891 	;; Stay before inserted string. `save-excursion' is of no use.
  14892 	(setq org-last-changed-timestamp
  14893 	      (org-insert-time-stamp time with-hm inactive nil nil extra))
  14894 	(goto-char pos))
  14895       (save-match-data
  14896 	(looking-at org-ts-regexp3)
  14897 	(goto-char
  14898 	 (pcase origin-cat
  14899 	   ;; `day' category ends before `hour' if any, or at the end
  14900 	   ;; of the day name.
  14901 	   (`day (min (or (match-beginning 7) (1- (match-end 5))) origin))
  14902 	   (`hour (min (match-end 7) origin))
  14903 	   (`minute (min (1- (match-end 8)) origin))
  14904 	   ((pred integerp) (min (1- (match-end 0)) origin))
  14905 	   ;; Point was right after the time-stamp.  However, the
  14906 	   ;; time-stamp length might have changed, so refer to
  14907 	   ;; (match-end 0) instead.
  14908 	   (`after (match-end 0))
  14909 	   ;; `year' and `month' have both fixed size: point couldn't
  14910 	   ;; have moved into another part.
  14911 	   (_ origin))))
  14912       ;; Update clock if on a CLOCK line.
  14913       (org-clock-update-time-maybe)
  14914       ;; Maybe adjust the closest clock in `org-clock-history'
  14915       (when org-clock-adjust-closest
  14916 	(if (not (and (org-at-clock-log-p)
  14917 		      (< 1 (length (delq nil (mapcar 'marker-position
  14918 						     org-clock-history))))))
  14919 	    (message "No clock to adjust")
  14920 	  (cond ((save-excursion	; fix previous clock?
  14921 		   (re-search-backward org-ts-regexp0 nil t)
  14922 		   (looking-back (concat org-clock-string " \\[")
  14923 				 (line-beginning-position)))
  14924 		 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
  14925 		((save-excursion	; fix next clock?
  14926 		   (re-search-backward org-ts-regexp0 nil t)
  14927 		   (looking-at (concat org-ts-regexp0 "\\] =>")))
  14928 		 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
  14929 	  (save-window-excursion
  14930 	    ;; Find closest clock to point, adjust the previous/next one in history
  14931 	    (let* ((p (save-excursion (org-back-to-heading t)))
  14932 		   (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
  14933 		   (clfixnth
  14934 		    (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
  14935 		   (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
  14936 	      (if (not clfixpos)
  14937 		  (message "No clock to adjust")
  14938 		(save-excursion
  14939 		  (org-goto-marker-or-bmk clfixpos)
  14940 		  (org-fold-show-subtree)
  14941 		  (when (re-search-forward clrgx nil t)
  14942 		    (goto-char (match-beginning 1))
  14943 		    (let (org-clock-adjust-closest)
  14944 		      (org-timestamp-change n timestamp? updown))
  14945 		    (message "Clock adjusted in %s for heading: %s"
  14946 			     (file-name-nondirectory (buffer-file-name))
  14947 			     (org-get-heading t t)))))))))
  14948       ;; Try to recenter the calendar window, if any.
  14949       (when (and org-calendar-follow-timestamp-change
  14950 		 (get-buffer-window "*Calendar*" t)
  14951 		 (memq timestamp? '(day month year)))
  14952 	(org-recenter-calendar (time-to-days time))))))
  14953 
  14954 (defun org-modify-ts-extra (s pos n dm)
  14955   "Change the different parts of the lead-time and repeat fields in timestamp."
  14956   (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
  14957 	ng h m new rem)
  14958     (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
  14959       (cond
  14960        ((or (org-pos-in-match-range pos 2)
  14961 	    (org-pos-in-match-range pos 3))
  14962 	(setq m (string-to-number (match-string 3 s))
  14963 	      h (string-to-number (match-string 2 s)))
  14964 	(if (org-pos-in-match-range pos 2)
  14965 	    (setq h (+ h n))
  14966 	  (setq n (* dm (with-no-warnings (cl-signum n))))
  14967 	  (unless (= 0 (setq rem (% m dm)))
  14968 	    (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
  14969 	  (setq m (+ m n)))
  14970 	(when (< m 0) (setq m (+ m 60) h (1- h)))
  14971 	(when (> m 59) (setq m (- m 60) h (1+ h)))
  14972 	(setq h (mod h 24))
  14973 	(setq ng 1 new (format "-%02d:%02d" h m)))
  14974        ((org-pos-in-match-range pos 6)
  14975 	(setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
  14976        ((org-pos-in-match-range pos 5)
  14977 	(setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
  14978 
  14979        ((org-pos-in-match-range pos 9)
  14980 	(setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
  14981        ((org-pos-in-match-range pos 8)
  14982 	(setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
  14983 
  14984       (when ng
  14985 	(setq s (concat
  14986 		 (substring s 0 (match-beginning ng))
  14987 		 new
  14988 		 (substring s (match-end ng))))))
  14989     s))
  14990 
  14991 (defun org-recenter-calendar (d)
  14992   "If the calendar is visible, recenter it to date D."
  14993   (let ((cwin (get-buffer-window "*Calendar*" t)))
  14994     (when cwin
  14995       (let ((calendar-move-hook nil))
  14996 	(with-selected-window cwin
  14997 	  (calendar-goto-date
  14998 	   (if (listp d) d (calendar-gregorian-from-absolute d))))))))
  14999 
  15000 (defun org-goto-calendar (&optional arg)
  15001   "Go to the Emacs calendar at the current date.
  15002 If there is a time stamp in the current line, go to that date.
  15003 A prefix ARG can be used to force the current date."
  15004   (interactive "P")
  15005   (let ((calendar-move-hook nil)
  15006 	(calendar-view-holidays-initially-flag nil)
  15007 	(calendar-view-diary-initially-flag nil)
  15008 	diff)
  15009     (when (or (org-at-timestamp-p 'lax)
  15010 	      (org-match-line (concat ".*" org-ts-regexp)))
  15011       (let ((d1 (time-to-days nil))
  15012 	    (d2 (time-to-days (org-time-string-to-time (match-string 1)))))
  15013 	(setq diff (- d2 d1))))
  15014     (calendar)
  15015     (calendar-goto-today)
  15016     (when (and diff (not arg)) (calendar-forward-day diff))))
  15017 
  15018 (defun org-get-date-from-calendar ()
  15019   "Return a list (month day year) of date at point in calendar."
  15020   (with-current-buffer "*Calendar*"
  15021     (save-match-data
  15022       (calendar-cursor-to-date))))
  15023 
  15024 (defun org-date-from-calendar ()
  15025   "Insert time stamp corresponding to cursor date in *Calendar* buffer.
  15026 If there is already a time stamp at the cursor position, update it."
  15027   (interactive)
  15028   (if (org-at-timestamp-p 'lax)
  15029       (org-timestamp-change 0 'calendar)
  15030     (let ((cal-date (org-get-date-from-calendar)))
  15031       (org-insert-time-stamp
  15032        (org-encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
  15033 
  15034 (defcustom org-image-actual-width t
  15035   "When non-nil, use the actual width of images when inlining them.
  15036 
  15037 When set to a number, use imagemagick (when available) to set the
  15038 image's width to this value.
  15039 
  15040 When set to a number in a list, try to get the width from any
  15041 #+ATTR.* keyword if it matches a width specification like
  15042 
  15043   #+ATTR_HTML: :width 300px
  15044 
  15045 and fall back on that number if none is found.
  15046 
  15047 When set to nil, try to get the width from an #+ATTR.* keyword
  15048 and fall back on the original width if none is found.
  15049 
  15050 When set to any other non-nil value, always use the image width.
  15051 
  15052 This requires Emacs >= 24.1, built with imagemagick support."
  15053   :group 'org-appearance
  15054   :version "24.4"
  15055   :package-version '(Org . "8.0")
  15056   :type '(choice
  15057 	  (const :tag "Use the image width" t)
  15058 	  (integer :tag "Use a number of pixels")
  15059 	  (list :tag "Use #+ATTR* or a number of pixels" (integer))
  15060 	  (const :tag "Use #+ATTR* or don't resize" nil)))
  15061 
  15062 (defcustom org-agenda-inhibit-startup nil
  15063   "Inhibit startup when preparing agenda buffers.
  15064 When this variable is t, the initialization of the Org agenda
  15065 buffers is inhibited: e.g. the visibility state is not set, the
  15066 tables are not re-aligned, etc."
  15067   :type 'boolean
  15068   :version "24.3"
  15069   :group 'org-agenda)
  15070 
  15071 (defcustom org-agenda-ignore-properties nil
  15072   "Avoid updating text properties when building the agenda.
  15073 Properties are used to prepare buffers for effort estimates,
  15074 appointments, statistics and subtree-local categories.
  15075 If you don't use these in the agenda, you can add them to this
  15076 list and agenda building will be a bit faster.
  15077 The value is a list, with zero or more of the symbols `effort', `appt',
  15078 `stats' or `category'."
  15079   :type '(set :greedy t
  15080 	      (const effort)
  15081 	      (const appt)
  15082 	      (const stats)
  15083 	      (const category))
  15084   :version "26.1"
  15085   :package-version '(Org . "8.3")
  15086   :group 'org-agenda)
  15087 
  15088 ;;;; Files
  15089 
  15090 (defun org-save-all-org-buffers ()
  15091   "Save all Org buffers without user confirmation."
  15092   (interactive)
  15093   (message "Saving all Org buffers...")
  15094   (save-some-buffers t (lambda () (and (derived-mode-p 'org-mode) t)))
  15095   (when (featurep 'org-id) (org-id-locations-save))
  15096   (message "Saving all Org buffers... done"))
  15097 
  15098 (defun org-revert-all-org-buffers ()
  15099   "Revert all Org buffers.
  15100 Prompt for confirmation when there are unsaved changes.
  15101 Be sure you know what you are doing before letting this function
  15102 overwrite your changes.
  15103 
  15104 This function is useful in a setup where one tracks Org files
  15105 with a version control system, to revert on one machine after pulling
  15106 changes from another.  I believe the procedure must be like this:
  15107 
  15108 1. \\[org-save-all-org-buffers]
  15109 2. Pull changes from the other machine, resolve conflicts
  15110 3. \\[org-revert-all-org-buffers]"
  15111   (interactive)
  15112   (unless (yes-or-no-p "Revert all Org buffers from their files? ")
  15113     (user-error "Abort"))
  15114   (save-excursion
  15115     (save-window-excursion
  15116       (dolist (b (buffer-list))
  15117 	(when (and (with-current-buffer b (derived-mode-p 'org-mode))
  15118 		   (with-current-buffer b buffer-file-name))
  15119 	  (pop-to-buffer-same-window b)
  15120 	  (revert-buffer t 'no-confirm)))
  15121       (when (and (featurep 'org-id) org-id-track-globally)
  15122 	(org-id-locations-load)))))
  15123 
  15124 ;;;; Agenda files
  15125 
  15126 ;;;###autoload
  15127 (defun org-switchb (&optional arg)
  15128   "Switch between Org buffers.
  15129 
  15130 With `\\[universal-argument]' prefix, restrict available buffers to files.
  15131 
  15132 With `\\[universal-argument] \\[universal-argument]' \
  15133 prefix, restrict available buffers to agenda files."
  15134   (interactive "P")
  15135   (let ((blist (org-buffer-list
  15136 		(cond ((equal arg '(4))  'files)
  15137 		      ((equal arg '(16)) 'agenda)))))
  15138     (pop-to-buffer-same-window
  15139      (completing-read "Org buffer: "
  15140 		      (mapcar #'list (mapcar #'buffer-name blist))
  15141 		      nil t))))
  15142 
  15143 (defun org-agenda-files (&optional unrestricted archives)
  15144   "Get the list of agenda files.
  15145 Optional UNRESTRICTED means return the full list even if a restriction
  15146 is currently in place.
  15147 When ARCHIVES is t, include all archive files that are really being
  15148 used by the agenda files.  If ARCHIVE is `ifmode', do this only if
  15149 `org-agenda-archives-mode' is t."
  15150   (let ((files
  15151 	 (cond
  15152 	  ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
  15153 	  ((stringp org-agenda-files) (org-read-agenda-file-list))
  15154 	  ((listp org-agenda-files) org-agenda-files)
  15155 	  (t (error "Invalid value of `org-agenda-files'")))))
  15156     (setq files (apply 'append
  15157 		       (mapcar (lambda (f)
  15158 				 (if (file-directory-p f)
  15159 				     (directory-files
  15160 				      f t org-agenda-file-regexp)
  15161 				   (list (expand-file-name f org-directory))))
  15162 			       files)))
  15163     (when org-agenda-skip-unavailable-files
  15164       (setq files (delq nil
  15165 			(mapcar (lambda (file)
  15166 				  (and (file-readable-p file) file))
  15167 				files))))
  15168     (when (or (eq archives t)
  15169 	      (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
  15170       (setq files (org-add-archive-files files)))
  15171     files))
  15172 
  15173 (defun org-agenda-file-p (&optional file)
  15174   "Return non-nil, if FILE is an agenda file.
  15175 If FILE is omitted, use the file associated with the current
  15176 buffer."
  15177   (let ((fname (or file (buffer-file-name))))
  15178     (and fname
  15179          (member (file-truename fname)
  15180                  (mapcar #'file-truename (org-agenda-files t))))))
  15181 
  15182 (defun org-edit-agenda-file-list ()
  15183   "Edit the list of agenda files.
  15184 Depending on setup, this either uses customize to edit the variable
  15185 `org-agenda-files', or it visits the file that is holding the list.  In the
  15186 latter case, the buffer is set up in a way that saving it automatically kills
  15187 the buffer and restores the previous window configuration."
  15188   (interactive)
  15189   (if (stringp org-agenda-files)
  15190       (let ((cw (current-window-configuration)))
  15191 	(find-file org-agenda-files)
  15192 	(setq-local org-window-configuration cw)
  15193 	(add-hook 'after-save-hook
  15194 		  (lambda ()
  15195 		    (set-window-configuration
  15196 		     (prog1 org-window-configuration
  15197 		       (kill-buffer (current-buffer))))
  15198 		    (org-install-agenda-files-menu)
  15199 		    (message "New agenda file list installed"))
  15200 		  nil 'local)
  15201 	(message "%s" (substitute-command-keys
  15202 		       "Edit list and finish with \\[save-buffer]")))
  15203     (customize-variable 'org-agenda-files)))
  15204 
  15205 (defun org-store-new-agenda-file-list (list)
  15206   "Set new value for the agenda file list and save it correctly."
  15207   (if (stringp org-agenda-files)
  15208       (let ((fe (org-read-agenda-file-list t)) b u)
  15209 	(while (setq b (find-buffer-visiting org-agenda-files))
  15210 	  (kill-buffer b))
  15211 	(with-temp-file org-agenda-files
  15212 	  (insert
  15213 	   (mapconcat
  15214 	    (lambda (f) ;; Keep un-expanded entries.
  15215 	      (if (setq u (assoc f fe))
  15216 		  (cdr u)
  15217 		f))
  15218 	    list "\n")
  15219 	   "\n")))
  15220     (let ((org-mode-hook nil) (org-inhibit-startup t)
  15221 	  (org-insert-mode-line-in-empty-file nil))
  15222       (setq org-agenda-files list)
  15223       (customize-save-variable 'org-agenda-files org-agenda-files))))
  15224 
  15225 (defun org-read-agenda-file-list (&optional pair-with-expansion)
  15226   "Read the list of agenda files from a file.
  15227 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
  15228 filenames, used by `org-store-new-agenda-file-list' to write back
  15229 un-expanded file names."
  15230   (when (file-directory-p org-agenda-files)
  15231     (error "`org-agenda-files' cannot be a single directory"))
  15232   (when (stringp org-agenda-files)
  15233     (with-temp-buffer
  15234       (insert-file-contents org-agenda-files)
  15235       (mapcar
  15236        (lambda (f)
  15237 	 (let ((e (expand-file-name (substitute-in-file-name f)
  15238 				    org-directory)))
  15239 	   (if pair-with-expansion
  15240 	       (cons e f)
  15241 	     e)))
  15242        (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
  15243 
  15244 ;;;###autoload
  15245 (defun org-cycle-agenda-files ()
  15246   "Cycle through the files in `org-agenda-files'.
  15247 If the current buffer visits an agenda file, find the next one in the list.
  15248 If the current buffer does not, find the first agenda file."
  15249   (interactive)
  15250   (let* ((fs (or (org-agenda-files t)
  15251 		 (user-error "No agenda files")))
  15252 	 (files (copy-sequence fs))
  15253 	 (tcf (and buffer-file-name (file-truename buffer-file-name)))
  15254 	 file)
  15255     (when tcf
  15256       (while (and (setq file (pop files))
  15257 		  (not (equal (file-truename file) tcf)))))
  15258     (find-file (car (or files fs)))
  15259     (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
  15260 
  15261 (defun org-agenda-file-to-front (&optional to-end)
  15262   "Move/add the current file to the top of the agenda file list.
  15263 If the file is not present in the list, it is added to the front.  If it is
  15264 present, it is moved there.  With optional argument TO-END, add/move to the
  15265 end of the list."
  15266   (interactive "P")
  15267   (let ((org-agenda-skip-unavailable-files nil)
  15268 	(file-alist (mapcar (lambda (x)
  15269 			      (cons (file-truename x) x))
  15270 			    (org-agenda-files t)))
  15271 	(ctf (file-truename
  15272 	      (or buffer-file-name
  15273 		  (user-error "Please save the current buffer to a file"))))
  15274 	x had)
  15275     (setq x (assoc ctf file-alist) had x)
  15276 
  15277     (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
  15278     (if to-end
  15279 	(setq file-alist (append (delq x file-alist) (list x)))
  15280       (setq file-alist (cons x (delq x file-alist))))
  15281     (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
  15282     (org-install-agenda-files-menu)
  15283     (message "File %s to %s of agenda file list"
  15284 	     (if had "moved" "added") (if to-end "end" "front"))))
  15285 
  15286 (defun org-remove-file (&optional file)
  15287   "Remove current file from the list of files in variable `org-agenda-files'.
  15288 These are the files which are being checked for agenda entries.
  15289 Optional argument FILE means use this file instead of the current."
  15290   (interactive)
  15291   (let* ((org-agenda-skip-unavailable-files nil)
  15292 	 (file (or file buffer-file-name
  15293 		   (user-error "Current buffer does not visit a file")))
  15294 	 (true-file (file-truename file))
  15295 	 (afile (abbreviate-file-name file))
  15296 	 (files (delq nil (mapcar
  15297 			   (lambda (x)
  15298 			     (unless (equal true-file
  15299 					    (file-truename x))
  15300 			       x))
  15301 			   (org-agenda-files t)))))
  15302     (if (not (= (length files) (length (org-agenda-files t))))
  15303 	(progn
  15304 	  (org-store-new-agenda-file-list files)
  15305 	  (org-install-agenda-files-menu)
  15306 	  (message "Removed from Org Agenda list: %s" afile))
  15307       (message "File was not in list: %s (not removed)" afile))))
  15308 
  15309 (defun org-file-menu-entry (file)
  15310   (vector file (list 'find-file file) t))
  15311 
  15312 (defun org-check-agenda-file (file)
  15313   "Make sure FILE exists.  If not, ask user what to do."
  15314   (unless (file-exists-p file)
  15315     (message "Non-existent agenda file %s.  [R]emove from list or [A]bort?"
  15316 	     (abbreviate-file-name file))
  15317     (let ((r (downcase (read-char-exclusive))))
  15318       (cond
  15319        ((equal r ?r)
  15320 	(org-remove-file file)
  15321 	(throw 'nextfile t))
  15322        (t (user-error "Abort"))))))
  15323 
  15324 (defun org-get-agenda-file-buffer (file)
  15325   "Get an agenda buffer visiting FILE.
  15326 If the buffer needs to be created, add it to the list of buffers
  15327 which might be released later."
  15328   (let ((buf (org-find-base-buffer-visiting file)))
  15329     (if buf
  15330 	buf ; just return it
  15331       ;; Make a new buffer and remember it
  15332       (setq buf (find-file-noselect file))
  15333       (when buf (push buf org-agenda-new-buffers))
  15334       buf)))
  15335 
  15336 (defun org-release-buffers (blist)
  15337   "Release all buffers in list, asking the user for confirmation when needed.
  15338 When a buffer is unmodified, it is just killed.  When modified, it is saved
  15339 \(if the user agrees) and then killed."
  15340   (let (file)
  15341     (dolist (buf blist)
  15342       (setq file (buffer-file-name buf))
  15343       (when (and (buffer-modified-p buf)
  15344 		 file
  15345 		 (y-or-n-p (format "Save file %s? " file)))
  15346 	(with-current-buffer buf (save-buffer)))
  15347       (kill-buffer buf))))
  15348 
  15349 (defun org-agenda-prepare-buffers (files)
  15350   "Create buffers for all agenda files, protect archived trees and comments."
  15351   (interactive)
  15352   (let ((inhibit-read-only t)
  15353 	(org-inhibit-startup org-agenda-inhibit-startup)
  15354         ;; Do not refresh list of agenda files in the menu when
  15355         ;; opening every new file.
  15356         (org-agenda-file-menu-enabled nil))
  15357     (setq org-tag-alist-for-agenda nil
  15358 	  org-tag-groups-alist-for-agenda nil)
  15359     (dolist (file files)
  15360       (catch 'nextfile
  15361         (with-current-buffer
  15362             (if (bufferp file)
  15363                 file
  15364               (org-check-agenda-file file)
  15365               (org-get-agenda-file-buffer file))
  15366           (org-with-wide-buffer
  15367 	   (org-set-regexps-and-options 'tags-only)
  15368 	   (or (memq 'category org-agenda-ignore-properties)
  15369 	       (org-refresh-category-properties))
  15370 	   (or (memq 'stats org-agenda-ignore-properties)
  15371 	       (org-refresh-stats-properties))
  15372 	   (or (memq 'effort org-agenda-ignore-properties)
  15373                (unless org-element-use-cache
  15374 		 (org-refresh-effort-properties)))
  15375 	   (or (memq 'appt org-agenda-ignore-properties)
  15376 	       (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
  15377            (dolist (el org-todo-keywords-1)
  15378              (unless (member el org-todo-keywords-for-agenda)
  15379                (push el org-todo-keywords-for-agenda)))
  15380            (dolist (el org-done-keywords)
  15381              (unless (member el org-done-keywords-for-agenda)
  15382                (push el org-done-keywords-for-agenda)))
  15383 	   (setq org-todo-keyword-alist-for-agenda
  15384                  (org--tag-add-to-alist
  15385 		  org-todo-key-alist
  15386                   org-todo-keyword-alist-for-agenda))
  15387 	   (setq org-tag-alist-for-agenda
  15388 		 (org--tag-add-to-alist
  15389 		  org-current-tag-alist
  15390                   org-tag-alist-for-agenda))
  15391 	   ;; Merge current file's tag groups into global
  15392 	   ;; `org-tag-groups-alist-for-agenda'.
  15393 	   (when org-group-tags
  15394 	     (dolist (alist org-tag-groups-alist)
  15395 	       (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
  15396 		 (if old
  15397 		     (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
  15398 		   (push alist org-tag-groups-alist-for-agenda)))))))))
  15399     ;; Refresh the menu once after loading all the agenda buffers.
  15400     (when org-agenda-file-menu-enabled
  15401       (org-install-agenda-files-menu))))
  15402 
  15403 
  15404 ;;;; CDLaTeX minor mode
  15405 
  15406 (defvar org-cdlatex-mode-map (make-sparse-keymap)
  15407   "Keymap for the minor `org-cdlatex-mode'.")
  15408 
  15409 (org-defkey org-cdlatex-mode-map (kbd "_") #'org-cdlatex-underscore-caret)
  15410 (org-defkey org-cdlatex-mode-map (kbd "^") #'org-cdlatex-underscore-caret)
  15411 (org-defkey org-cdlatex-mode-map (kbd "`") #'cdlatex-math-symbol)
  15412 (org-defkey org-cdlatex-mode-map (kbd "'") #'org-cdlatex-math-modify)
  15413 (org-defkey org-cdlatex-mode-map (kbd "C-c {") #'org-cdlatex-environment-indent)
  15414 
  15415 (defvar org-cdlatex-texmathp-advice-is-done nil
  15416   "Flag remembering if we have applied the advice to texmathp already.")
  15417 
  15418 (define-minor-mode org-cdlatex-mode
  15419   "Toggle the minor `org-cdlatex-mode'.
  15420 This mode supports entering LaTeX environment and math in LaTeX fragments
  15421 in Org mode.
  15422 \\{org-cdlatex-mode-map}"
  15423   :lighter " OCDL"
  15424   (when org-cdlatex-mode
  15425     (require 'cdlatex)
  15426     (run-hooks 'cdlatex-mode-hook)
  15427     (cdlatex-compute-tables))
  15428   (unless org-cdlatex-texmathp-advice-is-done
  15429     (setq org-cdlatex-texmathp-advice-is-done t)
  15430     (advice-add 'texmathp :around #'org--math-always-on)))
  15431 
  15432 (defun org--math-always-on (orig-fun &rest args)
  15433   "Always return t in Org buffers.
  15434 This is because we want to insert math symbols without dollars even outside
  15435 the LaTeX math segments.  If Org mode thinks that point is actually inside
  15436 an embedded LaTeX fragment, let `texmathp' do its job.
  15437 `\\[org-cdlatex-mode-map]'"
  15438   (interactive)
  15439   (cond
  15440    ((not (derived-mode-p 'org-mode)) (apply orig-fun args))
  15441    ((eq this-command 'cdlatex-math-symbol)
  15442     (setq texmathp-why '("cdlatex-math-symbol in org-mode" . 0))
  15443     t)
  15444    (t
  15445     (let ((p (org-inside-LaTeX-fragment-p)))
  15446       (when p ;; FIXME: Shouldn't we return t when `p' is nil?
  15447 	(if (member (car p)
  15448 	            (plist-get org-format-latex-options :matchers))
  15449 	    (progn
  15450 	      (setq texmathp-why '("Org mode embedded math" . 0))
  15451 	      t)
  15452 	  (apply orig-fun args)))))))
  15453 
  15454 (defun turn-on-org-cdlatex ()
  15455   "Unconditionally turn on `org-cdlatex-mode'."
  15456   (org-cdlatex-mode 1))
  15457 
  15458 (defun org-try-cdlatex-tab ()
  15459   "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
  15460 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
  15461   - inside a LaTeX fragment, or
  15462   - after the first word in a line, where an abbreviation expansion could
  15463     insert a LaTeX environment."
  15464   (when org-cdlatex-mode
  15465     (cond
  15466      ;; Before any word on the line: No expansion possible.
  15467      ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
  15468      ;; Just after first word on the line: Expand it.  Make sure it
  15469      ;; cannot happen on headlines, though.
  15470      ((save-excursion
  15471 	(skip-chars-backward "a-zA-Z0-9*")
  15472 	(skip-chars-backward " \t")
  15473 	(and (bolp) (not (org-at-heading-p))))
  15474       (cdlatex-tab) t)
  15475      ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
  15476 
  15477 (defun org-cdlatex-underscore-caret (&optional _arg)
  15478   "Execute `cdlatex-sub-superscript' in LaTeX fragments.
  15479 Revert to the normal definition outside of these fragments."
  15480   (interactive "P")
  15481   (if (org-inside-LaTeX-fragment-p)
  15482       (call-interactively 'cdlatex-sub-superscript)
  15483     (let (org-cdlatex-mode)
  15484       (call-interactively (key-binding (vector last-input-event))))))
  15485 
  15486 (defun org-cdlatex-math-modify (&optional _arg)
  15487   "Execute `cdlatex-math-modify' in LaTeX fragments.
  15488 Revert to the normal definition outside of these fragments."
  15489   (interactive "P")
  15490   (if (org-inside-LaTeX-fragment-p)
  15491       (call-interactively 'cdlatex-math-modify)
  15492     (let (org-cdlatex-mode)
  15493       (call-interactively (key-binding (vector last-input-event))))))
  15494 
  15495 (defun org-cdlatex-environment-indent (&optional environment item)
  15496   "Execute `cdlatex-environment' and indent the inserted environment.
  15497 
  15498 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
  15499 
  15500 The inserted environment is indented to current indentation
  15501 unless point is at the beginning of the line, in which the
  15502 environment remains unintended."
  15503   (interactive)
  15504   ;; cdlatex-environment always return nil.  Therefore, capture output
  15505   ;; first and determine if an environment was selected.
  15506   (let* ((beg (point-marker))
  15507 	 (end (copy-marker (point) t))
  15508 	 (inserted (progn
  15509 		     (ignore-errors (cdlatex-environment environment item))
  15510 		     (< beg end)))
  15511 	 ;; Figure out how many lines to move forward after the
  15512 	 ;; environment has been inserted.
  15513 	 (lines (when inserted
  15514 		  (save-excursion
  15515 		    (- (cl-loop while (< beg (point))
  15516 				with x = 0
  15517 				do (forward-line -1)
  15518 				(cl-incf x)
  15519 				finally return x)
  15520 		       (if (progn (goto-char beg)
  15521 				  (and (progn (skip-chars-forward " \t") (eolp))
  15522 				       (progn (skip-chars-backward " \t") (bolp))))
  15523 			   1 0)))))
  15524 	 (env (org-trim (delete-and-extract-region beg end))))
  15525     (when inserted
  15526       ;; Get indentation of next line unless at column 0.
  15527       (let ((ind (if (bolp) 0
  15528 		   (save-excursion
  15529 		     (org-return t)
  15530 		     (prog1 (current-indentation)
  15531 		       (when (progn (skip-chars-forward " \t") (eolp))
  15532 			 (delete-region beg (point)))))))
  15533 	    (bol (progn (skip-chars-backward " \t") (bolp))))
  15534 	;; Insert a newline before environment unless at column zero
  15535 	;; to "escape" the current line.  Insert a newline if
  15536 	;; something is one the same line as \end{ENVIRONMENT}.
  15537 	(insert
  15538 	 (concat (unless bol "\n") env
  15539 		 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
  15540 	(unless (zerop ind)
  15541 	  (save-excursion
  15542 	    (goto-char beg)
  15543 	    (while (< (point) end)
  15544 	      (unless (eolp) (indent-line-to ind))
  15545 	      (forward-line))))
  15546 	(goto-char beg)
  15547 	(forward-line lines)
  15548 	(indent-line-to ind)))
  15549     (set-marker beg nil)
  15550     (set-marker end nil)))
  15551 
  15552 
  15553 ;;;; LaTeX fragments
  15554 
  15555 (defun org-inside-LaTeX-fragment-p ()
  15556   "Test if point is inside a LaTeX fragment.
  15557 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
  15558 sequence appearing also before point.
  15559 Even though the matchers for math are configurable, this function assumes
  15560 that \\begin, \\(, \\[, and $$ are always used.  Only the single dollar
  15561 delimiters are skipped when they have been removed by customization.
  15562 The return value is nil, or a cons cell with the delimiter and the
  15563 position of this delimiter.
  15564 
  15565 This function does a reasonably good job, but can locally be fooled by
  15566 for example currency specifications.  For example it will assume being in
  15567 inline math after \"$22.34\".  The LaTeX fragment formatter will only format
  15568 fragments that are properly closed, but during editing, we have to live
  15569 with the uncertainty caused by missing closing delimiters.  This function
  15570 looks only before point, not after."
  15571   (catch 'exit
  15572     (let ((pos (point))
  15573 	  (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
  15574 	  (lim (progn
  15575 		 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil
  15576 				     'move)
  15577 		 (point)))
  15578 	  dd-on str (start 0) m re)
  15579       (goto-char pos)
  15580       (when dodollar
  15581 	(setq str (concat (buffer-substring lim (point)) "\000 X$.")
  15582 	      re (nth 1 (assoc "$" org-latex-regexps)))
  15583 	(while (string-match re str start)
  15584 	  (cond
  15585 	   ((= (match-end 0) (length str))
  15586 	    (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
  15587 	   ((= (match-end 0) (- (length str) 5))
  15588 	    (throw 'exit nil))
  15589 	   (t (setq start (match-end 0))))))
  15590       (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
  15591 	(goto-char pos)
  15592 	(and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
  15593 	(and (match-beginning 2) (throw 'exit nil))
  15594 	;; count $$
  15595 	(while (re-search-backward "\\$\\$" lim t)
  15596 	  (setq dd-on (not dd-on)))
  15597 	(goto-char pos)
  15598 	(when dd-on (cons "$$" m))))))
  15599 
  15600 (defun org-inside-latex-macro-p ()
  15601   "Is point inside a LaTeX macro or its arguments?"
  15602   (save-match-data
  15603     (org-in-regexp
  15604      "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
  15605 
  15606 (defun org--make-preview-overlay (beg end image &optional imagetype)
  15607   "Build an overlay between BEG and END using IMAGE file.
  15608 Argument IMAGETYPE is the extension of the displayed image,
  15609 as a string.  It defaults to \"png\"."
  15610   (let ((ov (make-overlay beg end))
  15611 	(imagetype (or (intern imagetype) 'png)))
  15612     (overlay-put ov 'org-overlay-type 'org-latex-overlay)
  15613     (overlay-put ov 'evaporate t)
  15614     (overlay-put ov
  15615 		 'modification-hooks
  15616 		 (list (lambda (o _flag _beg _end &optional _l)
  15617 			 (delete-overlay o))))
  15618     (overlay-put ov
  15619 		 'display
  15620 		 (list 'image :type imagetype :file image :ascent 'center))))
  15621 
  15622 (defun org-clear-latex-preview (&optional beg end)
  15623   "Remove all overlays with LaTeX fragment images in current buffer.
  15624 When optional arguments BEG and END are non-nil, remove all
  15625 overlays between them instead.  Return a non-nil value when some
  15626 overlays were removed, nil otherwise."
  15627   (let ((overlays
  15628 	 (cl-remove-if-not
  15629 	  (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
  15630 	  (overlays-in (or beg (point-min)) (or end (point-max))))))
  15631     (mapc #'delete-overlay overlays)
  15632     overlays))
  15633 
  15634 (defun org--latex-preview-region (beg end)
  15635   "Preview LaTeX fragments between BEG and END.
  15636 BEG and END are buffer positions."
  15637   (let ((file (buffer-file-name (buffer-base-buffer))))
  15638     (save-excursion
  15639       (org-format-latex
  15640        (concat org-preview-latex-image-directory "org-ltximg")
  15641        beg end
  15642        ;; Emacs cannot overlay images from remote hosts.  Create it in
  15643        ;; `temporary-file-directory' instead.
  15644        (if (or (not file) (file-remote-p file))
  15645 	   temporary-file-directory
  15646 	 default-directory)
  15647        'overlays nil 'forbuffer org-preview-latex-default-process))))
  15648 
  15649 (defun org-latex-preview (&optional arg)
  15650   "Toggle preview of the LaTeX fragment at point.
  15651 
  15652 If the cursor is on a LaTeX fragment, create the image and
  15653 overlay it over the source code, if there is none.  Remove it
  15654 otherwise.  If there is no fragment at point, display images for
  15655 all fragments in the current section.  With an active region,
  15656 display images for all fragments in the region.
  15657 
  15658 With a `\\[universal-argument]' prefix argument ARG, clear images \
  15659 for all fragments
  15660 in the current section.
  15661 
  15662 With a `\\[universal-argument] \\[universal-argument]' prefix \
  15663 argument ARG, display image for all
  15664 fragments in the buffer.
  15665 
  15666 With a `\\[universal-argument] \\[universal-argument] \
  15667 \\[universal-argument]' prefix argument ARG, clear image for all
  15668 fragments in the buffer."
  15669   (interactive "P")
  15670   (cond
  15671    ((not (display-graphic-p)) nil)
  15672    ;; Clear whole buffer.
  15673    ((equal arg '(64))
  15674     (org-clear-latex-preview (point-min) (point-max))
  15675     (message "LaTeX previews removed from buffer"))
  15676    ;; Preview whole buffer.
  15677    ((equal arg '(16))
  15678     (message "Creating LaTeX previews in buffer...")
  15679     (org--latex-preview-region (point-min) (point-max))
  15680     (message "Creating LaTeX previews in buffer... done."))
  15681    ;; Clear current section.
  15682    ((equal arg '(4))
  15683     (org-clear-latex-preview
  15684      (if (use-region-p)
  15685          (region-beginning)
  15686        (if (org-before-first-heading-p) (point-min)
  15687          (save-excursion
  15688 	   (org-with-limited-levels (org-back-to-heading t) (point)))))
  15689      (if (use-region-p)
  15690          (region-end)
  15691        (org-with-limited-levels (org-entry-end-position)))))
  15692    ((use-region-p)
  15693     (message "Creating LaTeX previews in region...")
  15694     (org--latex-preview-region (region-beginning) (region-end))
  15695     (message "Creating LaTeX previews in region... done."))
  15696    ;; Toggle preview on LaTeX code at point.
  15697    ((let ((datum (org-element-context)))
  15698       (and (memq (org-element-type datum) '(latex-environment latex-fragment))
  15699 	   (let ((beg (org-element-property :begin datum))
  15700 		 (end (org-element-property :end datum)))
  15701 	     (if (org-clear-latex-preview beg end)
  15702 		 (message "LaTeX preview removed")
  15703 	       (message "Creating LaTeX preview...")
  15704 	       (org--latex-preview-region beg end)
  15705 	       (message "Creating LaTeX preview... done."))
  15706 	     t))))
  15707    ;; Preview current section.
  15708    (t
  15709     (let ((beg (if (org-before-first-heading-p) (point-min)
  15710 		 (save-excursion
  15711 		   (org-with-limited-levels (org-back-to-heading t) (point)))))
  15712 	  (end (org-with-limited-levels (org-entry-end-position))))
  15713       (message "Creating LaTeX previews in section...")
  15714       (org--latex-preview-region beg end)
  15715       (message "Creating LaTeX previews in section... done.")))))
  15716 
  15717 (defun org-format-latex
  15718     (prefix &optional beg end dir overlays msg forbuffer processing-type)
  15719   "Replace LaTeX fragments with links to an image.
  15720 
  15721 The function takes care of creating the replacement image.
  15722 
  15723 Only consider fragments between BEG and END when those are
  15724 provided.
  15725 
  15726 When optional argument OVERLAYS is non-nil, display the image on
  15727 top of the fragment instead of replacing it.
  15728 
  15729 PROCESSING-TYPE is the conversion method to use, as a symbol.
  15730 
  15731 Some of the options can be changed using the variable
  15732 `org-format-latex-options', which see."
  15733   (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
  15734   (unless (eq processing-type 'verbatim)
  15735     (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
  15736 	   (cnt 0)
  15737 	   checkdir-flag)
  15738       (goto-char (or beg (point-min)))
  15739       ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
  15740       (when (and overlays (memq processing-type '(dvipng imagemagick)))
  15741 	(overlay-recenter (or end (point-max))))
  15742       (while (re-search-forward math-regexp end t)
  15743 	(unless (and overlays
  15744 		     (eq (get-char-property (point) 'org-overlay-type)
  15745 			 'org-latex-overlay))
  15746 	  (let* ((context (org-element-context))
  15747 		 (type (org-element-type context)))
  15748 	    (when (memq type '(latex-environment latex-fragment))
  15749 	      (let ((block-type (eq type 'latex-environment))
  15750 		    (value (org-element-property :value context))
  15751 		    (beg (org-element-property :begin context))
  15752 		    (end (save-excursion
  15753 			   (goto-char (org-element-property :end context))
  15754 			   (skip-chars-backward " \r\t\n")
  15755 			   (point))))
  15756 		(cond
  15757 		 ((eq processing-type 'mathjax)
  15758 		  ;; Prepare for MathJax processing.
  15759 		  (if (not (string-match "\\`\\$\\$?" value))
  15760 		      (goto-char end)
  15761 		    (delete-region beg end)
  15762 		    (if (string= (match-string 0 value) "$$")
  15763 			(insert "\\[" (substring value 2 -2) "\\]")
  15764 		      (insert "\\(" (substring value 1 -1) "\\)"))))
  15765 		 ((eq processing-type 'html)
  15766 		  (goto-char beg)
  15767 		  (delete-region beg end)
  15768 		  (insert (org-format-latex-as-html value)))
  15769 		 ((assq processing-type org-preview-latex-process-alist)
  15770 		  ;; Process to an image.
  15771 		  (cl-incf cnt)
  15772 		  (goto-char beg)
  15773 		  (let* ((processing-info
  15774 			  (cdr (assq processing-type org-preview-latex-process-alist)))
  15775 			 (face (face-at-point))
  15776 			 ;; Get the colors from the face at point.
  15777 			 (fg
  15778 			  (let ((color (plist-get org-format-latex-options
  15779 						  :foreground)))
  15780                             (if forbuffer
  15781                                 (cond
  15782                                  ((eq color 'auto)
  15783                                   (face-attribute face :foreground nil 'default))
  15784                                  ((eq color 'default)
  15785                                   (face-attribute 'default :foreground nil))
  15786                                  (t color))
  15787                               color)))
  15788 			 (bg
  15789 			  (let ((color (plist-get org-format-latex-options
  15790 						  :background)))
  15791                             (if forbuffer
  15792                                 (cond
  15793                                  ((eq color 'auto)
  15794                                   (face-attribute face :background nil 'default))
  15795                                  ((eq color 'default)
  15796                                   (face-attribute 'default :background nil))
  15797                                  (t color))
  15798                               color)))
  15799 			 (hash (sha1 (prin1-to-string
  15800 				      (list org-format-latex-header
  15801 					    org-latex-default-packages-alist
  15802 					    org-latex-packages-alist
  15803 					    org-format-latex-options
  15804 					    forbuffer value fg bg))))
  15805 			 (imagetype (or (plist-get processing-info :image-output-type) "png"))
  15806 			 (absprefix (expand-file-name prefix dir))
  15807 			 (linkfile (format "%s_%s.%s" prefix hash imagetype))
  15808 			 (movefile (format "%s_%s.%s" absprefix hash imagetype))
  15809 			 (sep (and block-type "\n\n"))
  15810 			 (link (concat sep "[[file:" linkfile "]]" sep))
  15811 			 (options
  15812 			  (org-combine-plists
  15813 			   org-format-latex-options
  15814 			   `(:foreground ,fg :background ,bg))))
  15815 		    (when msg (message msg cnt))
  15816 		    (unless checkdir-flag ; Ensure the directory exists.
  15817 		      (setq checkdir-flag t)
  15818 		      (let ((todir (file-name-directory absprefix)))
  15819 			(unless (file-directory-p todir)
  15820 			  (make-directory todir t))))
  15821 		    (unless (file-exists-p movefile)
  15822 		      (org-create-formula-image
  15823 		       value movefile options forbuffer processing-type))
  15824 		    (if overlays
  15825 			(progn
  15826 			  (dolist (o (overlays-in beg end))
  15827 			    (when (eq (overlay-get o 'org-overlay-type)
  15828 				      'org-latex-overlay)
  15829 			      (delete-overlay o)))
  15830 			  (org--make-preview-overlay beg end movefile imagetype)
  15831 			  (goto-char end))
  15832 		      (delete-region beg end)
  15833 		      (insert
  15834 		       (org-add-props link
  15835 			   (list 'org-latex-src
  15836 				 (replace-regexp-in-string "\"" "" value)
  15837 				 'org-latex-src-embed-type
  15838 				 (if block-type 'paragraph 'character)))))))
  15839 		 ((eq processing-type 'mathml)
  15840 		  ;; Process to MathML.
  15841 		  (unless (org-format-latex-mathml-available-p)
  15842 		    (user-error "LaTeX to MathML converter not configured"))
  15843 		  (cl-incf cnt)
  15844 		  (when msg (message msg cnt))
  15845 		  (goto-char beg)
  15846 		  (delete-region beg end)
  15847 		  (insert (org-format-latex-as-mathml
  15848 			   value block-type prefix dir)))
  15849 		 (t
  15850 		  (error "Unknown conversion process %s for LaTeX fragments"
  15851 			 processing-type)))))))))))
  15852 
  15853 (defun org-create-math-formula (latex-frag &optional mathml-file)
  15854   "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
  15855 Use `org-latex-to-mathml-convert-command'.  If the conversion is
  15856 successful, return the portion between \"<math...> </math>\"
  15857 elements otherwise return nil.  When MATHML-FILE is specified,
  15858 write the results in to that file.  When invoked as an
  15859 interactive command, prompt for LATEX-FRAG, with initial value
  15860 set to the current active region and echo the results for user
  15861 inspection."
  15862   (interactive (list (let ((frag (when (org-region-active-p)
  15863 				   (buffer-substring-no-properties
  15864 				    (region-beginning) (region-end)))))
  15865 		       (read-string "LaTeX Fragment: " frag nil frag))))
  15866   (unless latex-frag (user-error "Invalid LaTeX fragment"))
  15867   (let* ((tmp-in-file
  15868 	  (let ((file (file-relative-name
  15869 		       (make-temp-name (expand-file-name "ltxmathml-in")))))
  15870 	    (write-region latex-frag nil file)
  15871 	    file))
  15872 	 (tmp-out-file (file-relative-name
  15873 			(make-temp-name (expand-file-name  "ltxmathml-out"))))
  15874 	 (cmd (format-spec
  15875 	       org-latex-to-mathml-convert-command
  15876 	       `((?j . ,(and org-latex-to-mathml-jar-file
  15877 			     (shell-quote-argument
  15878 			      (expand-file-name
  15879 			       org-latex-to-mathml-jar-file))))
  15880 		 (?I . ,(shell-quote-argument tmp-in-file))
  15881 		 (?i . ,latex-frag)
  15882 		 (?o . ,(shell-quote-argument tmp-out-file)))))
  15883 	 mathml shell-command-output)
  15884     (when (called-interactively-p 'any)
  15885       (unless (org-format-latex-mathml-available-p)
  15886 	(user-error "LaTeX to MathML converter not configured")))
  15887     (message "Running %s" cmd)
  15888     (setq shell-command-output (shell-command-to-string cmd))
  15889     (setq mathml
  15890 	  (when (file-readable-p tmp-out-file)
  15891 	    (with-current-buffer (find-file-noselect tmp-out-file t)
  15892 	      (goto-char (point-min))
  15893 	      (when (re-search-forward
  15894 		     (format "<math[^>]*?%s[^>]*?>\\(.\\|\n\\)*</math>"
  15895 			     (regexp-quote
  15896 			      "xmlns=\"http://www.w3.org/1998/Math/MathML\""))
  15897 		     nil t)
  15898 		(prog1 (match-string 0) (kill-buffer))))))
  15899     (cond
  15900      (mathml
  15901       (setq mathml
  15902 	    (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
  15903       (when mathml-file
  15904 	(write-region mathml nil mathml-file))
  15905       (when (called-interactively-p 'any)
  15906 	(message mathml)))
  15907      ((warn "LaTeX to MathML conversion failed")
  15908       (message shell-command-output)))
  15909     (delete-file tmp-in-file)
  15910     (when (file-exists-p tmp-out-file)
  15911       (delete-file tmp-out-file))
  15912     mathml))
  15913 
  15914 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
  15915 					      prefix &optional dir)
  15916   "Use `org-create-math-formula' but check local cache first."
  15917   (let* ((absprefix (expand-file-name prefix dir))
  15918 	 (print-length nil) (print-level nil)
  15919 	 (formula-id (concat
  15920 		      "formula-"
  15921 		      (sha1
  15922 		       (prin1-to-string
  15923 			(list latex-frag
  15924 			      org-latex-to-mathml-convert-command)))))
  15925 	 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
  15926 	 (formula-cache-dir (file-name-directory formula-cache)))
  15927 
  15928     (unless (file-directory-p formula-cache-dir)
  15929       (make-directory formula-cache-dir t))
  15930 
  15931     (unless (file-exists-p formula-cache)
  15932       (org-create-math-formula latex-frag formula-cache))
  15933 
  15934     (if (file-exists-p formula-cache)
  15935 	;; Successful conversion.  Return the link to MathML file.
  15936 	(org-add-props
  15937 	    (format  "[[file:%s]]" (file-relative-name formula-cache dir))
  15938 	    (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
  15939 		  'org-latex-src-embed-type (if latex-frag-type
  15940 						'paragraph 'character)))
  15941       ;; Failed conversion.  Return the LaTeX fragment verbatim
  15942       latex-frag)))
  15943 
  15944 (defun org-format-latex-as-html (latex-fragment)
  15945   "Convert LATEX-FRAGMENT to HTML.
  15946 This uses  `org-latex-to-html-convert-command', which see."
  15947   (let ((cmd (format-spec org-latex-to-html-convert-command
  15948 			  `((?i . ,latex-fragment)))))
  15949     (message "Running %s" cmd)
  15950     (shell-command-to-string cmd)))
  15951 
  15952 (defun org--get-display-dpi ()
  15953   "Get the DPI of the display.
  15954 The function assumes that the display has the same pixel width in
  15955 the horizontal and vertical directions."
  15956   (if (display-graphic-p)
  15957       (round (/ (display-pixel-height)
  15958 		(/ (display-mm-height) 25.4)))
  15959     (error "Attempt to calculate the dpi of a non-graphic display")))
  15960 
  15961 (defun org-create-formula-image
  15962     (string tofile options buffer &optional processing-type)
  15963   "Create an image from LaTeX source using external processes.
  15964 
  15965 The LaTeX STRING is saved to a temporary LaTeX file, then
  15966 converted to an image file by process PROCESSING-TYPE defined in
  15967 `org-preview-latex-process-alist'.  A nil value defaults to
  15968 `org-preview-latex-default-process'.
  15969 
  15970 The generated image file is eventually moved to TOFILE.
  15971 
  15972 The OPTIONS argument controls the size, foreground color and
  15973 background color of the generated image.
  15974 
  15975 When BUFFER non-nil, this function is used for LaTeX previewing.
  15976 Otherwise, it is used to deal with LaTeX snippets showed in
  15977 a HTML file."
  15978   (let* ((processing-type (or processing-type
  15979 			      org-preview-latex-default-process))
  15980 	 (processing-info
  15981 	  (cdr (assq processing-type org-preview-latex-process-alist)))
  15982 	 (programs (plist-get processing-info :programs))
  15983 	 (error-message (or (plist-get processing-info :message) ""))
  15984 	 (image-input-type (plist-get processing-info :image-input-type))
  15985 	 (image-output-type (plist-get processing-info :image-output-type))
  15986 	 (post-clean (or (plist-get processing-info :post-clean)
  15987 			 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
  15988 			   ".svg" ".png" ".jpg" ".jpeg" ".out")))
  15989 	 (latex-header
  15990 	  (or (plist-get processing-info :latex-header)
  15991 	      (org-latex-make-preamble
  15992 	       (org-export-get-environment (org-export-get-backend 'latex))
  15993 	       org-format-latex-header
  15994 	       'snippet)))
  15995 	 (latex-compiler (plist-get processing-info :latex-compiler))
  15996 	 (tmpdir temporary-file-directory)
  15997 	 (texfilebase (make-temp-name
  15998 		       (expand-file-name "orgtex" tmpdir)))
  15999 	 (texfile (concat texfilebase ".tex"))
  16000 	 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
  16001 				'(1.0 . 1.0)))
  16002 	 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
  16003 		   (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
  16004 	 (dpi (* scale (if (and buffer (display-graphic-p)) (org--get-display-dpi) 140.0)))
  16005 	 (fg (or (plist-get options (if buffer :foreground :html-foreground))
  16006 		 "Black"))
  16007 	 (bg (or (plist-get options (if buffer :background :html-background))
  16008 		 "Transparent"))
  16009 	 (image-converter
  16010           (or (and (string= bg "Transparent")
  16011                    (plist-get processing-info :transparent-image-converter))
  16012               (plist-get processing-info :image-converter)))
  16013          (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
  16014 	 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
  16015     (dolist (program programs)
  16016       (org-check-external-command program error-message))
  16017     (if (eq fg 'default)
  16018 	(setq fg (org-latex-color :foreground))
  16019       (setq fg (org-latex-color-format fg)))
  16020     (setq bg (cond
  16021 	      ((eq bg 'default) (org-latex-color :background))
  16022 	      ((string= bg "Transparent") nil)
  16023 	      (t (org-latex-color-format bg))))
  16024     ;; Remove TeX \par at end of snippet to avoid trailing space.
  16025     (if (string-suffix-p string "\n")
  16026         (aset string (1- (length string)) ?%)
  16027       (setq string (concat string "%")))
  16028     (with-temp-file texfile
  16029       (insert latex-header)
  16030       (insert "\n\\begin{document}\n"
  16031 	      "\\definecolor{fg}{rgb}{" fg "}%\n"
  16032 	      (if bg
  16033 		  (concat "\\definecolor{bg}{rgb}{" bg "}%\n"
  16034 			  "\n\\pagecolor{bg}%\n")
  16035 		"")
  16036 	      "\n{\\color{fg}\n"
  16037 	      string
  16038 	      "\n}\n"
  16039 	      "\n\\end{document}\n"))
  16040     (let* ((err-msg (format "Please adjust `%s' part of \
  16041 `org-preview-latex-process-alist'."
  16042 			    processing-type))
  16043 	   (image-input-file
  16044 	    (org-compile-file
  16045 	     texfile latex-compiler image-input-type err-msg log-buf))
  16046 	   (image-output-file
  16047 	    (org-compile-file
  16048 	     image-input-file image-converter image-output-type err-msg log-buf
  16049 	     `((?D . ,(shell-quote-argument (format "%s" dpi)))
  16050 	       (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
  16051       (copy-file image-output-file tofile 'replace)
  16052       (dolist (e post-clean)
  16053 	(when (file-exists-p (concat texfilebase e))
  16054 	  (delete-file (concat texfilebase e))))
  16055       image-output-file)))
  16056 
  16057 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
  16058   "Fill a LaTeX header template TPL.
  16059 In the template, the following place holders will be recognized:
  16060 
  16061  [DEFAULT-PACKAGES]      \\usepackage statements for DEF-PKG
  16062  [NO-DEFAULT-PACKAGES]   do not include DEF-PKG
  16063  [PACKAGES]              \\usepackage statements for PKG
  16064  [NO-PACKAGES]           do not include PKG
  16065  [EXTRA]                 the string EXTRA
  16066  [NO-EXTRA]              do not include EXTRA
  16067 
  16068 For backward compatibility, if both the positive and the negative place
  16069 holder is missing, the positive one (without the \"NO-\") will be
  16070 assumed to be present at the end of the template.
  16071 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
  16072 EXTRA is a string.
  16073 SNIPPETS-P indicates if this is run to create snippet images for HTML."
  16074   (let (rpl (end ""))
  16075     (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
  16076 	(setq rpl (if (or (match-end 1) (not def-pkg))
  16077 		      "" (org-latex-packages-to-string def-pkg snippets-p t))
  16078 	      tpl (replace-match rpl t t tpl))
  16079       (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
  16080 
  16081     (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
  16082 	(setq rpl (if (or (match-end 1) (not pkg))
  16083 		      "" (org-latex-packages-to-string pkg snippets-p t))
  16084 	      tpl (replace-match rpl t t tpl))
  16085       (when pkg (setq end
  16086 		      (concat end "\n"
  16087 			      (org-latex-packages-to-string pkg snippets-p)))))
  16088 
  16089     (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
  16090 	(setq rpl (if (or (match-end 1) (not extra))
  16091 		      "" (concat extra "\n"))
  16092 	      tpl (replace-match rpl t t tpl))
  16093       (when (and extra (string-match "\\S-" extra))
  16094 	(setq end (concat end "\n" extra))))
  16095 
  16096     (if (string-match "\\S-" end)
  16097 	(concat tpl "\n" end)
  16098       tpl)))
  16099 
  16100 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
  16101   "Turn an alist of packages into a string with the \\usepackage macros."
  16102   (setq pkg (mapconcat (lambda(p)
  16103 			 (cond
  16104 			  ((stringp p) p)
  16105 			  ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
  16106 			   (format "%% Package %s omitted" (cadr p)))
  16107 			  ((equal "" (car p))
  16108 			   (format "\\usepackage{%s}" (cadr p)))
  16109 			  (t
  16110 			   (format "\\usepackage[%s]{%s}"
  16111 				   (car p) (cadr p)))))
  16112 		       pkg
  16113 		       "\n"))
  16114   (if newline (concat pkg "\n") pkg))
  16115 
  16116 (defun org-dvipng-color (attr)
  16117   "Return a RGB color specification for dvipng."
  16118   (org-dvipng-color-format (face-attribute 'default attr nil)))
  16119 
  16120 (defun org-dvipng-color-format (color-name)
  16121   "Convert COLOR-NAME to a RGB color value for dvipng."
  16122   (apply #'format "rgb %s %s %s"
  16123 	 (mapcar 'org-normalize-color
  16124 		 (color-values color-name))))
  16125 
  16126 (defun org-latex-color (attr)
  16127   "Return a RGB color for the LaTeX color package."
  16128   (org-latex-color-format (face-attribute 'default attr nil)))
  16129 
  16130 (defun org-latex-color-format (color-name)
  16131   "Convert COLOR-NAME to a RGB color value."
  16132   (apply #'format "%s,%s,%s"
  16133 	 (mapcar 'org-normalize-color
  16134 		 (color-values color-name))))
  16135 
  16136 (defun org-normalize-color (value)
  16137   "Return string to be used as color value for an RGB component."
  16138   (format "%g" (/ value 65535.0)))
  16139 
  16140 
  16141 ;; Image display
  16142 
  16143 (defvar-local org-inline-image-overlays nil)
  16144 
  16145 (defun org--inline-image-overlays (&optional beg end)
  16146   "Return image overlays between BEG and END."
  16147   (let* ((beg (or beg (point-min)))
  16148          (end (or end (point-max)))
  16149          (overlays (overlays-in beg end))
  16150          result)
  16151     (dolist (ov overlays result)
  16152       (when (memq ov org-inline-image-overlays)
  16153         (push ov result)))))
  16154 
  16155 (defun org-toggle-inline-images (&optional include-linked beg end)
  16156   "Toggle the display of inline images.
  16157 INCLUDE-LINKED is passed to `org-display-inline-images'."
  16158   (interactive "P")
  16159   (if (org--inline-image-overlays beg end)
  16160       (progn
  16161         (org-remove-inline-images beg end)
  16162         (when (called-interactively-p 'interactive)
  16163 	  (message "Inline image display turned off")))
  16164     (org-display-inline-images include-linked nil beg end)
  16165     (when (called-interactively-p 'interactive)
  16166       (let ((new (org--inline-image-overlays beg end)))
  16167         (message (if new
  16168 		     (format "%d images displayed inline"
  16169 			     (length new))
  16170 		   "No images to display inline"))))))
  16171 
  16172 (defun org-redisplay-inline-images ()
  16173   "Assure display of inline images and refresh them."
  16174   (interactive)
  16175   (org-toggle-inline-images)
  16176   (unless org-inline-image-overlays
  16177     (org-toggle-inline-images)))
  16178 
  16179 ;; For without-x builds.
  16180 (declare-function image-flush "image" (spec &optional frame))
  16181 
  16182 (defcustom org-display-remote-inline-images 'skip
  16183   "How to display remote inline images.
  16184 Possible values of this option are:
  16185 
  16186 skip        Don't display remote images.
  16187 download    Always download and display remote images.
  16188 cache       Display remote images, and open them in separate buffers
  16189             for caching.  Silently update the image buffer when a file
  16190             change is detected."
  16191   :group 'org-appearance
  16192   :package-version '(Org . "9.4")
  16193   :type '(choice
  16194 	  (const :tag "Ignore remote images" skip)
  16195 	  (const :tag "Always display remote images" download)
  16196 	  (const :tag "Display and silently update remote images" cache))
  16197   :safe #'symbolp)
  16198 
  16199 (defun org--create-inline-image (file width)
  16200   "Create image located at FILE, or return nil.
  16201 WIDTH is the width of the image.  The image may not be created
  16202 according to the value of `org-display-remote-inline-images'."
  16203   (let* ((remote? (file-remote-p file))
  16204 	 (file-or-data
  16205 	  (pcase org-display-remote-inline-images
  16206 	    ((guard (not remote?)) file)
  16207 	    (`download (with-temp-buffer
  16208 			 (set-buffer-multibyte nil)
  16209 			 (insert-file-contents-literally file)
  16210 			 (buffer-string)))
  16211 	    (`cache (let ((revert-without-query '(".")))
  16212 		      (with-current-buffer (find-file-noselect file)
  16213 			(buffer-string))))
  16214 	    (`skip nil)
  16215 	    (other
  16216 	     (message "Invalid value of `org-display-remote-inline-images': %S"
  16217 		      other)
  16218 	     nil))))
  16219     (when file-or-data
  16220       (create-image file-or-data
  16221 		    (and (image-type-available-p 'imagemagick)
  16222 			 width
  16223 			 'imagemagick)
  16224 		    remote?
  16225 		    :width width :scale 1))))
  16226 
  16227 (defun org-display-inline-images (&optional include-linked refresh beg end)
  16228   "Display inline images.
  16229 
  16230 An inline image is a link which follows either of these
  16231 conventions:
  16232 
  16233   1. Its path is a file with an extension matching return value
  16234      from `image-file-name-regexp' and it has no contents.
  16235 
  16236   2. Its description consists in a single link of the previous
  16237      type.  In this case, that link must be a well-formed plain
  16238      or angle link, i.e., it must have an explicit \"file\" type.
  16239 
  16240 Equip each image with the key-map `image-map'.
  16241 
  16242 When optional argument INCLUDE-LINKED is non-nil, also links with
  16243 a text description part will be inlined.  This can be nice for
  16244 a quick look at those images, but it does not reflect what
  16245 exported files will look like.
  16246 
  16247 When optional argument REFRESH is non-nil, refresh existing
  16248 images between BEG and END.  This will create new image displays
  16249 only if necessary.
  16250 
  16251 BEG and END define the considered part.  They default to the
  16252 buffer boundaries with possible narrowing."
  16253   (interactive "P")
  16254   (when (display-graphic-p)
  16255     (when refresh
  16256       (org-remove-inline-images beg end)
  16257       (when (fboundp 'clear-image-cache) (clear-image-cache)))
  16258     (let ((end (or end (point-max))))
  16259       (org-with-point-at (or beg (point-min))
  16260 	(let* ((case-fold-search t)
  16261 	       (file-extension-re (image-file-name-regexp))
  16262 	       (link-abbrevs (mapcar #'car
  16263 				     (append org-link-abbrev-alist-local
  16264 					     org-link-abbrev-alist)))
  16265 	       ;; Check absolute, relative file names and explicit
  16266 	       ;; "file:" links.  Also check link abbreviations since
  16267 	       ;; some might expand to "file" links.
  16268 	       (file-types-re
  16269 		(format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)"
  16270 			(if (not link-abbrevs) ""
  16271 			  (concat "\\|" (regexp-opt link-abbrevs))))))
  16272 	  (while (re-search-forward file-types-re end t)
  16273 	    (let* ((link (org-element-lineage
  16274 			  (save-match-data (org-element-context))
  16275 			  '(link) t))
  16276                    (linktype (org-element-property :type link))
  16277 		   (inner-start (match-beginning 1))
  16278 		   (path
  16279 		    (cond
  16280 		     ;; No link at point; no inline image.
  16281 		     ((not link) nil)
  16282 		     ;; File link without a description.  Also handle
  16283 		     ;; INCLUDE-LINKED here since it should have
  16284 		     ;; precedence over the next case.  I.e., if link
  16285 		     ;; contains filenames in both the path and the
  16286 		     ;; description, prioritize the path only when
  16287 		     ;; INCLUDE-LINKED is non-nil.
  16288 		     ((or (not (org-element-property :contents-begin link))
  16289 			  include-linked)
  16290 		      (and (or (equal "file" linktype)
  16291                                (equal "attachment" linktype))
  16292 			   (org-element-property :path link)))
  16293 		     ;; Link with a description.  Check if description
  16294 		     ;; is a filename.  Even if Org doesn't have syntax
  16295 		     ;; for those -- clickable image -- constructs, fake
  16296 		     ;; them, as in `org-export-insert-image-links'.
  16297 		     ((not inner-start) nil)
  16298 		     (t
  16299 		      (org-with-point-at inner-start
  16300 			(and (looking-at
  16301 			      (if (char-equal ?< (char-after inner-start))
  16302 				  org-link-angle-re
  16303 				org-link-plain-re))
  16304 			     ;; File name must fill the whole
  16305 			     ;; description.
  16306 			     (= (org-element-property :contents-end link)
  16307 				(match-end 0))
  16308 			     (match-string 2)))))))
  16309 	      (when (and path (string-match-p file-extension-re path))
  16310 		(let ((file (if (equal "attachment" linktype)
  16311 				(progn
  16312                                   (require 'org-attach)
  16313 				  (ignore-errors (org-attach-expand path)))
  16314                               (expand-file-name path))))
  16315 		  (when (and file (file-exists-p file))
  16316 		    (let ((width (org-display-inline-image--width link))
  16317 			  (old (get-char-property-and-overlay
  16318 				(org-element-property :begin link)
  16319 				'org-image-overlay)))
  16320 		      (if (and (car-safe old) refresh)
  16321                           (image-flush (overlay-get (cdr old) 'display))
  16322 			(let ((image (org--create-inline-image file width)))
  16323 			  (when image
  16324 			    (let ((ov (make-overlay
  16325 				       (org-element-property :begin link)
  16326 				       (progn
  16327 					 (goto-char
  16328 					  (org-element-property :end link))
  16329 					 (skip-chars-backward " \t")
  16330 					 (point)))))
  16331                               ;; FIXME: See bug#59902.  We cannot rely
  16332                               ;; on Emacs to update image if the file
  16333                               ;; has changed.
  16334                               (image-flush image)
  16335 			      (overlay-put ov 'display image)
  16336 			      (overlay-put ov 'face 'default)
  16337 			      (overlay-put ov 'org-image-overlay t)
  16338 			      (overlay-put
  16339 			       ov 'modification-hooks
  16340 			       (list 'org-display-inline-remove-overlay))
  16341 			      (when (boundp 'image-map)
  16342 				(overlay-put ov 'keymap image-map))
  16343 			      (push ov org-inline-image-overlays))))))))))))))))
  16344 
  16345 (defvar visual-fill-column-width) ; Silence compiler warning
  16346 (defun org-display-inline-image--width (link)
  16347   "Determine the display width of the image LINK, in pixels.
  16348 - When `org-image-actual-width' is t, the image's pixel width is used.
  16349 - When `org-image-actual-width' is a number, that value will is used.
  16350 - When `org-image-actual-width' is nil or a list, the first :width attribute
  16351   set (if it exists) is used to set the image width.  A width of X% is
  16352   divided by 100.
  16353   If no :width attribute is given and `org-image-actual-width' is a list with
  16354   a number as the car, then that number is used as the default value.
  16355   If the value is a float between 0 and 2, it interpreted as that proportion
  16356   of the text width in the buffer."
  16357   ;; Apply `org-image-actual-width' specifications.
  16358   ;; Support subtree-level property "ORG-IMAGE-ACTUAL-WIDTH" specified
  16359   ;; width.
  16360   (let ((org-image-actual-width (org-property-or-variable-value 'org-image-actual-width)))
  16361     (cond
  16362      ((eq org-image-actual-width t) nil)
  16363      ((listp org-image-actual-width)
  16364       (let* ((case-fold-search t)
  16365              (par (org-element-lineage link '(paragraph)))
  16366              (attr-re "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)")
  16367              (par-end (org-element-property :post-affiliated par))
  16368              ;; Try to find an attribute providing a :width.
  16369              (attr-width
  16370               (when (and par (org-with-point-at
  16371                                  (org-element-property :begin par)
  16372                                (re-search-forward attr-re par-end t)))
  16373                 (match-string 1)))
  16374              (width
  16375               (cond
  16376                ;; Treat :width t as if `org-image-actual-width' were t.
  16377                ((string= attr-width "t") nil)
  16378                ;; Fallback to `org-image-actual-width' if no interprable width is given.
  16379                ((or (null attr-width)
  16380                     (string-match-p "\\`[^0-9]" attr-width))
  16381                 (car org-image-actual-width))
  16382                ;; Convert numeric widths to numbers, converting percentages.
  16383                ((string-match-p "\\`[0-9.]+%" attr-width)
  16384                 (/ (string-to-number attr-width) 100.0))
  16385                (t (string-to-number attr-width)))))
  16386         (if (and (floatp width) (<= 0.0 width 2.0))
  16387             ;; A float in [0,2] should be interpereted as this portion of
  16388             ;; the text width in the window.  This works well with cases like
  16389             ;; #+attr_latex: :width 0.X\{line,page,column,etc.}width,
  16390             ;; as the "0.X" is pulled out as a float.  We use 2 as the upper
  16391             ;; bound as cases such as 1.2\linewidth are feasible.
  16392             (round (* width
  16393                       (window-pixel-width)
  16394                       (/ (or (and (bound-and-true-p visual-fill-column-mode)
  16395                                   (or visual-fill-column-width auto-fill-function))
  16396                              (when auto-fill-function fill-column)
  16397                              (- (window-text-width) (line-number-display-width)))
  16398                          (float (window-total-width)))))
  16399           width)))
  16400      ((numberp org-image-actual-width)
  16401       org-image-actual-width)
  16402      (t nil))))
  16403 
  16404 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
  16405   "Remove inline-display overlay if a corresponding region is modified."
  16406   (when (and ov after)
  16407     (delete ov org-inline-image-overlays)
  16408     ;; Clear image from cache to avoid image not updating upon
  16409     ;; changing on disk.  See Emacs bug#59902.
  16410     (when (overlay-get ov 'org-image-overlay)
  16411       (image-flush (overlay-get ov 'display)))
  16412     (delete-overlay ov)))
  16413 
  16414 (defun org-remove-inline-images (&optional beg end)
  16415   "Remove inline display of images."
  16416   (interactive)
  16417   (let* ((beg (or beg (point-min)))
  16418          (end (or end (point-max)))
  16419          (overlays (overlays-in beg end)))
  16420     (dolist (ov overlays)
  16421       (when (memq ov org-inline-image-overlays)
  16422         (setq org-inline-image-overlays (delq ov org-inline-image-overlays))
  16423         (delete-overlay ov)))
  16424     ;; Clear removed overlays.
  16425     (dolist (ov org-inline-image-overlays)
  16426       (unless (overlay-buffer ov)
  16427         (setq org-inline-image-overlays (delq ov org-inline-image-overlays))))))
  16428 
  16429 (defvar org-self-insert-command-undo-counter 0)
  16430 (defvar org-speed-command nil)
  16431 
  16432 (defun org-fix-tags-on-the-fly ()
  16433   "Align tags in headline at point.
  16434 Unlike `org-align-tags', this function does nothing if point is
  16435 either not currently on a tagged headline or on a tag."
  16436   (when (and (org-match-line org-tag-line-re)
  16437 	     (< (point) (match-beginning 1)))
  16438     (org-align-tags)))
  16439 
  16440 (defun org-self-insert-command (N)
  16441   "Like `self-insert-command', use overwrite-mode for whitespace in tables.
  16442 If the cursor is in a table looking at whitespace, the whitespace is
  16443 overwritten, and the table is not marked as requiring realignment."
  16444   (interactive "p")
  16445   (org-fold-check-before-invisible-edit 'insert)
  16446   (cond
  16447    ((and org-use-speed-commands
  16448 	 (let ((kv (this-command-keys-vector)))
  16449 	   (setq org-speed-command
  16450 		 (run-hook-with-args-until-success
  16451 		  'org-speed-command-hook
  16452 		  (make-string 1 (aref kv (1- (length kv))))))))
  16453     (cond
  16454      ((commandp org-speed-command)
  16455       (setq this-command org-speed-command)
  16456       (call-interactively org-speed-command))
  16457      ((functionp org-speed-command)
  16458       (funcall org-speed-command))
  16459      ((consp org-speed-command)
  16460       (eval org-speed-command t))
  16461      (t (let (org-use-speed-commands)
  16462 	  (call-interactively 'org-self-insert-command)))))
  16463    ((and
  16464      (= N 1)
  16465      (not (org-region-active-p))
  16466      (org-at-table-p)
  16467      (progn
  16468        ;; Check if we blank the field, and if that triggers align.
  16469        (and (featurep 'org-table)
  16470 	    org-table-auto-blank-field
  16471 	    (memq last-command
  16472 		  '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
  16473 	    (if (or (eq (char-after) ?\s) (looking-at "[^|\n]*  |"))
  16474 		;; Got extra space, this field does not determine
  16475 		;; column width.
  16476 		(let (org-table-may-need-update) (org-table-blank-field))
  16477 	      ;; No extra space, this field may determine column
  16478 	      ;; width.
  16479 	      (org-table-blank-field)))
  16480        t)
  16481      (looking-at "[^|\n]*  |"))
  16482     ;; There is room for insertion without re-aligning the table.
  16483     (self-insert-command N)
  16484     (org-table-with-shrunk-field
  16485      (save-excursion
  16486        (skip-chars-forward "^|")
  16487        ;; Do not delete last space, which is
  16488        ;; `org-table-separator-space', but the regular space before
  16489        ;; it.
  16490        (delete-region (- (point) 2) (1- (point))))))
  16491    (t
  16492     (setq org-table-may-need-update t)
  16493     (self-insert-command N)
  16494     (org-fix-tags-on-the-fly)
  16495     (when org-self-insert-cluster-for-undo
  16496       (if (not (eq last-command 'org-self-insert-command))
  16497 	  (setq org-self-insert-command-undo-counter 1)
  16498 	(if (>= org-self-insert-command-undo-counter 20)
  16499 	    (setq org-self-insert-command-undo-counter 1)
  16500 	  (and (> org-self-insert-command-undo-counter 0)
  16501 	       buffer-undo-list (listp buffer-undo-list)
  16502 	       (not (cadr buffer-undo-list)) ; remove nil entry
  16503 	       (setcdr buffer-undo-list (cddr buffer-undo-list)))
  16504 	  (setq org-self-insert-command-undo-counter
  16505 		(1+ org-self-insert-command-undo-counter))))))))
  16506 
  16507 (defun org-delete-backward-char (N)
  16508   "Like `delete-backward-char', insert whitespace at field end in tables.
  16509 When deleting backwards, in tables this function will insert whitespace in
  16510 front of the next \"|\" separator, to keep the table aligned.  The table will
  16511 still be marked for re-alignment if the field did fill the entire column,
  16512 because, in this case the deletion might narrow the column."
  16513   (interactive "p")
  16514   (save-match-data
  16515     (org-fold-check-before-invisible-edit 'delete-backward)
  16516     (if (and (= N 1)
  16517 	     (not overwrite-mode)
  16518 	     (not (org-region-active-p))
  16519 	     (not (eq (char-before) ?|))
  16520 	     (save-excursion (skip-chars-backward " \t") (not (bolp)))
  16521 	     (looking-at-p ".*?|")
  16522 	     (org-at-table-p))
  16523 	(progn (forward-char -1) (org-delete-char 1))
  16524       (backward-delete-char N)
  16525       (org-fix-tags-on-the-fly))))
  16526 
  16527 (defun org-delete-char (N)
  16528   "Like `delete-char', but insert whitespace at field end in tables.
  16529 When deleting characters, in tables this function will insert whitespace in
  16530 front of the next \"|\" separator, to keep the table aligned.  The table will
  16531 still be marked for re-alignment if the field did fill the entire column,
  16532 because, in this case the deletion might narrow the column."
  16533   (interactive "p")
  16534   (save-match-data
  16535     (org-fold-check-before-invisible-edit 'delete)
  16536     (cond
  16537      ((or (/= N 1)
  16538 	  (eq (char-after) ?|)
  16539 	  (save-excursion (skip-chars-backward " \t") (bolp))
  16540 	  (not (org-at-table-p)))
  16541       (delete-char N)
  16542       (org-fix-tags-on-the-fly))
  16543      ((looking-at ".\\(.*?\\)|")
  16544       (let* ((update? org-table-may-need-update)
  16545 	     (noalign (looking-at-p ".*?  |")))
  16546 	(delete-char 1)
  16547 	(org-table-with-shrunk-field
  16548 	 (save-excursion
  16549 	   ;; Last space is `org-table-separator-space', so insert
  16550 	   ;; a regular one before it instead.
  16551 	   (goto-char (- (match-end 0) 2))
  16552 	   (insert " ")))
  16553 	;; If there were two spaces at the end, this field does not
  16554 	;; determine the width of the column.
  16555 	(when noalign (setq org-table-may-need-update update?))))
  16556      (t
  16557       (delete-char N)))))
  16558 
  16559 ;; Make `delete-selection-mode' work with Org mode and Orgtbl mode
  16560 (put 'org-self-insert-command 'delete-selection
  16561      (lambda ()
  16562        (not (run-hook-with-args-until-success
  16563              'self-insert-uses-region-functions))))
  16564 (put 'orgtbl-self-insert-command 'delete-selection
  16565      (lambda ()
  16566        (not (run-hook-with-args-until-success
  16567              'self-insert-uses-region-functions))))
  16568 (put 'org-delete-char 'delete-selection 'supersede)
  16569 (put 'org-delete-backward-char 'delete-selection 'supersede)
  16570 (put 'org-yank 'delete-selection 'yank)
  16571 (put 'org-return 'delete-selection t)
  16572 
  16573 ;; Make `flyspell-mode' delay after some commands
  16574 (put 'org-self-insert-command 'flyspell-delayed t)
  16575 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
  16576 (put 'org-delete-char 'flyspell-delayed t)
  16577 (put 'org-delete-backward-char 'flyspell-delayed t)
  16578 
  16579 ;; Make pabbrev-mode expand after Org mode commands
  16580 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
  16581 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
  16582 
  16583 (defun org-transpose-words ()
  16584   "Transpose words for Org.
  16585 This uses the `org-mode-transpose-word-syntax-table' syntax
  16586 table, which interprets characters in `org-emphasis-alist' as
  16587 word constituents."
  16588   (interactive)
  16589   (with-syntax-table org-mode-transpose-word-syntax-table
  16590     (call-interactively 'transpose-words)))
  16591 
  16592 (defvar org-ctrl-c-ctrl-c-hook nil
  16593   "Hook for functions attaching themselves to `C-c C-c'.
  16594 
  16595 This can be used to add additional functionality to the `C-c C-c'
  16596 key which executes context-dependent commands.  This hook is run
  16597 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
  16598 run after the last test.
  16599 
  16600 Each function will be called with no arguments.  The function
  16601 must check if the context is appropriate for it to act.  If yes,
  16602 it should do its thing and then return a non-nil value.  If the
  16603 context is wrong, just do nothing and return nil.")
  16604 
  16605 (defvar org-ctrl-c-ctrl-c-final-hook nil
  16606   "Hook for functions attaching themselves to `C-c C-c'.
  16607 
  16608 This can be used to add additional functionality to the `C-c C-c'
  16609 key which executes context-dependent commands.  This hook is run
  16610 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
  16611 before the first test.
  16612 
  16613 Each function will be called with no arguments.  The function
  16614 must check if the context is appropriate for it to act.  If yes,
  16615 it should do its thing and then return a non-nil value.  If the
  16616 context is wrong, just do nothing and return nil.")
  16617 
  16618 (defvar org-tab-after-check-for-table-hook nil
  16619   "Hook for functions to attach themselves to TAB.
  16620 See `org-ctrl-c-ctrl-c-hook' for more information.
  16621 This hook runs after it has been established that the cursor is not in a
  16622 table, but before checking if the cursor is in a headline or if global cycling
  16623 should be done.
  16624 If any function in this hook returns t, not other actions like visibility
  16625 cycling will be done.")
  16626 
  16627 (defvar org-tab-after-check-for-cycling-hook nil
  16628   "Hook for functions to attach themselves to TAB.
  16629 See `org-ctrl-c-ctrl-c-hook' for more information.
  16630 This hook runs after it has been established that not table field motion and
  16631 not visibility should be done because of current context.  This is probably
  16632 the place where a package like yasnippets can hook in.")
  16633 
  16634 (defvar org-tab-before-tab-emulation-hook nil
  16635   "Hook for functions to attach themselves to TAB.
  16636 See `org-ctrl-c-ctrl-c-hook' for more information.
  16637 This hook runs after every other options for TAB have been exhausted, but
  16638 before indentation and \t insertion takes place.")
  16639 
  16640 (defvar org-metaleft-hook nil
  16641   "Hook for functions attaching themselves to `M-left'.
  16642 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16643 (defvar org-metaright-hook nil
  16644   "Hook for functions attaching themselves to `M-right'.
  16645 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16646 (defvar org-metaup-hook nil
  16647   "Hook for functions attaching themselves to `M-up'.
  16648 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16649 (defvar org-metadown-hook nil
  16650   "Hook for functions attaching themselves to `M-down'.
  16651 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16652 (defvar org-shiftmetaleft-hook nil
  16653   "Hook for functions attaching themselves to `M-S-left'.
  16654 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16655 (defvar org-shiftmetaright-hook nil
  16656   "Hook for functions attaching themselves to `M-S-right'.
  16657 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16658 (defvar org-shiftmetaup-hook nil
  16659   "Hook for functions attaching themselves to `M-S-up'.
  16660 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16661 (defvar org-shiftmetadown-hook nil
  16662   "Hook for functions attaching themselves to `M-S-down'.
  16663 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16664 (defvar org-metareturn-hook nil
  16665   "Hook for functions attaching themselves to `M-RET'.
  16666 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16667 (defvar org-shiftup-hook nil
  16668   "Hook for functions attaching themselves to `S-up'.
  16669 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16670 (defvar org-shiftup-final-hook nil
  16671   "Hook for functions attaching themselves to `S-up'.
  16672 This one runs after all other options except shift-select have been excluded.
  16673 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16674 (defvar org-shiftdown-hook nil
  16675   "Hook for functions attaching themselves to `S-down'.
  16676 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16677 (defvar org-shiftdown-final-hook nil
  16678   "Hook for functions attaching themselves to `S-down'.
  16679 This one runs after all other options except shift-select have been excluded.
  16680 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16681 (defvar org-shiftleft-hook nil
  16682   "Hook for functions attaching themselves to `S-left'.
  16683 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16684 (defvar org-shiftleft-final-hook nil
  16685   "Hook for functions attaching themselves to `S-left'.
  16686 This one runs after all other options except shift-select have been excluded.
  16687 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16688 (defvar org-shiftright-hook nil
  16689   "Hook for functions attaching themselves to `S-right'.
  16690 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16691 (defvar org-shiftright-final-hook nil
  16692   "Hook for functions attaching themselves to `S-right'.
  16693 This one runs after all other options except shift-select have been excluded.
  16694 See `org-ctrl-c-ctrl-c-hook' for more information.")
  16695 
  16696 (defun org-modifier-cursor-error ()
  16697   "Throw an error, a modified cursor command was applied in wrong context."
  16698   (user-error "This command is active in special context like tables, headlines or items"))
  16699 
  16700 (defun org-shiftselect-error ()
  16701   "Throw an error because Shift-Cursor command was applied in wrong context."
  16702   (if (and (boundp 'shift-select-mode) shift-select-mode)
  16703       (user-error "To use shift-selection with Org mode, customize `org-support-shift-select'")
  16704     (user-error "This command works only in special context like headlines or timestamps")))
  16705 
  16706 (defun org-call-for-shift-select (cmd)
  16707   (let ((this-command-keys-shift-translated t))
  16708     (call-interactively cmd)))
  16709 
  16710 (defun org-shifttab (&optional arg)
  16711   "Global visibility cycling or move to previous table field.
  16712 Call `org-table-previous-field' within a table.
  16713 When ARG is nil, cycle globally through visibility states.
  16714 When ARG is a numeric prefix, show contents of this level."
  16715   (interactive "P")
  16716   (cond
  16717    ((org-at-table-p) (call-interactively 'org-table-previous-field))
  16718    ((integerp arg)
  16719     (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
  16720       (message "Content view to level: %d" arg)
  16721       (org-cycle-content (prefix-numeric-value arg2))
  16722       (org-cycle-show-empty-lines t)
  16723       (setq org-cycle-global-status 'overview)
  16724       (run-hook-with-args 'org-cycle-hook 'overview)))
  16725    (t (call-interactively 'org-cycle-global))))
  16726 
  16727 (defun org-shiftmetaleft ()
  16728   "Promote subtree or delete table column.
  16729 Calls `org-promote-subtree', `org-outdent-item-tree', or
  16730 `org-table-delete-column', depending on context.  See the
  16731 individual commands for more information."
  16732   (interactive)
  16733   (cond
  16734    ((and (eq system-type 'darwin)
  16735          (or (eq org-support-shift-select 'always)
  16736              (and org-support-shift-select (org-region-active-p))))
  16737     (org-call-for-shift-select 'backward-char))
  16738    ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
  16739    ((org-at-table-p) (call-interactively 'org-table-delete-column))
  16740    ((org-at-heading-p) (call-interactively 'org-promote-subtree))
  16741    ((if (not (org-region-active-p)) (org-at-item-p)
  16742       (save-excursion (goto-char (region-beginning))
  16743 		      (org-at-item-p)))
  16744     (call-interactively 'org-outdent-item-tree))
  16745    (t (org-modifier-cursor-error))))
  16746 
  16747 (defun org-shiftmetaright ()
  16748   "Demote subtree or insert table column.
  16749 Calls `org-demote-subtree', `org-indent-item-tree', or
  16750 `org-table-insert-column', depending on context.  See the
  16751 individual commands for more information."
  16752   (interactive)
  16753   (cond
  16754    ((and (eq system-type 'darwin)
  16755          (or (eq org-support-shift-select 'always)
  16756              (and org-support-shift-select (org-region-active-p))))
  16757     (org-call-for-shift-select 'forward-char))
  16758    ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
  16759    ((org-at-table-p) (call-interactively 'org-table-insert-column))
  16760    ((org-at-heading-p) (call-interactively 'org-demote-subtree))
  16761    ((if (not (org-region-active-p)) (org-at-item-p)
  16762       (save-excursion (goto-char (region-beginning))
  16763 		      (org-at-item-p)))
  16764     (call-interactively 'org-indent-item-tree))
  16765    (t (org-modifier-cursor-error))))
  16766 
  16767 (defun org-shiftmetaup (&optional _arg)
  16768   "Drag the line at point up.
  16769 In a table, kill the current row.
  16770 On a clock timestamp, update the value of the timestamp like `S-<up>'
  16771 but also adjust the previous clocked item in the clock history.
  16772 Everywhere else, drag the line at point up."
  16773   (interactive "P")
  16774   (cond
  16775    ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
  16776    ((org-at-table-p) (call-interactively 'org-table-kill-row))
  16777    ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  16778 			   (call-interactively 'org-timestamp-up)))
  16779    (t (call-interactively 'org-drag-line-backward))))
  16780 
  16781 (defun org-shiftmetadown (&optional _arg)
  16782   "Drag the line at point down.
  16783 In a table, insert an empty row at the current line.
  16784 On a clock timestamp, update the value of the timestamp like `S-<down>'
  16785 but also adjust the previous clocked item in the clock history.
  16786 Everywhere else, drag the line at point down."
  16787   (interactive "P")
  16788   (cond
  16789    ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
  16790    ((org-at-table-p) (call-interactively 'org-table-insert-row))
  16791    ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
  16792 			   (call-interactively 'org-timestamp-down)))
  16793    (t (call-interactively 'org-drag-line-forward))))
  16794 
  16795 (defsubst org-hidden-tree-error ()
  16796   (user-error
  16797    "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
  16798 
  16799 (defun org-metaleft (&optional _arg)
  16800   "Promote heading, list item at point or move table column left.
  16801 
  16802 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
  16803 depending on context.  With no specific context, calls the Emacs
  16804 default `backward-word'.  See the individual commands for more
  16805 information.
  16806 
  16807 This function runs the hook `org-metaleft-hook' as a first step,
  16808 and returns at first non-nil value."
  16809   (interactive "P")
  16810   (cond
  16811    ((run-hook-with-args-until-success 'org-metaleft-hook))
  16812    ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
  16813    ((org-with-limited-levels
  16814      (or (org-at-heading-p)
  16815 	 (and (org-region-active-p)
  16816 	      (save-excursion
  16817 		(goto-char (region-beginning))
  16818 		(org-at-heading-p)))))
  16819     (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  16820     (call-interactively 'org-do-promote))
  16821    ;; At an inline task.
  16822    ((org-at-heading-p)
  16823     (call-interactively 'org-inlinetask-promote))
  16824    ((or (org-at-item-p)
  16825 	(and (org-region-active-p)
  16826 	     (save-excursion
  16827 	       (goto-char (region-beginning))
  16828 	       (org-at-item-p))))
  16829     (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  16830     (call-interactively 'org-outdent-item))
  16831    (t (call-interactively 'backward-word))))
  16832 
  16833 (defun org-metaright (&optional _arg)
  16834   "Demote heading, list item at point or move table column right.
  16835 
  16836 In front of a drawer or a block keyword, indent it correctly.
  16837 
  16838 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
  16839 `org-indent-drawer' or `org-indent-block' depending on context.
  16840 With no specific context, calls the Emacs default `forward-word'.
  16841 See the individual commands for more information.
  16842 
  16843 This function runs the hook `org-metaright-hook' as a first step,
  16844 and returns at first non-nil value."
  16845   (interactive "P")
  16846   (cond
  16847    ((run-hook-with-args-until-success 'org-metaright-hook))
  16848    ((org-at-table-p) (call-interactively 'org-table-move-column))
  16849    ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
  16850    ((org-at-block-p) (call-interactively 'org-indent-block))
  16851    ((org-with-limited-levels
  16852      (or (org-at-heading-p)
  16853 	 (and (org-region-active-p)
  16854 	      (save-excursion
  16855 		(goto-char (region-beginning))
  16856 		(org-at-heading-p)))))
  16857     (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
  16858     (call-interactively 'org-do-demote))
  16859    ;; At an inline task.
  16860    ((org-at-heading-p)
  16861     (call-interactively 'org-inlinetask-demote))
  16862    ((or (org-at-item-p)
  16863 	(and (org-region-active-p)
  16864 	     (save-excursion
  16865 	       (goto-char (region-beginning))
  16866 	       (org-at-item-p))))
  16867     (when (org-check-for-hidden 'items) (org-hidden-tree-error))
  16868     (call-interactively 'org-indent-item))
  16869    (t (call-interactively 'forward-word))))
  16870 
  16871 (defun org-check-for-hidden (what)
  16872   "Check if there are hidden headlines/items in the current visual line.
  16873 WHAT can be either `headlines' or `items'.  If the current line is
  16874 an outline or item heading and it has a folded subtree below it,
  16875 this function returns t, nil otherwise."
  16876   (let ((re (cond
  16877 	     ((eq what 'headlines) org-outline-regexp-bol)
  16878 	     ((eq what 'items) (org-item-beginning-re))
  16879 	     (t (error "This should not happen"))))
  16880 	beg end)
  16881     (save-excursion
  16882       (catch 'exit
  16883 	(unless (org-region-active-p)
  16884           (setq beg (line-beginning-position))
  16885 	  (beginning-of-line 2)
  16886 	  (while (and (not (eobp)) ;; this is like `next-line'
  16887 		      (org-invisible-p (1- (point))))
  16888 	    (beginning-of-line 2))
  16889 	  (setq end (point))
  16890 	  (goto-char beg)
  16891           (goto-char (line-end-position))
  16892 	  (setq end (max end (point)))
  16893 	  (while (re-search-forward re end t)
  16894 	    (when (org-invisible-p (match-beginning 0))
  16895 	      (throw 'exit t))))
  16896 	nil))))
  16897 
  16898 (defun org-metaup (&optional _arg)
  16899   "Move subtree up or move table row up.
  16900 Calls `org-move-subtree-up' or `org-table-move-row' or
  16901 `org-move-item-up', depending on context.  See the individual commands
  16902 for more information."
  16903   (interactive "P")
  16904   (cond
  16905    ((run-hook-with-args-until-success 'org-metaup-hook))
  16906    ((org-region-active-p)
  16907     (let* ((a (save-excursion
  16908 		(goto-char (region-beginning))
  16909 		(line-beginning-position)))
  16910 	   (b (save-excursion
  16911 		(goto-char (region-end))
  16912 		(if (bolp) (1- (point)) (line-end-position))))
  16913 	   (c (save-excursion
  16914 		(goto-char a)
  16915 		(move-beginning-of-line 0)
  16916 		(point)))
  16917 	   (d (save-excursion
  16918 		(goto-char a)
  16919 		(move-end-of-line 0)
  16920 		(point))))
  16921       (transpose-regions a b c d)
  16922       (goto-char c)))
  16923    ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
  16924    ((and (featurep 'org-inlinetask)
  16925          (org-inlinetask-in-task-p))
  16926     (org-drag-element-backward))
  16927    ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
  16928    ((org-at-item-p) (call-interactively 'org-move-item-up))
  16929    (t (org-drag-element-backward))))
  16930 
  16931 (defun org-metadown (&optional _arg)
  16932   "Move subtree down or move table row down.
  16933 Calls `org-move-subtree-down' or `org-table-move-row' or
  16934 `org-move-item-down', depending on context.  See the individual
  16935 commands for more information."
  16936   (interactive "P")
  16937   (cond
  16938    ((run-hook-with-args-until-success 'org-metadown-hook))
  16939    ((org-region-active-p)
  16940     (let* ((a (save-excursion
  16941 		(goto-char (region-beginning))
  16942 		(line-beginning-position)))
  16943 	   (b (save-excursion
  16944 		(goto-char (region-end))
  16945 		(if (bolp) (1- (point)) (line-end-position))))
  16946 	   (c (save-excursion
  16947 		(goto-char b)
  16948 		(move-beginning-of-line (if (bolp) 1 2))
  16949 		(point)))
  16950 	   (d (save-excursion
  16951 		(goto-char b)
  16952 		(move-end-of-line (if (bolp) 1 2))
  16953 		(point))))
  16954       (transpose-regions a b c d)
  16955       (goto-char d)))
  16956    ((org-at-table-p) (call-interactively 'org-table-move-row))
  16957    ((and (featurep 'org-inlinetask)
  16958          (org-inlinetask-in-task-p))
  16959     (org-drag-element-forward))
  16960    ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
  16961    ((org-at-item-p) (call-interactively 'org-move-item-down))
  16962    (t (org-drag-element-forward))))
  16963 
  16964 (defun org-shiftup (&optional arg)
  16965   "Act on current element according to context.
  16966 Call `org-timestamp-up' or `org-priority-up', or
  16967 `org-previous-item', or `org-table-move-cell-up'.  See the
  16968 individual commands for more information."
  16969   (interactive "P")
  16970   (cond
  16971    ((run-hook-with-args-until-success 'org-shiftup-hook))
  16972    ((and org-support-shift-select (org-region-active-p))
  16973     (org-call-for-shift-select 'previous-line))
  16974    ((org-at-timestamp-p 'lax)
  16975     (call-interactively (if org-edit-timestamp-down-means-later
  16976 			    'org-timestamp-down 'org-timestamp-up)))
  16977    ((and (not (eq org-support-shift-select 'always))
  16978 	 org-priority-enable-commands
  16979 	 (org-at-heading-p))
  16980     (call-interactively 'org-priority-up))
  16981    ((and (not org-support-shift-select) (org-at-item-p))
  16982     (call-interactively 'org-previous-item))
  16983    ((org-clocktable-try-shift 'up arg))
  16984    ((and (not (eq org-support-shift-select 'always))
  16985 	 (org-at-table-p))
  16986     (org-table-move-cell-up))
  16987    ((run-hook-with-args-until-success 'org-shiftup-final-hook))
  16988    (org-support-shift-select
  16989     (org-call-for-shift-select 'previous-line))
  16990    (t (org-shiftselect-error))))
  16991 
  16992 (defun org-shiftdown (&optional arg)
  16993   "Act on current element according to context.
  16994 Call `org-timestamp-down' or `org-priority-down', or
  16995 `org-next-item', or `org-table-move-cell-down'.  See the
  16996 individual commands for more information."
  16997   (interactive "P")
  16998   (cond
  16999    ((run-hook-with-args-until-success 'org-shiftdown-hook))
  17000    ((and org-support-shift-select (org-region-active-p))
  17001     (org-call-for-shift-select 'next-line))
  17002    ((org-at-timestamp-p 'lax)
  17003     (call-interactively (if org-edit-timestamp-down-means-later
  17004 			    'org-timestamp-up 'org-timestamp-down)))
  17005    ((and (not (eq org-support-shift-select 'always))
  17006 	 org-priority-enable-commands
  17007 	 (org-at-heading-p))
  17008     (call-interactively 'org-priority-down))
  17009    ((and (not org-support-shift-select) (org-at-item-p))
  17010     (call-interactively 'org-next-item))
  17011    ((org-clocktable-try-shift 'down arg))
  17012    ((and (not (eq org-support-shift-select 'always))
  17013 	 (org-at-table-p))
  17014     (org-table-move-cell-down))
  17015    ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
  17016    (org-support-shift-select
  17017     (org-call-for-shift-select 'next-line))
  17018    (t (org-shiftselect-error))))
  17019 
  17020 (defun org-shiftright (&optional arg)
  17021   "Act on the current element according to context.
  17022 This does one of the following:
  17023 
  17024 - switch a timestamp at point one day into the future
  17025 - on a headline, switch to the next TODO keyword
  17026 - on an item, switch entire list to the next bullet type
  17027 - on a property line, switch to the next allowed value
  17028 - on a clocktable definition line, move time block into the future
  17029 - in a table, move a single cell right"
  17030   (interactive "P")
  17031   (cond
  17032    ((run-hook-with-args-until-success 'org-shiftright-hook))
  17033    ((and org-support-shift-select (org-region-active-p))
  17034     (org-call-for-shift-select 'forward-char))
  17035    ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-up-day))
  17036    ((and (not (eq org-support-shift-select 'always))
  17037 	 (org-at-heading-p))
  17038     (let ((org-inhibit-logging
  17039 	   (not org-treat-S-cursor-todo-selection-as-state-change))
  17040 	  (org-inhibit-blocking
  17041 	   (not org-treat-S-cursor-todo-selection-as-state-change)))
  17042       (org-call-with-arg 'org-todo 'right)))
  17043    ((or (and org-support-shift-select
  17044 	     (not (eq org-support-shift-select 'always))
  17045 	     (org-at-item-bullet-p))
  17046 	(and (not org-support-shift-select) (org-at-item-p)))
  17047     (org-call-with-arg 'org-cycle-list-bullet nil))
  17048    ((and (not (eq org-support-shift-select 'always))
  17049 	 (org-at-property-p))
  17050     (call-interactively 'org-property-next-allowed-value))
  17051    ((org-clocktable-try-shift 'right arg))
  17052    ((and (not (eq org-support-shift-select 'always))
  17053 	 (org-at-table-p))
  17054     (org-table-move-cell-right))
  17055    ((run-hook-with-args-until-success 'org-shiftright-final-hook))
  17056    (org-support-shift-select
  17057     (org-call-for-shift-select 'forward-char))
  17058    (t (org-shiftselect-error))))
  17059 
  17060 (defun org-shiftleft (&optional arg)
  17061   "Act on current element according to context.
  17062 This does one of the following:
  17063 
  17064 - switch a timestamp at point one day into the past
  17065 - on a headline, switch to the previous TODO keyword.
  17066 - on an item, switch entire list to the previous bullet type
  17067 - on a property line, switch to the previous allowed value
  17068 - on a clocktable definition line, move time block into the past
  17069 - in a table, move a single cell left"
  17070   (interactive "P")
  17071   (cond
  17072    ((run-hook-with-args-until-success 'org-shiftleft-hook))
  17073    ((and org-support-shift-select (org-region-active-p))
  17074     (org-call-for-shift-select 'backward-char))
  17075    ((org-at-timestamp-p 'lax) (call-interactively 'org-timestamp-down-day))
  17076    ((and (not (eq org-support-shift-select 'always))
  17077 	 (org-at-heading-p))
  17078     (let ((org-inhibit-logging
  17079 	   (not org-treat-S-cursor-todo-selection-as-state-change))
  17080 	  (org-inhibit-blocking
  17081 	   (not org-treat-S-cursor-todo-selection-as-state-change)))
  17082       (org-call-with-arg 'org-todo 'left)))
  17083    ((or (and org-support-shift-select
  17084 	     (not (eq org-support-shift-select 'always))
  17085 	     (org-at-item-bullet-p))
  17086 	(and (not org-support-shift-select) (org-at-item-p)))
  17087     (org-call-with-arg 'org-cycle-list-bullet 'previous))
  17088    ((and (not (eq org-support-shift-select 'always))
  17089 	 (org-at-property-p))
  17090     (call-interactively 'org-property-previous-allowed-value))
  17091    ((org-clocktable-try-shift 'left arg))
  17092    ((and (not (eq org-support-shift-select 'always))
  17093 	 (org-at-table-p))
  17094     (org-table-move-cell-left))
  17095    ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
  17096    (org-support-shift-select
  17097     (org-call-for-shift-select 'backward-char))
  17098    (t (org-shiftselect-error))))
  17099 
  17100 (defun org-shiftcontrolright ()
  17101   "Switch to next TODO set."
  17102   (interactive)
  17103   (cond
  17104    ((and org-support-shift-select (org-region-active-p))
  17105     (org-call-for-shift-select 'forward-word))
  17106    ((and (not (eq org-support-shift-select 'always))
  17107 	 (org-at-heading-p))
  17108     (org-call-with-arg 'org-todo 'nextset))
  17109    (org-support-shift-select
  17110     (org-call-for-shift-select 'forward-word))
  17111    (t (org-shiftselect-error))))
  17112 
  17113 (defun org-shiftcontrolleft ()
  17114   "Switch to previous TODO set."
  17115   (interactive)
  17116   (cond
  17117    ((and org-support-shift-select (org-region-active-p))
  17118     (org-call-for-shift-select 'backward-word))
  17119    ((and (not (eq org-support-shift-select 'always))
  17120 	 (org-at-heading-p))
  17121     (org-call-with-arg 'org-todo 'previousset))
  17122    (org-support-shift-select
  17123     (org-call-for-shift-select 'backward-word))
  17124    (t (org-shiftselect-error))))
  17125 
  17126 (defun org-shiftcontrolup (&optional n)
  17127   "Change timestamps synchronously up in CLOCK log lines.
  17128 Optional argument N tells to change by that many units."
  17129   (interactive "P")
  17130   (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  17131       (let (org-support-shift-select)
  17132 	(org-clock-timestamps-up n))
  17133     (user-error "Not at a clock log")))
  17134 
  17135 (defun org-shiftcontroldown (&optional n)
  17136   "Change timestamps synchronously down in CLOCK log lines.
  17137 Optional argument N tells to change by that many units."
  17138   (interactive "P")
  17139   (if (and (org-at-clock-log-p) (org-at-timestamp-p 'lax))
  17140       (let (org-support-shift-select)
  17141 	(org-clock-timestamps-down n))
  17142     (user-error "Not at a clock log")))
  17143 
  17144 (defun org-increase-number-at-point (&optional inc)
  17145   "Increment the number at point.
  17146 With an optional prefix numeric argument INC, increment using
  17147 this numeric value."
  17148   (interactive "p")
  17149   (if (not (number-at-point))
  17150       (user-error "Not on a number")
  17151     (unless inc (setq inc 1))
  17152     (let ((pos (point))
  17153 	  (beg (skip-chars-backward "-+^/*0-9eE."))
  17154 	  (end (skip-chars-forward "-+^/*0-9eE.")) nap)
  17155       (setq nap (buffer-substring-no-properties
  17156 		 (+ pos beg) (+ pos beg end)))
  17157       (delete-region (+ pos beg) (+ pos beg end))
  17158       (insert (calc-eval (concat (number-to-string inc) "+" nap))))
  17159     (when (org-at-table-p)
  17160       (org-table-align)
  17161       (org-table-end-of-field 1))))
  17162 
  17163 (defun org-decrease-number-at-point (&optional inc)
  17164   "Decrement the number at point.
  17165 With an optional prefix numeric argument INC, decrement using
  17166 this numeric value."
  17167   (interactive "p")
  17168   (org-increase-number-at-point (- (or inc 1))))
  17169 
  17170 (defun org-ctrl-c-ret ()
  17171   "Call `org-table-hline-and-move' or `org-insert-heading'."
  17172   (interactive)
  17173   (cond
  17174    ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
  17175    (t (call-interactively 'org-insert-heading))))
  17176 
  17177 (defun org-copy-visible (beg end)
  17178   "Copy the visible parts of the region."
  17179   (interactive "r")
  17180   (let ((result ""))
  17181     (while (/= beg end)
  17182       (if (eq org-fold-core-style 'text-properties)
  17183           (progn
  17184             (while (org-invisible-p beg)
  17185 	      (setq beg (org-fold-next-visibility-change beg end)))
  17186             (let ((next (org-fold-next-visibility-change beg end)))
  17187 	      (setq result (concat result (buffer-substring beg next)))
  17188 	      (setq beg next)))
  17189         (when (invisible-p beg)
  17190 	  (setq beg (next-single-char-property-change beg 'invisible nil end)))
  17191         (let ((next (next-single-char-property-change beg 'invisible nil end)))
  17192 	  (setq result (concat result (buffer-substring beg next)))
  17193 	  (setq beg next))))
  17194     ;; Prevent Emacs from adding full selected text to `kill-ring'
  17195     ;; when `select-enable-primary' is non-nil.  This special value of
  17196     ;; `deactivate-mark' only works since Emacs 29.
  17197     (setq deactivate-mark 'dont-save)
  17198     (kill-new result)
  17199     (message "Visible strings have been copied to the kill ring.")))
  17200 
  17201 (defun org-copy-special ()
  17202   "Copy region in table or copy current subtree.
  17203 Calls `org-table-copy-region' or `org-copy-subtree', depending on
  17204 context.  See the individual commands for more information."
  17205   (interactive)
  17206   (call-interactively
  17207    (if (org-at-table-p) #'org-table-copy-region #'org-copy-subtree)))
  17208 
  17209 (defun org-cut-special ()
  17210   "Cut region in table or cut current subtree.
  17211 Calls `org-table-cut-region' or `org-cut-subtree', depending on
  17212 context.  See the individual commands for more information."
  17213   (interactive)
  17214   (call-interactively
  17215    (if (org-at-table-p) #'org-table-cut-region #'org-cut-subtree)))
  17216 
  17217 (defun org-paste-special (arg)
  17218   "Paste rectangular region into table, or past subtree relative to level.
  17219 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
  17220 See the individual commands for more information."
  17221   (interactive "P")
  17222   (if (org-at-table-p)
  17223       (org-table-paste-rectangle)
  17224     (org-paste-subtree arg)))
  17225 
  17226 (defun org-edit-special (&optional arg)
  17227   "Call a special editor for the element at point.
  17228 When at a table, call the formula editor with `org-table-edit-formulas'.
  17229 When in a source code block, call `org-edit-src-code'.
  17230 When in a fixed-width region, call `org-edit-fixed-width-region'.
  17231 When in an export block, call `org-edit-export-block'.
  17232 When in a comment block, call `org-edit-comment-block'.
  17233 When in a LaTeX environment, call `org-edit-latex-environment'.
  17234 When at an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, visit the included file.
  17235 When at a footnote reference, call `org-edit-footnote-reference'.
  17236 When at a planning line call, `org-deadline' and/or `org-schedule'.
  17237 When at an active timestamp, call `org-time-stamp'.
  17238 When at an inactive timestamp, call `org-time-stamp-inactive'.
  17239 On a link, call `ffap' to visit the link at point.
  17240 Otherwise, return a user error."
  17241   (interactive "P")
  17242   (let ((element (org-element-at-point)))
  17243     (barf-if-buffer-read-only)
  17244     (pcase (org-element-type element)
  17245       (`src-block
  17246        (if (not arg) (org-edit-src-code)
  17247 	 (let* ((info (org-babel-get-src-block-info))
  17248 		(lang (nth 0 info))
  17249 		(params (nth 2 info))
  17250 		(session (cdr (assq :session params))))
  17251 	   (if (not session) (org-edit-src-code)
  17252 	     ;; At a source block with a session and function called
  17253 	     ;; with an ARG: switch to the buffer related to the
  17254 	     ;; inferior process.
  17255 	     (switch-to-buffer
  17256 	      (funcall (intern (concat "org-babel-prep-session:" lang))
  17257 		       session params))))))
  17258       (`keyword
  17259        (unless (member (org-element-property :key element)
  17260 		       '("BIBLIOGRAPHY" "INCLUDE" "SETUPFILE"))
  17261 	 (user-error "No special environment to edit here"))
  17262        (let ((value (org-element-property :value element)))
  17263 	 (unless (org-string-nw-p value) (user-error "No file to edit"))
  17264 	 (let ((file (and (string-match "\\`\"\\(.*?\\)\"\\|\\S-+" value)
  17265 			  (or (match-string 1 value)
  17266 			      (match-string 0 value)))))
  17267 	   (when (org-url-p file)
  17268 	     (user-error "Files located with a URL cannot be edited"))
  17269 	   (org-link-open-from-string
  17270 	    (format "[[%s]]" (expand-file-name file))))))
  17271       (`table
  17272        (if (eq (org-element-property :type element) 'table.el)
  17273            (org-edit-table.el)
  17274          (call-interactively 'org-table-edit-formulas)))
  17275       ;; Only Org tables contain `table-row' type elements.
  17276       (`table-row (call-interactively 'org-table-edit-formulas))
  17277       (`example-block (org-edit-src-code))
  17278       (`export-block (org-edit-export-block))
  17279       (`comment-block (org-edit-comment-block))
  17280       (`fixed-width (org-edit-fixed-width-region))
  17281       (`latex-environment (org-edit-latex-environment))
  17282       (`planning
  17283        (let ((proplist (cadr element)))
  17284          (mapc #'call-interactively
  17285                (remq nil
  17286                      (list
  17287                       (when (plist-get proplist :deadline) #'org-deadline)
  17288                       (when (plist-get proplist :scheduled) #'org-schedule))))))
  17289       (_
  17290        ;; No notable element at point.  Though, we may be at a link or
  17291        ;; a footnote reference, which are objects.  Thus, scan deeper.
  17292        (let ((context (org-element-context element)))
  17293 	 (pcase (org-element-type context)
  17294 	   (`footnote-reference (org-edit-footnote-reference))
  17295 	   (`inline-src-block (org-edit-inline-src-code))
  17296 	   (`latex-fragment (org-edit-latex-fragment))
  17297 	   (`timestamp (if (eq 'inactive (org-element-property :type context))
  17298 			   (call-interactively #'org-time-stamp-inactive)
  17299 			 (call-interactively #'org-time-stamp)))
  17300 	   (`link (call-interactively #'ffap))
  17301 	   (_ (user-error "No special environment to edit here"))))))))
  17302 
  17303 (defun org-ctrl-c-ctrl-c (&optional arg)
  17304   "Set tags in headline, or update according to changed information at point.
  17305 
  17306 This command does many different things, depending on context:
  17307 
  17308 - If column view is active, in agenda or org buffers, quit it.
  17309 
  17310 - If there are highlights, remove them.
  17311 
  17312 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
  17313   this is what we do.
  17314 
  17315 - If the cursor is on a statistics cookie, update it.
  17316 
  17317 - If the cursor is in a headline, in an agenda or an org buffer,
  17318   prompt for tags and insert them into the current line, aligned
  17319   to `org-tags-column'.  When called with prefix arg, realign all
  17320   tags in the current buffer.
  17321 
  17322 - If the cursor is in one of the special #+KEYWORD lines, this
  17323   triggers scanning the buffer for these lines and updating the
  17324   information.
  17325 
  17326 - If the cursor is inside a table, realign the table.  This command
  17327   works even if the automatic table editor has been turned off.
  17328 
  17329 - If the cursor is on a #+TBLFM line, re-apply the formulas to
  17330   the entire table.
  17331 
  17332 - If the cursor is at a footnote reference or definition, jump to
  17333   the corresponding definition or references, respectively.
  17334 
  17335 - If the cursor is a the beginning of a dynamic block, update it.
  17336 
  17337 - If the current buffer is a capture buffer, close note and file it.
  17338 
  17339 - If the cursor is on a <<<target>>>, update radio targets and
  17340   corresponding links in this buffer.
  17341 
  17342 - If the cursor is on a numbered item in a plain list, renumber the
  17343   ordered list.
  17344 
  17345 - If the cursor is on a checkbox, toggle it.
  17346 
  17347 - If the cursor is on a code block, evaluate it.  The variable
  17348   `org-confirm-babel-evaluate' can be used to control prompting
  17349   before code block evaluation, by default every code block
  17350   evaluation requires confirmation.  Code block evaluation can be
  17351   inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
  17352   (interactive "P")
  17353   (cond
  17354    ((bound-and-true-p org-columns-overlays) (org-columns-quit))
  17355    ((or (bound-and-true-p org-clock-overlays) org-occur-highlights)
  17356     (when (boundp 'org-clock-overlays) (org-clock-remove-overlays))
  17357     (org-remove-occur-highlights)
  17358     (message "Temporary highlights/overlays removed from current buffer"))
  17359    ((and (local-variable-p 'org-finish-function)
  17360 	 (fboundp org-finish-function))
  17361     (funcall org-finish-function))
  17362    ((org-babel-hash-at-point))
  17363    ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
  17364    (t
  17365     (let* ((context
  17366 	    (org-element-lineage
  17367 	     (org-element-context)
  17368 	     ;; Limit to supported contexts.
  17369 	     '(babel-call clock dynamic-block footnote-definition
  17370 			  footnote-reference inline-babel-call inline-src-block
  17371 			  inlinetask item keyword node-property paragraph
  17372 			  plain-list planning property-drawer radio-target
  17373 			  src-block statistics-cookie table table-cell table-row
  17374 			  timestamp)
  17375 	     t))
  17376 	   (radio-list-p (org-at-radio-list-p))
  17377 	   (type (org-element-type context)))
  17378       ;; For convenience: at the first line of a paragraph on the same
  17379       ;; line as an item, apply function on that item instead.
  17380       (when (eq type 'paragraph)
  17381 	(let ((parent (org-element-property :parent context)))
  17382 	  (when (and (eq (org-element-type parent) 'item)
  17383 		     (= (line-beginning-position)
  17384 			(org-element-property :begin parent)))
  17385 	    (setq context parent)
  17386 	    (setq type 'item))))
  17387       ;; Act according to type of element or object at point.
  17388       ;;
  17389       ;; Do nothing on a blank line, except if it is contained in
  17390       ;; a source block.  Hence, we first check if point is in such
  17391       ;; a block and then if it is at a blank line.
  17392       (pcase type
  17393 	((or `inline-src-block `src-block)
  17394 	 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
  17395 	   (org-babel-eval-wipe-error-buffer)
  17396 	   (org-babel-execute-src-block
  17397 	    current-prefix-arg (org-babel-get-src-block-info nil context))))
  17398 	((guard (org-match-line "[ \t]*$"))
  17399 	 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
  17400 	     (user-error
  17401 	      (substitute-command-keys
  17402 	       "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))
  17403 	((or `babel-call `inline-babel-call)
  17404 	 (let ((info (org-babel-lob-get-info context)))
  17405 	   (when info (org-babel-execute-src-block nil info nil type))))
  17406 	(`clock
  17407          (if (org-at-timestamp-p 'lax)
  17408              ;; Update the timestamp as well.  `org-timestamp-change'
  17409              ;; will call `org-clock-update-time-maybe'.
  17410              (org-timestamp-change 0 'day)
  17411            (org-clock-update-time-maybe)))
  17412 	(`dynamic-block
  17413 	 (save-excursion
  17414 	   (goto-char (org-element-property :post-affiliated context))
  17415 	   (org-update-dblock)))
  17416 	(`footnote-definition
  17417 	 (goto-char (org-element-property :post-affiliated context))
  17418 	 (call-interactively 'org-footnote-action))
  17419 	(`footnote-reference (call-interactively #'org-footnote-action))
  17420 	((or `headline `inlinetask)
  17421 	 (save-excursion (goto-char (org-element-property :begin context))
  17422 			 (call-interactively #'org-set-tags-command)))
  17423 	(`item
  17424 	 ;; At an item: `C-u C-u' sets checkbox to "[-]"
  17425 	 ;; unconditionally, whereas `C-u' will toggle its presence.
  17426 	 ;; Without a universal argument, if the item has a checkbox,
  17427 	 ;; toggle it.  Otherwise repair the list.
  17428 	 (if (or radio-list-p
  17429 		 (and (boundp org-list-checkbox-radio-mode)
  17430 		      org-list-checkbox-radio-mode))
  17431 	     (org-toggle-radio-button arg)
  17432 	   (let* ((box (org-element-property :checkbox context))
  17433 		  (struct (org-element-property :structure context))
  17434 		  (old-struct (copy-tree struct))
  17435 		  (parents (org-list-parents-alist struct))
  17436 		  (prevs (org-list-prevs-alist struct))
  17437 		  (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
  17438 	     (org-list-set-checkbox
  17439 	      (org-element-property :begin context) struct
  17440 	      (cond ((equal arg '(16)) "[-]")
  17441 		    ((and (not box) (equal arg '(4))) "[ ]")
  17442 		    ((or (not box) (equal arg '(4))) nil)
  17443 		    ((eq box 'on) "[ ]")
  17444 		    (t "[X]")))
  17445 	     ;; Mimic `org-list-write-struct' but with grabbing a return
  17446 	     ;; value from `org-list-struct-fix-box'.
  17447 	     (org-list-struct-fix-ind struct parents 2)
  17448 	     (org-list-struct-fix-item-end struct)
  17449 	     (org-list-struct-fix-bul struct prevs)
  17450 	     (org-list-struct-fix-ind struct parents)
  17451 	     (let ((block-item
  17452 		    (org-list-struct-fix-box struct parents prevs orderedp)))
  17453 	       (if (and box (equal struct old-struct))
  17454 		   (if (equal arg '(16))
  17455 		       (message "Checkboxes already reset")
  17456 		     (user-error "Cannot toggle this checkbox: %s"
  17457 				 (if (eq box 'on)
  17458 				     "all subitems checked"
  17459 				   "unchecked subitems")))
  17460 		 (org-list-struct-apply-struct struct old-struct)
  17461 		 (org-update-checkbox-count-maybe))
  17462 	       (when block-item
  17463 		 (message "Checkboxes were removed due to empty box at line %d"
  17464 			  (org-current-line block-item)))))))
  17465 	(`plain-list
  17466 	 ;; At a plain list, with a double C-u argument, set
  17467 	 ;; checkboxes of each item to "[-]", whereas a single one
  17468 	 ;; will toggle their presence according to the state of the
  17469 	 ;; first item in the list.  Without an argument, repair the
  17470 	 ;; list.
  17471 	 (if (or radio-list-p
  17472 		 (and (boundp org-list-checkbox-radio-mode)
  17473 		      org-list-checkbox-radio-mode))
  17474 	     (org-toggle-radio-button arg)
  17475 	   (let* ((begin (org-element-property :contents-begin context))
  17476 		  (struct (org-element-property :structure context))
  17477 		  (old-struct (copy-tree struct))
  17478 		  (first-box (save-excursion
  17479 			       (goto-char begin)
  17480 			       (looking-at org-list-full-item-re)
  17481 			       (match-string-no-properties 3)))
  17482 		  (new-box (cond ((equal arg '(16)) "[-]")
  17483 				 ((equal arg '(4)) (unless first-box "[ ]"))
  17484 				 ((equal first-box "[X]") "[ ]")
  17485 				 (t "[X]"))))
  17486 	     (cond
  17487 	      (arg
  17488 	       (dolist (pos
  17489 			(org-list-get-all-items
  17490 			 begin struct (org-list-prevs-alist struct)))
  17491 		 (org-list-set-checkbox pos struct new-box)))
  17492 	      ((and first-box (eq (point) begin))
  17493 	       ;; For convenience, when point is at bol on the first
  17494 	       ;; item of the list and no argument is provided, simply
  17495 	       ;; toggle checkbox of that item, if any.
  17496 	       (org-list-set-checkbox begin struct new-box)))
  17497 	     (when (equal
  17498 		    (org-list-write-struct
  17499 		     struct (org-list-parents-alist struct) old-struct)
  17500 		    old-struct)
  17501 	       (message "Cannot update this checkbox"))
  17502 	     (org-update-checkbox-count-maybe))))
  17503 	(`keyword
  17504 	 (let ((org-inhibit-startup-visibility-stuff t)
  17505 	       (org-startup-align-all-tables nil))
  17506 	   (when (boundp 'org-table-coordinate-overlays)
  17507 	     (mapc #'delete-overlay org-table-coordinate-overlays)
  17508 	     (setq org-table-coordinate-overlays nil))
  17509 	   (org-save-outline-visibility 'use-markers (org-mode-restart)))
  17510 	 (message "Local setup has been refreshed"))
  17511 	((or `property-drawer `node-property)
  17512 	 (call-interactively #'org-property-action))
  17513 	(`radio-target
  17514 	 (call-interactively #'org-update-radio-target-regexp))
  17515 	(`statistics-cookie
  17516 	 (call-interactively #'org-update-statistics-cookies))
  17517 	((or `table `table-cell `table-row)
  17518 	 ;; At a table, generate a plot if on the #+plot line,
  17519          ;; recalculate every field and align it otherwise.  Also
  17520 	 ;; send the table if necessary.
  17521          (cond
  17522           ((and (org-match-line "[ \t]*#\\+plot:")
  17523                 (< (point) (org-element-property :post-affiliated context)))
  17524            (org-plot/gnuplot))
  17525           ;; If the table has a `table.el' type, just give up.
  17526           ((eq (org-element-property :type context) 'table.el)
  17527            (message "%s" (substitute-command-keys "\\<org-mode-map>\
  17528 Use `\\[org-edit-special]' to edit table.el tables")))
  17529           ;; At a table row or cell, maybe recalculate line but always
  17530 	  ;; align table.
  17531           ((or (eq type 'table)
  17532                ;; Check if point is at a TBLFM line.
  17533                (and (eq type 'table-row)
  17534                     (= (point) (org-element-property :end context))))
  17535            (save-excursion
  17536              (if (org-at-TBLFM-p)
  17537                  (progn (require 'org-table)
  17538                         (org-table-calc-current-TBLFM))
  17539                (goto-char (org-element-property :contents-begin context))
  17540                (org-call-with-arg 'org-table-recalculate (or arg t))
  17541                (orgtbl-send-table 'maybe))))
  17542           (t
  17543            (org-table-maybe-eval-formula)
  17544            (cond (arg (call-interactively #'org-table-recalculate))
  17545                  ((org-table-maybe-recalculate-line))
  17546                  (t (org-table-align))))))
  17547 	((or `timestamp (and `planning (guard (org-at-timestamp-p 'lax))))
  17548 	 (org-timestamp-change 0 'day))
  17549 	((and `nil (guard (org-at-heading-p)))
  17550 	 ;; When point is on an unsupported object type, we can miss
  17551 	 ;; the fact that it also is at a heading.  Handle it here.
  17552 	 (call-interactively #'org-set-tags-command))
  17553 	((guard
  17554 	  (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)))
  17555 	(_
  17556 	 (user-error
  17557 	  (substitute-command-keys
  17558 	   "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))))))
  17559 
  17560 (defun org-mode-restart ()
  17561   "Restart `org-mode'."
  17562   (interactive)
  17563   (let ((indent-status (bound-and-true-p org-indent-mode)))
  17564     (funcall major-mode)
  17565     (hack-local-variables)
  17566     (when (and indent-status (not (bound-and-true-p org-indent-mode)))
  17567       (org-indent-mode -1))
  17568     (org-reset-file-cache))
  17569   (message "%s restarted" major-mode))
  17570 
  17571 (defun org-kill-note-or-show-branches ()
  17572   "Abort storing current note, or show just branches."
  17573   (interactive)
  17574   (cond (org-finish-function
  17575 	 (let ((org-note-abort t)) (funcall org-finish-function)))
  17576 	((org-before-first-heading-p)
  17577 	 (org-fold-show-branches-buffer)
  17578 	 (org-fold-hide-archived-subtrees (point-min) (point-max)))
  17579 	(t
  17580 	 (let ((beg (progn (org-back-to-heading) (point)))
  17581 	       (end (save-excursion (org-end-of-subtree t t) (point))))
  17582 	   (org-fold-hide-subtree)
  17583 	   (org-fold-show-branches)
  17584 	   (org-fold-hide-archived-subtrees beg end)))))
  17585 
  17586 (defun org-delete-indentation (&optional arg)
  17587   "Join current line to previous and fix whitespace at join.
  17588 
  17589 If previous line is a headline add to headline title.  Otherwise
  17590 the function calls `delete-indentation'.
  17591 
  17592 I.e. with a non-nil optional argument, join the line with the
  17593 following one.  If there is a region then join the lines in that
  17594 region."
  17595   (interactive "*P")
  17596   (if (save-excursion
  17597 	(beginning-of-line (if arg 1 0))
  17598 	(let ((case-fold-search nil))
  17599 	  (looking-at org-complex-heading-regexp)))
  17600       ;; At headline.
  17601       (let ((tags-column (when (match-beginning 5)
  17602 			   (save-excursion (goto-char (match-beginning 5))
  17603 					   (current-column))))
  17604 	    (string (concat " " (progn (when arg (forward-line 1))
  17605 				       (org-trim (delete-and-extract-region
  17606 						  (line-beginning-position)
  17607 						  (line-end-position)))))))
  17608 	(unless (bobp) (delete-region (point) (1- (point))))
  17609 	(goto-char (or (match-end 4)
  17610 		       (match-beginning 5)
  17611 		       (match-end 0)))
  17612 	(skip-chars-backward " \t")
  17613 	(save-excursion (insert string))
  17614 	;; Adjust alignment of tags.
  17615 	(cond
  17616 	 ((not tags-column))		;no tags
  17617 	 (org-auto-align-tags (org-align-tags))
  17618 	 (t (org--align-tags-here tags-column)))) ;preserve tags column
  17619     (let ((current-prefix-arg arg))
  17620       (call-interactively #'delete-indentation))))
  17621 
  17622 (defun org-open-line (n)
  17623   "Insert a new row in tables, call `open-line' elsewhere.
  17624 If `org-special-ctrl-o' is nil, just call `open-line' everywhere.
  17625 As a special case, when a document starts with a table, allow to
  17626 call `open-line' on the very first character."
  17627   (interactive "*p")
  17628   (if (and org-special-ctrl-o (/= (point) 1) (org-at-table-p))
  17629       (org-table-insert-row)
  17630     (open-line n)))
  17631 
  17632 (defun org--newline (indent arg interactive)
  17633   "Call `newline-and-indent' or just `newline'.
  17634 If INDENT is non-nil, call `newline-and-indent' with ARG to
  17635 indent unconditionally; otherwise, call `newline' with ARG and
  17636 INTERACTIVE, which can trigger indentation if
  17637 `electric-indent-mode' is enabled."
  17638   (if indent
  17639       (org-newline-and-indent arg)
  17640     (newline arg interactive)))
  17641 
  17642 (defun org-return (&optional indent arg interactive)
  17643   "Goto next table row or insert a newline.
  17644 
  17645 Calls `org-table-next-row' or `newline', depending on context.
  17646 
  17647 When optional INDENT argument is non-nil, call
  17648 `newline-and-indent' with ARG, otherwise call `newline' with ARG
  17649 and INTERACTIVE.
  17650 
  17651 When `org-return-follows-link' is non-nil and point is on
  17652 a timestamp or a link, call `org-open-at-point'.  However, it
  17653 will not happen if point is in a table or on a \"dead\"
  17654 object (e.g., within a comment).  In these case, you need to use
  17655 `org-open-at-point' directly."
  17656   (interactive "i\nP\np")
  17657   (let* ((context (if org-return-follows-link (org-element-context)
  17658 		    (org-element-at-point)))
  17659          (element-type (org-element-type context)))
  17660     (cond
  17661      ;; In a table, call `org-table-next-row'.  However, before first
  17662      ;; column or after last one, split the table.
  17663      ((or (and (eq 'table element-type)
  17664 	       (not (eq 'table.el (org-element-property :type context)))
  17665 	       (>= (point) (org-element-property :contents-begin context))
  17666 	       (< (point) (org-element-property :contents-end context)))
  17667 	  (org-element-lineage context '(table-row table-cell) t))
  17668       (if (or (looking-at-p "[ \t]*$")
  17669 	      (save-excursion (skip-chars-backward " \t") (bolp)))
  17670 	  (insert "\n")
  17671 	(org-table-justify-field-maybe)
  17672 	(call-interactively #'org-table-next-row)))
  17673      ;; On a link or a timestamp, call `org-open-at-point' if
  17674      ;; `org-return-follows-link' allows it.  Tolerate fuzzy
  17675      ;; locations, e.g., in a comment, as `org-open-at-point'.
  17676      ((and org-return-follows-link
  17677 	   (or (and (eq 'link element-type)
  17678 		    ;; Ensure point is not on the white spaces after
  17679 		    ;; the link.
  17680 		    (let ((origin (point)))
  17681 		      (org-with-point-at (org-element-property :end context)
  17682 			(skip-chars-backward " \t")
  17683 			(> (point) origin))))
  17684 	       (org-in-regexp org-ts-regexp-both nil t)
  17685 	       (org-in-regexp org-tsr-regexp-both nil  t)
  17686 	       (org-in-regexp org-link-any-re nil t)))
  17687       (call-interactively #'org-open-at-point))
  17688      ;; Insert newline in heading, but preserve tags.
  17689      ((and (not (bolp))
  17690 	   (let ((case-fold-search nil))
  17691 	     (org-match-line org-complex-heading-regexp)))
  17692       ;; At headline.  Split line.  However, if point is on keyword,
  17693       ;; priority cookie or tags, do not break any of them: add
  17694       ;; a newline after the headline instead.
  17695       (let ((tags-column (and (match-beginning 5)
  17696 			      (save-excursion (goto-char (match-beginning 5))
  17697 					      (current-column))))
  17698 	    (string
  17699 	     (when (and (match-end 4) (org-point-in-group (point) 4))
  17700 	       (delete-and-extract-region (point) (match-end 4)))))
  17701 	;; Adjust tag alignment.
  17702 	(cond
  17703 	 ((not (and tags-column string)))
  17704 	 (org-auto-align-tags (org-align-tags))
  17705 	 (t (org--align-tags-here tags-column))) ;preserve tags column
  17706 	(end-of-line)
  17707 	(org-fold-show-entry 'hide-drawers)
  17708 	(org--newline indent arg interactive)
  17709 	(when string (save-excursion (insert (org-trim string))))))
  17710      ;; In a list, make sure indenting keeps trailing text within.
  17711      ((and (not (eolp))
  17712 	   (org-element-lineage context '(item)))
  17713       (let ((trailing-data
  17714 	     (delete-and-extract-region (point) (line-end-position))))
  17715 	(org--newline indent arg interactive)
  17716 	(save-excursion (insert trailing-data))))
  17717      (t
  17718       ;; Do not auto-fill when point is in an Org property drawer.
  17719       (let ((auto-fill-function (and (not (org-at-property-p))
  17720 				     auto-fill-function)))
  17721 	(org--newline indent arg interactive))))))
  17722 
  17723 (defun org-return-and-maybe-indent ()
  17724   "Goto next table row, or insert a newline, maybe indented.
  17725 Call `org-table-next-row' or `org-return', depending on context.
  17726 See the individual commands for more information.
  17727 
  17728 When inserting a newline, if `org-adapt-indentation' is t:
  17729 indent the line if `electric-indent-mode' is disabled, don't
  17730 indent it if it is enabled."
  17731   (interactive)
  17732   (org-return (not electric-indent-mode)))
  17733 
  17734 (defun org-ctrl-c-tab (&optional arg)
  17735   "Toggle columns width in a table, or show children.
  17736 Call `org-table-toggle-column-width' if point is in a table.
  17737 Otherwise provide a compact view of the children.  ARG is the
  17738 level to hide."
  17739   (interactive "p")
  17740   (cond
  17741    ((org-at-table-p)
  17742     (call-interactively #'org-table-toggle-column-width))
  17743    ((org-before-first-heading-p)
  17744     (save-excursion
  17745       (org-fold-flag-above-first-heading)
  17746       (org-fold-hide-sublevels (or arg 1))))
  17747    (t
  17748     (org-fold-hide-subtree)
  17749     (org-fold-show-children arg))))
  17750 
  17751 (defun org-ctrl-c-star ()
  17752   "Compute table, or change heading status of lines.
  17753 Calls `org-table-recalculate' or `org-toggle-heading',
  17754 depending on context."
  17755   (interactive)
  17756   (cond
  17757    ((org-at-table-p)
  17758     (call-interactively 'org-table-recalculate))
  17759    (t
  17760     ;; Convert all lines in region to list items
  17761     (call-interactively 'org-toggle-heading))))
  17762 
  17763 (defun org-ctrl-c-minus ()
  17764   "Insert separator line in table or modify bullet status of line.
  17765 Also turns a plain line or a region of lines into list items.
  17766 Calls `org-table-insert-hline', `org-toggle-item', or
  17767 `org-cycle-list-bullet', depending on context."
  17768   (interactive)
  17769   (cond
  17770    ((org-at-table-p)
  17771     (call-interactively 'org-table-insert-hline))
  17772    ((org-region-active-p)
  17773     (call-interactively 'org-toggle-item))
  17774    ((org-in-item-p)
  17775     (call-interactively 'org-cycle-list-bullet))
  17776    (t
  17777     (call-interactively 'org-toggle-item))))
  17778 
  17779 (defun org-toggle-heading (&optional nstars)
  17780   "Convert headings to normal text, or items or text to headings.
  17781 If there is no active region, only convert the current line.
  17782 
  17783 With a `\\[universal-argument]' prefix, convert the whole list at
  17784 point into heading.
  17785 
  17786 In a region:
  17787 
  17788 - If the first non blank line is a headline, remove the stars
  17789   from all headlines in the region.
  17790 
  17791 - If it is a normal line, turn each and every normal line (i.e.,
  17792   not an heading or an item) in the region into headings.  If you
  17793   want to convert only the first line of this region, use one
  17794   universal prefix argument.
  17795 
  17796 - If it is a plain list item, turn all plain list items into headings.
  17797   The checkboxes are converted to appropriate TODO or DONE keywords
  17798   (using `car' or `org-done-keywords' and `org-not-done-keywords' when
  17799   available).
  17800 
  17801 When converting a line into a heading, the number of stars is chosen
  17802 such that the lines become children of the current entry.  However,
  17803 when a numeric prefix argument is given, its value determines the
  17804 number of stars to add."
  17805   (interactive "P")
  17806   (let ((skip-blanks
  17807 	 ;; Return beginning of first non-blank line, starting from
  17808 	 ;; line at POS.
  17809 	 (lambda (pos)
  17810 	   (save-excursion
  17811 	     (goto-char pos)
  17812 	     (while (org-at-comment-p) (forward-line))
  17813 	     (skip-chars-forward " \r\t\n")
  17814              (line-beginning-position))))
  17815 	beg end toggled)
  17816     ;; Determine boundaries of changes.  If a universal prefix has
  17817     ;; been given, put the list in a region.  If region ends at a bol,
  17818     ;; do not consider the last line to be in the region.
  17819 
  17820     (when (and current-prefix-arg (org-at-item-p))
  17821       (when (listp current-prefix-arg) (setq current-prefix-arg 1))
  17822       (org-mark-element))
  17823 
  17824     (if (org-region-active-p)
  17825 	(setq beg (funcall skip-blanks (region-beginning))
  17826 	      end (copy-marker (save-excursion
  17827 				 (goto-char (region-end))
  17828                                  (if (bolp) (point) (line-end-position)))))
  17829       (setq beg (funcall skip-blanks (line-beginning-position))
  17830             end (copy-marker (line-end-position))))
  17831     ;; Ensure inline tasks don't count as headings.
  17832     (org-with-limited-levels
  17833      (save-excursion
  17834        (goto-char beg)
  17835        (cond
  17836 	;; Case 1. Started at an heading: de-star headings.
  17837 	((org-at-heading-p)
  17838 	 (while (< (point) end)
  17839 	   (when (org-at-heading-p)
  17840 	     (looking-at org-outline-regexp) (replace-match "")
  17841 	     (setq toggled t))
  17842 	   (forward-line)))
  17843 	;; Case 2. Started at an item: change items into headlines.
  17844 	;;         One star will be added by `org-list-to-subtree'.
  17845 	((org-at-item-p)
  17846 	 (while (< (point) end)
  17847 	   (when (org-at-item-p)
  17848 	     ;; Pay attention to cases when region ends before list.
  17849 	     (let* ((struct (org-list-struct))
  17850 		    (list-end
  17851 		     (min (org-list-get-bottom-point struct) (1+ end))))
  17852 	       (save-restriction
  17853 		 (narrow-to-region (point) list-end)
  17854 		 (insert (org-list-to-subtree
  17855 			  (org-list-to-lisp t)
  17856 			  (pcase (org-current-level)
  17857 			    (`nil 1)
  17858 			    (l (1+ (org-reduced-level l))))
  17859                           ;; Keywords to replace checkboxes.
  17860                           (list
  17861                            ;; [X]
  17862                            :cbon (concat (or (car org-done-keywords) "DONE") " ")
  17863                            ;; [ ]
  17864                            :cboff (concat (or (car org-not-done-keywords) "TODO") " ")
  17865                            ;; [-]
  17866                            :cbtrans (concat (or (car org-not-done-keywords) "TODO") " ")))
  17867 			 "\n")))
  17868 	     (setq toggled t))
  17869 	   (forward-line)))
  17870 	;; Case 3. Started at normal text: make every line an heading,
  17871 	;;         skipping headlines and items.
  17872 	(t (let* ((stars
  17873 		   (make-string
  17874 		    (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
  17875 		  (add-stars
  17876 		   (cond (nstars "")	; stars from prefix only
  17877 			 ((equal stars "") "*")	; before first heading
  17878 			 (org-odd-levels-only "**") ; inside heading, odd
  17879 			 (t "*")))	; inside heading, oddeven
  17880 		  (rpl (concat stars add-stars " "))
  17881 		  (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
  17882 	     (while (< (point) (if (equal nstars '(4)) lend end))
  17883 	       (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
  17884 			  (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
  17885 		 (replace-match (concat rpl (match-string 2))) (setq toggled t))
  17886 	       (forward-line)))))))
  17887     (unless toggled (message "Cannot toggle heading from here"))))
  17888 
  17889 (defun org-meta-return (&optional arg)
  17890   "Insert a new heading or wrap a region in a table.
  17891 Calls `org-insert-heading', `org-insert-item' or
  17892 `org-table-wrap-region', depending on context.  When called with
  17893 an argument, unconditionally call `org-insert-heading'."
  17894   (interactive "P")
  17895   (org-fold-check-before-invisible-edit 'insert)
  17896   (or (run-hook-with-args-until-success 'org-metareturn-hook)
  17897       (call-interactively (cond (arg #'org-insert-heading)
  17898 				((org-at-table-p) #'org-table-wrap-region)
  17899 				((org-in-item-p) #'org-insert-item)
  17900 				(t #'org-insert-heading)))))
  17901 
  17902 ;;; Menu entries
  17903 (defsubst org-in-subtree-not-table-p ()
  17904   "Are we in a subtree and not in a table?"
  17905   (and (not (org-before-first-heading-p))
  17906        (not (org-at-table-p))))
  17907 
  17908 ;; Define the Org mode menus
  17909 (easy-menu-define org-org-menu org-mode-map "Org menu."
  17910   `("Org"
  17911     ("Show/Hide"
  17912      ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
  17913      ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
  17914      ["Sparse Tree..." org-sparse-tree t]
  17915      ["Reveal Context" org-fold-reveal t]
  17916      ["Show All" org-fold-show-all t]
  17917      "--"
  17918      ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
  17919     "--"
  17920     ["New Heading" org-insert-heading t]
  17921     ("Navigate Headings"
  17922      ["Up" outline-up-heading t]
  17923      ["Next" outline-next-visible-heading t]
  17924      ["Previous" outline-previous-visible-heading t]
  17925      ["Next Same Level" outline-forward-same-level t]
  17926      ["Previous Same Level" outline-backward-same-level t]
  17927      "--"
  17928      ["Jump" org-goto t])
  17929     ("Edit Structure"
  17930      ["Move Subtree Up" org-metaup (org-at-heading-p)]
  17931      ["Move Subtree Down" org-metadown (org-at-heading-p)]
  17932      "--"
  17933      ["Copy Subtree"  org-copy-special (org-in-subtree-not-table-p)]
  17934      ["Cut Subtree"  org-cut-special (org-in-subtree-not-table-p)]
  17935      ["Paste Subtree"  org-paste-special (not (org-at-table-p))]
  17936      "--"
  17937      ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
  17938      "--"
  17939      ["Copy visible text"  org-copy-visible t]
  17940      "--"
  17941      ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
  17942      ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
  17943      ["Demote Heading"  org-metaright (org-in-subtree-not-table-p)]
  17944      ["Demote Subtree"  org-shiftmetaright (org-in-subtree-not-table-p)]
  17945      "--"
  17946      ["Sort Region/Children" org-sort t]
  17947      "--"
  17948      ["Convert to odd levels" org-convert-to-odd-levels t]
  17949      ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
  17950     ("Editing"
  17951      ["Emphasis..." org-emphasize t]
  17952      ["Add block structure" org-insert-structure-template t]
  17953      ["Edit Source Example" org-edit-special t]
  17954      "--"
  17955      ["Footnote new/jump" org-footnote-action t]
  17956      ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
  17957     ("Archive"
  17958      ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
  17959      "--"
  17960      ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
  17961      ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
  17962      ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)])
  17963     "--"
  17964     ("Hyperlinks"
  17965      ["Store Link (Global)" org-store-link t]
  17966      ["Find existing link to here" org-occur-link-in-agenda-files t]
  17967      ["Insert Link" org-insert-link t]
  17968      ["Follow Link" org-open-at-point t]
  17969      "--"
  17970      ["Next link" org-next-link t]
  17971      ["Previous link" org-previous-link t]
  17972      "--"
  17973      ["Descriptive Links"
  17974       org-toggle-link-display
  17975       :style radio
  17976       :selected org-descriptive-links
  17977       ]
  17978      ["Literal Links"
  17979       org-toggle-link-display
  17980       :style radio
  17981       :selected (not org-descriptive-links)])
  17982     "--"
  17983     ("TODO Lists"
  17984      ["TODO/DONE/-" org-todo t]
  17985      ("Select keyword"
  17986       ["Next keyword" org-shiftright (org-at-heading-p)]
  17987       ["Previous keyword" org-shiftleft (org-at-heading-p)]
  17988       ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
  17989       ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
  17990       ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
  17991      ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
  17992      ["Global TODO list" org-todo-list :active t :keys "\\[org-agenda] t"]
  17993      "--"
  17994      ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
  17995       :selected org-enforce-todo-dependencies :style toggle :active t]
  17996      "Settings for tree at point"
  17997      ["Do Children sequentially" org-toggle-ordered-property :style radio
  17998       :selected (org-entry-get nil "ORDERED")
  17999       :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18000      ["Do Children parallel" org-toggle-ordered-property :style radio
  18001       :selected (not (org-entry-get nil "ORDERED"))
  18002       :active org-enforce-todo-dependencies :keys "C-c C-x o"]
  18003      "--"
  18004      ["Set Priority" org-priority t]
  18005      ["Priority Up" org-shiftup t]
  18006      ["Priority Down" org-shiftdown t]
  18007      "--"
  18008      ["Get news from all feeds" org-feed-update-all t]
  18009      ["Go to the inbox of a feed..." org-feed-goto-inbox t]
  18010      ["Customize feeds" (customize-variable 'org-feed-alist) t])
  18011     ("TAGS and Properties"
  18012      ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
  18013      ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
  18014      "--"
  18015      ["Set property" org-set-property (not (org-before-first-heading-p))]
  18016      ["Column view of properties" org-columns t]
  18017      ["Insert Column View DBlock" org-columns-insert-dblock t])
  18018     ("Dates and Scheduling"
  18019      ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
  18020      ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
  18021      ("Change Date"
  18022       ["1 Day Later" org-shiftright (org-at-timestamp-p 'lax)]
  18023       ["1 Day Earlier" org-shiftleft (org-at-timestamp-p 'lax)]
  18024       ["1 ... Later" org-shiftup (org-at-timestamp-p 'lax)]
  18025       ["1 ... Earlier" org-shiftdown (org-at-timestamp-p 'lax)])
  18026      ["Compute Time Range" org-evaluate-time-range t]
  18027      ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
  18028      ["Deadline" org-deadline (not (org-before-first-heading-p))]
  18029      "--"
  18030      ["Custom time format" org-toggle-time-stamp-overlays
  18031       :style radio :selected org-display-custom-times]
  18032      "--"
  18033      ["Goto Calendar" org-goto-calendar t]
  18034      ["Date from Calendar" org-date-from-calendar t]
  18035      "--"
  18036      ["Start/Restart Timer" org-timer-start t]
  18037      ["Pause/Continue Timer" org-timer-pause-or-continue t]
  18038      ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
  18039      ["Insert Timer String" org-timer t]
  18040      ["Insert Timer Item" org-timer-item t])
  18041     ("Logging work"
  18042      ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
  18043      ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
  18044      ["Clock out" org-clock-out t]
  18045      ["Clock cancel" org-clock-cancel t]
  18046      "--"
  18047      ["Mark as default task" org-clock-mark-default-task t]
  18048      ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
  18049      ["Goto running clock" org-clock-goto t]
  18050      "--"
  18051      ["Display times" org-clock-display t]
  18052      ["Create clock table" org-clock-report t]
  18053      "--"
  18054      ["Record DONE time"
  18055       (progn (setq org-log-done (not org-log-done))
  18056 	     (message "Switching to %s will %s record a timestamp"
  18057 		      (car org-done-keywords)
  18058 		      (if org-log-done "automatically" "not")))
  18059       :style toggle :selected org-log-done])
  18060     "--"
  18061     ["Agenda Command..." org-agenda t]
  18062     ["Set Restriction Lock" org-agenda-set-restriction-lock t]
  18063     ("File List for Agenda")
  18064     ("Special views current file"
  18065      ["TODO Tree"  org-show-todo-tree t]
  18066      ["Check Deadlines" org-check-deadlines t]
  18067      ["Tags/Property tree" org-match-sparse-tree t])
  18068     "--"
  18069     ["Export/Publish..." org-export-dispatch t]
  18070     ("LaTeX"
  18071      ["Org CDLaTeX mode" org-cdlatex-mode :active (require 'cdlatex nil t)
  18072       :style toggle :selected org-cdlatex-mode]
  18073      ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
  18074      ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
  18075      ["Modify math symbol" org-cdlatex-math-modify
  18076       (org-inside-LaTeX-fragment-p)]
  18077      ["Insert citation" org-reftex-citation t])
  18078     "--"
  18079     ("Documentation"
  18080      ["Show Version" org-version t]
  18081      ["Info Documentation" org-info t]
  18082      ["Browse Org News" org-browse-news t])
  18083     ("Customize"
  18084      ["Browse Org Group" org-customize t]
  18085      "--"
  18086      ["Expand This Menu" org-create-customize-menu t])
  18087     ["Send bug report" org-submit-bug-report t]
  18088     "--"
  18089     ("Refresh/Reload"
  18090      ["Refresh setup current buffer" org-mode-restart t]
  18091      ["Reload Org (after update)" org-reload t]
  18092      ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])))
  18093 
  18094 (easy-menu-define org-tbl-menu org-mode-map "Org Table menu."
  18095   '("Table"
  18096     ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
  18097     ["Next Field" org-cycle (org-at-table-p)]
  18098     ["Previous Field" org-shifttab (org-at-table-p)]
  18099     ["Next Row" org-return (org-at-table-p)]
  18100     "--"
  18101     ["Blank Field" org-table-blank-field (org-at-table-p)]
  18102     ["Edit Field" org-table-edit-field (org-at-table-p)]
  18103     ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
  18104     "--"
  18105     ("Column"
  18106      ["Move Column Left" org-metaleft (org-at-table-p)]
  18107      ["Move Column Right" org-metaright (org-at-table-p)]
  18108      ["Delete Column" org-shiftmetaleft (org-at-table-p)]
  18109      ["Insert Column" org-shiftmetaright (org-at-table-p)]
  18110      ["Shrink Column" org-table-toggle-column-width (org-at-table-p)])
  18111     ("Row"
  18112      ["Move Row Up" org-metaup (org-at-table-p)]
  18113      ["Move Row Down" org-metadown (org-at-table-p)]
  18114      ["Delete Row" org-shiftmetaup (org-at-table-p)]
  18115      ["Insert Row" org-shiftmetadown (org-at-table-p)]
  18116      ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
  18117      "--"
  18118      ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
  18119     ("Rectangle"
  18120      ["Copy Rectangle" org-copy-special (org-at-table-p)]
  18121      ["Cut Rectangle" org-cut-special (org-at-table-p)]
  18122      ["Paste Rectangle" org-paste-special (org-at-table-p)]
  18123      ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
  18124     "--"
  18125     ("Calculate"
  18126      ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
  18127      ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
  18128      ["Edit Formulas" org-edit-special (org-at-table-p)]
  18129      "--"
  18130      ["Recalculate line" org-table-recalculate (org-at-table-p)]
  18131      ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
  18132      ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
  18133      "--"
  18134      ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
  18135      "--"
  18136      ["Sum Column/Rectangle" org-table-sum
  18137       (or (org-at-table-p) (org-region-active-p))]
  18138      ["Which Column?" org-table-current-column (org-at-table-p)])
  18139     ["Debug Formulas"
  18140      org-table-toggle-formula-debugger
  18141      :style toggle :selected (bound-and-true-p org-table-formula-debug)]
  18142     ["Show Col/Row Numbers"
  18143      org-table-toggle-coordinate-overlays
  18144      :style toggle
  18145      :selected (bound-and-true-p org-table-overlay-coordinates)]
  18146     "--"
  18147     ["Create" org-table-create (not (org-at-table-p))]
  18148     ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
  18149     ["Import from File" org-table-import (not (org-at-table-p))]
  18150     ["Export to File" org-table-export (org-at-table-p)]
  18151     "--"
  18152     ["Create/Convert from/to table.el" org-table-create-with-table.el t]
  18153     "--"
  18154     ("Plot"
  18155      ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
  18156      ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
  18157 
  18158 (defun org-info (&optional node)
  18159   "Read documentation for Org in the info system.
  18160 With optional NODE, go directly to that node."
  18161   (interactive)
  18162   (info (format "(org)%s" (or node ""))))
  18163 
  18164 (defun org-browse-news ()
  18165   "Browse the news for the latest major release."
  18166   (interactive)
  18167   (browse-url "https://orgmode.org/Changes.html"))
  18168 
  18169 ;;;###autoload
  18170 (defun org-submit-bug-report ()
  18171   "Submit a bug report on Org via mail.
  18172 
  18173 Don't hesitate to report any problems or inaccurate documentation.
  18174 
  18175 If you don't have setup sending mail from (X)Emacs, please copy the
  18176 output buffer into your mail program, as it gives us important
  18177 information about your Org version and configuration."
  18178   (interactive)
  18179   (require 'reporter)
  18180   (defvar reporter-prompt-for-summary-p)
  18181   (org-load-modules-maybe)
  18182   (org-require-autoloaded-modules)
  18183   (let ((reporter-prompt-for-summary-p "Bug report subject: "))
  18184     (reporter-submit-bug-report
  18185      "emacs-orgmode@gnu.org"
  18186      (org-version nil 'full)
  18187      (let (list)
  18188        (save-window-excursion
  18189 	 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
  18190 	 (delete-other-windows)
  18191 	 (erase-buffer)
  18192 	 (insert "You are about to submit a bug report to the Org mailing list.
  18193 
  18194 If your report is about Org installation, please read this section:
  18195 https://orgmode.org/org.html#Installation
  18196 
  18197 Please read https://orgmode.org/org.html#Feedback on how to make
  18198 a good report, it will help Org contributors fixing your problem.
  18199 
  18200 Search https://lists.gnu.org/archive/html/emacs-orgmode/ to see
  18201 if the issue you are about to raise has already been dealt with.
  18202 
  18203 We also would like to add your full Org and Outline configuration
  18204 to the bug report.  It will help us debugging the issue.
  18205 
  18206 *HOWEVER*, some variables you have customized may contain private
  18207 information.  The names of customers, colleagues, or friends, might
  18208 appear in the form of file names, tags, todo states or search strings.
  18209 If you answer \"yes\" to the prompt, you might want to check and remove
  18210 such private information before sending the email.")
  18211 	 (add-text-properties (point-min) (point-max) '(face org-warning))
  18212 	 (when (yes-or-no-p "Include your Org configuration ")
  18213 	   (mapatoms
  18214 	    (lambda (v)
  18215 	      (and (boundp v)
  18216 		   (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
  18217 		   (or (and (symbol-value v)
  18218 			    (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
  18219 		       (and
  18220 			(get v 'custom-type) (get v 'standard-value)
  18221 			(not (equal (symbol-value v)
  18222 			            (eval (car (get v 'standard-value)) t)))))
  18223 		   (push v list)))))
  18224 	 (kill-buffer (get-buffer "*Warn about privacy*"))
  18225 	 list))
  18226      nil nil
  18227      "Remember to cover the basics, that is, what you expected to happen and
  18228 what in fact did happen.  You don't know how to make a good report?  See
  18229 
  18230      https://orgmode.org/manual/Feedback.html#Feedback
  18231 
  18232 Your bug report will be posted to the Org mailing list.
  18233 ------------------------------------------------------------------------")
  18234     (save-excursion
  18235       (when (re-search-backward "^\\(Subject: \\)Org mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
  18236 	(replace-match "\\1[BUG] \\3 [\\2]")))))
  18237 
  18238 (defun org-install-agenda-files-menu ()
  18239   "Install agenda file menu."
  18240   (let ((bl (buffer-list)))
  18241     (save-excursion
  18242       (while bl
  18243 	(set-buffer (pop bl))
  18244 	(when (derived-mode-p 'org-mode) (setq bl nil)))
  18245       (when (derived-mode-p 'org-mode)
  18246 	(easy-menu-change
  18247 	 '("Org") "File List for Agenda"
  18248 	 (append
  18249 	  (list
  18250 	   ["Edit File List" (org-edit-agenda-file-list) t]
  18251 	   ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
  18252 	   ["Remove Current File from List" org-remove-file t]
  18253 	   ["Cycle through agenda files" org-cycle-agenda-files t]
  18254 	   ["Occur in all agenda files" org-occur-in-agenda-files t]
  18255 	   "--")
  18256 	  (mapcar 'org-file-menu-entry
  18257 		  ;; Prevent initialization from failing.
  18258 		  (ignore-errors (org-agenda-files t)))))))))
  18259 
  18260 ;;;; Documentation
  18261 
  18262 (defun org-require-autoloaded-modules ()
  18263   (interactive)
  18264   (mapc #'require
  18265 	'(org-agenda org-archive org-attach org-clock org-colview org-id
  18266 		     org-table org-timer)))
  18267 
  18268 ;;;###autoload
  18269 (defun org-reload (&optional uncompiled)
  18270   "Reload all Org Lisp files.
  18271 With prefix arg UNCOMPILED, load the uncompiled versions."
  18272   (interactive "P")
  18273   (require 'loadhist)
  18274   (let* ((org-dir     (org-find-library-dir "org"))
  18275 	 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
  18276 	 (feature-re "^\\(org\\|ob\\|ox\\|ol\\|oc\\)\\(-.*\\)?")
  18277 	 (remove-re (format "\\`%s\\'"
  18278 			    (regexp-opt '("org" "org-loaddefs" "org-version"))))
  18279 	 (feats (delete-dups
  18280 		 (mapcar 'file-name-sans-extension
  18281 			 (mapcar 'file-name-nondirectory
  18282 				 (delq nil
  18283 				       (mapcar 'feature-file
  18284 					       features))))))
  18285 	 (lfeat (append
  18286 		 (sort
  18287 		  (setq feats
  18288 			(delq nil (mapcar
  18289 				   (lambda (f)
  18290 				     (if (and (string-match feature-re f)
  18291 					      (not (string-match remove-re f)))
  18292 					 f nil))
  18293 				   feats)))
  18294 		  'string-lessp)
  18295 		 (list "org-version" "org")))
  18296 	 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
  18297 	 load-uncore load-misses)
  18298     (setq load-misses
  18299 	  (delq t
  18300 		(mapcar (lambda (f)
  18301 			  (or (org-load-noerror-mustsuffix (concat org-dir f))
  18302 			      (and (string= org-dir contrib-dir)
  18303 				   (org-load-noerror-mustsuffix (concat contrib-dir f)))
  18304 			      (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
  18305 				   (push f load-uncore)
  18306 				   t)
  18307 			      f))
  18308 			lfeat)))
  18309     (when load-uncore
  18310       (message "The following feature%s found in load-path, please check if that's correct:\n%s"
  18311 	       (if (> (length load-uncore) 1) "s were" " was")
  18312                (reverse load-uncore)))
  18313     (if load-misses
  18314 	(message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
  18315 		 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
  18316       (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
  18317 
  18318 ;;;###autoload
  18319 (defun org-customize ()
  18320   "Call the customize function with org as argument."
  18321   (interactive)
  18322   (org-load-modules-maybe)
  18323   (org-require-autoloaded-modules)
  18324   (customize-browse 'org))
  18325 
  18326 (defun org-create-customize-menu ()
  18327   "Create a full customization menu for Org mode, insert it into the menu."
  18328   (interactive)
  18329   (org-load-modules-maybe)
  18330   (org-require-autoloaded-modules)
  18331   (easy-menu-change
  18332    '("Org") "Customize"
  18333    `(["Browse Org group" org-customize t]
  18334      "--"
  18335      ,(customize-menu-create 'org)
  18336      ["Set" Custom-set t]
  18337      ["Save" Custom-save t]
  18338      ["Reset to Current" Custom-reset-current t]
  18339      ["Reset to Saved" Custom-reset-saved t]
  18340      ["Reset to Standard Settings" Custom-reset-standard t]))
  18341   (message "\"Org\"-menu now contains full customization menu"))
  18342 
  18343 ;;;; Miscellaneous stuff
  18344 
  18345 ;;; Generally useful functions
  18346 
  18347 (defun org-in-clocktable-p ()
  18348   "Check if the cursor is in a clocktable."
  18349   (let ((pos (point)) start)
  18350     (save-excursion
  18351       (end-of-line 1)
  18352       (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
  18353 	   (setq start (match-beginning 0))
  18354 	   (re-search-forward "^[ \t]*#\\+END:.*" nil t)
  18355 	   (>= (match-end 0) pos)
  18356 	   start))))
  18357 
  18358 (defun org-in-verbatim-emphasis ()
  18359   (save-match-data
  18360     (and (org-in-regexp org-verbatim-re 2)
  18361 	 (>= (point) (match-beginning 3))
  18362 	 (<= (point) (match-end 4)))))
  18363 
  18364 (defun org-goto-marker-or-bmk (marker &optional bookmark)
  18365   "Go to MARKER, widen if necessary.  When marker is not live, try BOOKMARK."
  18366   (if (and marker (marker-buffer marker)
  18367 	   (buffer-live-p (marker-buffer marker)))
  18368       (progn
  18369 	(pop-to-buffer-same-window (marker-buffer marker))
  18370 	(when (or (> marker (point-max)) (< marker (point-min)))
  18371 	  (widen))
  18372 	(goto-char marker)
  18373 	(org-fold-show-context 'org-goto))
  18374     (if bookmark
  18375 	(bookmark-jump bookmark)
  18376       (error "Cannot find location"))))
  18377 
  18378 (defun org-quote-csv-field (s)
  18379   "Quote field for inclusion in CSV material."
  18380   (if (string-match "[\",]" s)
  18381       (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
  18382     s))
  18383 
  18384 (defun org-force-self-insert (N)
  18385   "Needed to enforce self-insert under remapping."
  18386   (interactive "p")
  18387   (self-insert-command N))
  18388 
  18389 (defun org-quote-vert (s)
  18390   "Replace \"|\" with \"\\vert\"."
  18391   (while (string-match "|" s)
  18392     (setq s (replace-match "\\vert" t t s)))
  18393   s)
  18394 
  18395 (defun org-uuidgen-p (s)
  18396   "Is S an ID created by UUIDGEN?"
  18397   (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
  18398 
  18399 (defun org-in-src-block-p (&optional inside element)
  18400   "Whether point is in a code source block.
  18401 When INSIDE is non-nil, don't consider we are within a source
  18402 block when point is at #+BEGIN_SRC or #+END_SRC.
  18403 When ELEMENT is provided, it is considered to be element at point."
  18404   (save-match-data (setq element (or element (org-element-at-point))))
  18405   (when (eq 'src-block (org-element-type element))
  18406     (or (not inside)
  18407         (not (or (= (line-beginning-position)
  18408                     (org-element-property :post-affiliated element))
  18409                  (= (1+ (line-end-position))
  18410                     (- (org-element-property :end element)
  18411                        (org-element-property :post-blank element))))))))
  18412 
  18413 (defun org-context ()
  18414   "Return a list of contexts of the current cursor position.
  18415 If several contexts apply, all are returned.
  18416 Each context entry is a list with a symbol naming the context, and
  18417 two positions indicating start and end of the context.  Possible
  18418 contexts are:
  18419 
  18420 :headline         anywhere in a headline
  18421 :headline-stars   on the leading stars in a headline
  18422 :todo-keyword     on a TODO keyword (including DONE) in a headline
  18423 :tags             on the TAGS in a headline
  18424 :priority         on the priority cookie in a headline
  18425 :item             on the first line of a plain list item
  18426 :item-bullet      on the bullet/number of a plain list item
  18427 :checkbox         on the checkbox in a plain list item
  18428 :table            in an Org table
  18429 :table-special    on a special filed in a table
  18430 :table-table      in a table.el table
  18431 :clocktable       in a clocktable
  18432 :src-block        in a source block
  18433 :link             on a hyperlink
  18434 :keyword          on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
  18435 :latex-fragment   on a LaTeX fragment
  18436 :latex-preview    on a LaTeX fragment with overlaid preview image
  18437 
  18438 This function expects the position to be visible because it uses font-lock
  18439 faces as a help to recognize the following contexts: :table-special, :link,
  18440 and :keyword."
  18441   (let* ((f (get-text-property (point) 'face))
  18442 	 (faces (if (listp f) f (list f)))
  18443 	 (case-fold-search t)
  18444 	 (p (point)) clist o)
  18445     ;; First the large context
  18446     (cond
  18447      ((org-at-heading-p)
  18448       (push (list :headline (line-beginning-position)
  18449                   (line-end-position))
  18450             clist)
  18451       (when (progn
  18452 	      (beginning-of-line 1)
  18453 	      (looking-at org-todo-line-tags-regexp))
  18454 	(push (org-point-in-group p 1 :headline-stars) clist)
  18455 	(push (org-point-in-group p 2 :todo-keyword) clist)
  18456 	(push (org-point-in-group p 4 :tags) clist))
  18457       (goto-char p)
  18458       (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
  18459       (when (looking-at "\\[#[A-Z0-9]\\]")
  18460 	(push (org-point-in-group p 0 :priority) clist)))
  18461 
  18462      ((org-at-item-p)
  18463       (push (org-point-in-group p 2 :item-bullet) clist)
  18464       (push (list :item (line-beginning-position)
  18465 		  (save-excursion (org-end-of-item) (point)))
  18466 	    clist)
  18467       (and (org-at-item-checkbox-p)
  18468 	   (push (org-point-in-group p 0 :checkbox) clist)))
  18469 
  18470      ((org-at-table-p)
  18471       (push (list :table (org-table-begin) (org-table-end)) clist)
  18472       (when (memq 'org-formula faces)
  18473 	(push (list :table-special
  18474 		    (previous-single-property-change p 'face)
  18475 		    (next-single-property-change p 'face))
  18476 	      clist)))
  18477      ((org-at-table-p 'any)
  18478       (push (list :table-table) clist)))
  18479     (goto-char p)
  18480 
  18481     (let ((case-fold-search t))
  18482       ;; New the "medium" contexts: clocktables, source blocks
  18483       (cond ((org-in-clocktable-p)
  18484 	     (push (list :clocktable
  18485 			 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
  18486 				  (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
  18487 			      (match-beginning 1))
  18488 			 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
  18489 			      (match-end 0)))
  18490 		   clist))
  18491 	    ((org-in-src-block-p)
  18492 	     (push (list :src-block
  18493 			 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
  18494 				  (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
  18495 			      (match-beginning 1))
  18496 			 (and (search-forward "#+END_SRC" nil t)
  18497 			      (match-beginning 0)))
  18498 		   clist))))
  18499     (goto-char p)
  18500 
  18501     ;; Now the small context
  18502     (cond
  18503      ((org-at-timestamp-p)
  18504       (push (org-point-in-group p 0 :timestamp) clist))
  18505      ((memq 'org-link faces)
  18506       (push (list :link
  18507 		  (previous-single-property-change p 'face)
  18508 		  (next-single-property-change p 'face))
  18509 	    clist))
  18510      ((memq 'org-special-keyword faces)
  18511       (push (list :keyword
  18512 		  (previous-single-property-change p 'face)
  18513 		  (next-single-property-change p 'face))
  18514 	    clist))
  18515      ((setq o (cl-some
  18516 	       (lambda (o)
  18517 		 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
  18518 		      o))
  18519 	       (overlays-at (point))))
  18520       (push (list :latex-fragment
  18521 		  (overlay-start o) (overlay-end o))
  18522 	    clist)
  18523       (push (list :latex-preview
  18524 		  (overlay-start o) (overlay-end o))
  18525 	    clist))
  18526      ((org-inside-LaTeX-fragment-p)
  18527       ;; FIXME: positions wrong.
  18528       (push (list :latex-fragment (point) (point)) clist)))
  18529 
  18530     (setq clist (nreverse (delq nil clist)))
  18531     clist))
  18532 
  18533 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
  18534   "Non-nil when point is between matches of START-RE and END-RE.
  18535 
  18536 Also return a non-nil value when point is on one of the matches.
  18537 
  18538 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
  18539 buffer positions.  Default values are the positions of headlines
  18540 surrounding the point.
  18541 
  18542 The functions returns a cons cell whose car (resp. cdr) is the
  18543 position before START-RE (resp. after END-RE)."
  18544   (save-match-data
  18545     (let ((pos (point))
  18546 	  (limit-up (or lim-up (save-excursion (outline-previous-heading))))
  18547 	  (limit-down (or lim-down (save-excursion (outline-next-heading))))
  18548 	  beg end)
  18549       (save-excursion
  18550 	;; Point is on a block when on START-RE or if START-RE can be
  18551 	;; found before it...
  18552 	(and (or (org-in-regexp start-re)
  18553 		 (re-search-backward start-re limit-up t))
  18554 	     (setq beg (match-beginning 0))
  18555 	     ;; ... and END-RE after it...
  18556 	     (goto-char (match-end 0))
  18557 	     (re-search-forward end-re limit-down t)
  18558 	     (> (setq end (match-end 0)) pos)
  18559 	     ;; ... without another START-RE in-between.
  18560 	     (goto-char (match-beginning 0))
  18561 	     (not (re-search-backward start-re (1+ beg) t))
  18562 	     ;; Return value.
  18563 	     (cons beg end))))))
  18564 
  18565 (defun org-in-block-p (names)
  18566   "Non-nil when point belongs to a block whose name belongs to NAMES.
  18567 
  18568 NAMES is a list of strings containing names of blocks.
  18569 
  18570 Return first block name matched, or nil.  Beware that in case of
  18571 nested blocks, the returned name may not belong to the closest
  18572 block from point."
  18573   (save-match-data
  18574     (catch 'exit
  18575       (let ((case-fold-search t)
  18576 	    (lim-up (save-excursion (outline-previous-heading)))
  18577 	    (lim-down (save-excursion (outline-next-heading))))
  18578 	(dolist (name names)
  18579 	  (let ((n (regexp-quote name)))
  18580 	    (when (org-between-regexps-p
  18581 		   (concat "^[ \t]*#\\+begin_" n)
  18582 		   (concat "^[ \t]*#\\+end_" n)
  18583 		   lim-up lim-down)
  18584 	      (throw 'exit n)))))
  18585       nil)))
  18586 
  18587 (defun org-occur-in-agenda-files (regexp &optional _nlines)
  18588   "Call `multi-occur' with buffers for all agenda files."
  18589   (interactive "sOrg-files matching: ")
  18590   (let* ((files (org-agenda-files))
  18591 	 (tnames (mapcar #'file-truename files))
  18592 	 (extra org-agenda-text-search-extra-files))
  18593     (when (eq (car extra) 'agenda-archives)
  18594       (setq extra (cdr extra))
  18595       (setq files (org-add-archive-files files)))
  18596     (dolist (f extra)
  18597       (unless (member (file-truename f) tnames)
  18598 	(unless (member f files) (setq files (append files (list f))))
  18599 	(setq tnames (append tnames (list (file-truename f))))))
  18600     (multi-occur
  18601      (mapcar (lambda (x)
  18602 	       (with-current-buffer
  18603 		   ;; FIXME: Why not just (find-file-noselect x)?
  18604 		   ;; Is it to avoid the "revert buffer" prompt?
  18605 		   (or (get-file-buffer x) (find-file-noselect x))
  18606 		 (widen)
  18607 		 (current-buffer)))
  18608 	     files)
  18609      regexp)))
  18610 
  18611 (add-hook 'occur-mode-find-occurrence-hook
  18612 	  (lambda () (when (derived-mode-p 'org-mode) (org-fold-reveal))))
  18613 
  18614 (defun org-occur-link-in-agenda-files ()
  18615   "Create a link and search for it in the agendas.
  18616 The link is not stored in `org-stored-links', it is just created
  18617 for the search purpose."
  18618   (interactive)
  18619   (let ((link (condition-case nil
  18620 		  (org-store-link nil)
  18621 		(error "Unable to create a link to here"))))
  18622     (org-occur-in-agenda-files (regexp-quote link))))
  18623 
  18624 (defun org-back-over-empty-lines ()
  18625   "Move backwards over whitespace, to the beginning of the first empty line.
  18626 Returns the number of empty lines passed."
  18627   (let ((pos (point)))
  18628     (if (cdr (assq 'heading org-blank-before-new-entry))
  18629 	(skip-chars-backward " \t\n\r")
  18630       (unless (eobp)
  18631 	(forward-line -1)))
  18632     (beginning-of-line 2)
  18633     (goto-char (min (point) pos))
  18634     (count-lines (point) pos)))
  18635 
  18636 ;;; TODO: Only called once, from ox-odt which should probably use
  18637 ;;; org-export-inline-image-p or something.
  18638 (defun org-file-image-p (file)
  18639   "Return non-nil if FILE is an image."
  18640   (save-match-data
  18641     (string-match (image-file-name-regexp) file)))
  18642 
  18643 (defun org-get-cursor-date (&optional with-time)
  18644   "Return the date at cursor in as a time.
  18645 This works in the calendar and in the agenda, anywhere else it just
  18646 returns the current time.
  18647 If WITH-TIME is non-nil, returns the time of the event at point (in
  18648 the agenda) or the current time of the day; otherwise returns the
  18649 earliest time on the cursor date that Org treats as that date
  18650 (bearing in mind `org-extend-today-until')."
  18651   (let (date day defd tp hod mod)
  18652     (when with-time
  18653       (setq tp (get-text-property (point) 'time))
  18654       (when (and tp (string-match "\\([0-2]?[0-9]\\):\\([0-5][0-9]\\)" tp))
  18655 	(setq hod (string-to-number (match-string 1 tp))
  18656 	      mod (string-to-number (match-string 2 tp))))
  18657       (or tp (let ((now (decode-time)))
  18658 	       (setq hod (nth 2 now)
  18659 		     mod (nth 1 now)))))
  18660     (cond
  18661      ((eq major-mode 'calendar-mode)
  18662       (setq date (calendar-cursor-to-date)
  18663 	    defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  18664                                   (nth 1 date) (nth 0 date) (nth 2 date))))
  18665      ((eq major-mode 'org-agenda-mode)
  18666       (setq day (get-text-property (point) 'day))
  18667       (when day
  18668 	(setq date (calendar-gregorian-from-absolute day)
  18669 	      defd (org-encode-time 0 (or mod 0) (or hod org-extend-today-until)
  18670                                     (nth 1 date) (nth 0 date) (nth 2 date))))))
  18671     (or defd (current-time))))
  18672 
  18673 (defun org-mark-subtree (&optional up)
  18674   "Mark the current subtree.
  18675 This puts point at the start of the current subtree, and mark at
  18676 the end.  If a numeric prefix UP is given, move up into the
  18677 hierarchy of headlines by UP levels before marking the subtree."
  18678   (interactive "P")
  18679   (org-with-limited-levels
  18680    (cond ((org-at-heading-p) (beginning-of-line))
  18681 	 ((org-before-first-heading-p) (user-error "Not in a subtree"))
  18682 	 (t (outline-previous-visible-heading 1))))
  18683   (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
  18684   (if (called-interactively-p 'any)
  18685       (call-interactively 'org-mark-element)
  18686     (org-mark-element)))
  18687 
  18688 ;;; Indentation
  18689 
  18690 (defun org--at-headline-data-p (&optional beg element)
  18691   "Return non-nil when `point' or BEG is inside headline metadata.
  18692 
  18693 Metadata is planning line, properties drawer, logbook drawer right
  18694 after property drawer, or clock log line immediately following
  18695 properties drawer/planning line/ heading.
  18696 
  18697 Optional argument ELEMENT contains element at BEG."
  18698   (org-with-wide-buffer
  18699    (when beg (goto-char beg))
  18700    (setq element (or element (org-element-at-point)))
  18701    (if (or (eq (org-element-type element) 'headline)
  18702            (not (org-element-lineage element '(headline inlinetask))))
  18703        nil ; Not inside heading.
  18704      ;; Skip to top-level parent in section.
  18705      (while (not (eq 'section (org-element-type (org-element-property :parent element))))
  18706        (setq element (org-element-property :parent element)))
  18707      (pcase (org-element-type element)
  18708        ((or `planning `property-drawer)
  18709         t)
  18710        (`drawer
  18711         ;; LOGBOOK drawer with appropriate name.
  18712         (equal
  18713          (org-log-into-drawer)
  18714          (org-element-property :drawer-name element)))
  18715        (`clock
  18716         ;; Previous element must be headline metadata or headline.
  18717         (goto-char (1- (org-element-property :begin element)))
  18718         (or (org-at-heading-p)
  18719             (org--at-headline-data-p)))))))
  18720 
  18721 (defvar org-element-greater-elements)
  18722 (defun org--get-expected-indentation (element contentsp)
  18723   "Expected indentation column for current line, according to ELEMENT.
  18724 ELEMENT is an element containing point.  CONTENTSP is non-nil
  18725 when indentation is to be computed according to contents of
  18726 ELEMENT."
  18727   (let ((type (org-element-type element))
  18728 	(start (org-element-property :begin element))
  18729 	(post-affiliated (org-element-property :post-affiliated element)))
  18730     (org-with-wide-buffer
  18731      (cond
  18732       (contentsp
  18733        (cl-case type
  18734 	 ((diary-sexp footnote-definition) 0)
  18735          (section
  18736           (org--get-expected-indentation
  18737            (org-element-property :parent element)
  18738            t))
  18739 	 ((headline inlinetask nil)
  18740 	  (if (not org-adapt-indentation) 0
  18741 	    (let ((level (org-current-level)))
  18742 	      (if level (1+ level) 0))))
  18743 	 ((item plain-list) (org-list-item-body-column post-affiliated))
  18744 	 (t
  18745 	  (goto-char start)
  18746 	  (current-indentation))))
  18747       ((memq type '(headline inlinetask nil))
  18748        (if (org-match-line "[ \t]*$")
  18749 	   (org--get-expected-indentation element t)
  18750 	 0))
  18751       ((memq type '(diary-sexp footnote-definition)) 0)
  18752       ;; First paragraph of a footnote definition or an item.
  18753       ;; Indent like parent.
  18754       ((< (line-beginning-position) start)
  18755        (org--get-expected-indentation
  18756 	(org-element-property :parent element) t))
  18757       ;; At first line: indent according to previous sibling, if any,
  18758       ;; ignoring footnote definitions and inline tasks, or parent's
  18759       ;; contents.  If `org-adapt-indentation' is `headline-data', ignore
  18760       ;; previous headline data siblings.
  18761       ((= (line-beginning-position) start)
  18762        (catch 'exit
  18763 	 (while t
  18764 	   (if (= (point-min) start) (throw 'exit 0)
  18765 	     (goto-char (1- start))
  18766 	     (let* ((previous (org-element-at-point))
  18767 		    (parent previous))
  18768 	       (while (and parent (<= (org-element-property :end parent) start))
  18769 		 (setq previous parent
  18770 		       parent (org-element-property :parent parent)))
  18771 	       (cond
  18772 		((not previous) (throw 'exit 0))
  18773 		((> (org-element-property :end previous) start)
  18774 		 (throw 'exit (org--get-expected-indentation previous t)))
  18775 		((memq (org-element-type previous)
  18776 		       '(footnote-definition inlinetask))
  18777 		 (setq start (org-element-property :begin previous)))
  18778                 ;; Do not indent like previous when the previous
  18779                 ;; element is headline data and `org-adapt-indentation'
  18780                 ;; is set to `headline-data'.
  18781                 ((and (eq 'headline-data org-adapt-indentation)
  18782                       (not (org--at-headline-data-p start element))
  18783                       (or (org-at-heading-p)
  18784                           (org--at-headline-data-p (1- start) previous)))
  18785                  (throw 'exit 0))
  18786 		(t (goto-char (org-element-property :begin previous))
  18787 		   (throw 'exit
  18788 			  (if (bolp) (current-indentation)
  18789 			    ;; At first paragraph in an item or
  18790 			    ;; a footnote definition.
  18791 			    (org--get-expected-indentation
  18792 			     (org-element-property :parent previous) t))))))))))
  18793       ;; Otherwise, move to the first non-blank line above.
  18794       (t
  18795        (beginning-of-line)
  18796        (let ((pos (point)))
  18797 	 (skip-chars-backward " \r\t\n")
  18798 	 (cond
  18799 	  ;; Two blank lines end a footnote definition or a plain
  18800 	  ;; list.  When we indent an empty line after them, the
  18801 	  ;; containing list or footnote definition is over, so it
  18802 	  ;; qualifies as a previous sibling.  Therefore, we indent
  18803 	  ;; like its first line.
  18804 	  ((and (memq type '(footnote-definition plain-list))
  18805 		(> (count-lines (point) pos) 2))
  18806 	   (goto-char start)
  18807 	   (current-indentation))
  18808 	  ;; Line above is the first one of a paragraph at the
  18809 	  ;; beginning of an item or a footnote definition.  Indent
  18810 	  ;; like parent.
  18811 	  ((< (line-beginning-position) start)
  18812 	   (org--get-expected-indentation
  18813 	    (org-element-property :parent element) t))
  18814 	  ;; Line above is the beginning of an element, i.e., point
  18815 	  ;; was originally on the blank lines between element's start
  18816 	  ;; and contents.
  18817 	  ((= (line-beginning-position) post-affiliated)
  18818 	   (org--get-expected-indentation element t))
  18819 	  ;; POS is after contents in a greater element.  Indent like
  18820 	  ;; the beginning of the element.
  18821 	  ((and (memq type org-element-greater-elements)
  18822 		(let ((cend (org-element-property :contents-end element)))
  18823 		  (and cend (<= cend pos))))
  18824 	   ;; As a special case, if point is at the end of a footnote
  18825 	   ;; definition or an item, indent like the very last element
  18826 	   ;; within.  If that last element is an item, indent like
  18827 	   ;; its contents.
  18828 	   (if (memq type '(footnote-definition item plain-list))
  18829 	       (let ((last (org-element-at-point)))
  18830 		 (goto-char pos)
  18831 		 (org--get-expected-indentation
  18832 		  last (eq (org-element-type last) 'item)))
  18833 	     (goto-char start)
  18834 	     (current-indentation)))
  18835 	  ;; In any other case, indent like the current line.
  18836 	  (t (current-indentation)))))
  18837       ;; Finally, no indentation is needed, fall back to 0.
  18838       (t (current-indentation))))))
  18839 
  18840 (defun org--align-node-property ()
  18841   "Align node property at point.
  18842 Alignment is done according to `org-property-format', which see."
  18843   (when (save-excursion
  18844 	  (beginning-of-line)
  18845 	  (looking-at org-property-re))
  18846     (combine-change-calls (match-beginning 0) (match-end 0)
  18847       (let ((newtext (concat (match-string 4)
  18848 	                     (org-trim
  18849 	                      (format org-property-format (match-string 1) (match-string 3))))))
  18850         ;; Do not use `replace-match' here as we want to inherit folding
  18851         ;; properties if inside fold.
  18852         (delete-region (match-beginning 0) (match-end 0))
  18853         (insert-and-inherit newtext)))))
  18854 
  18855 (defun org-indent-line ()
  18856   "Indent line depending on context.
  18857 
  18858 Indentation is done according to the following rules:
  18859 
  18860   - Footnote definitions, diary sexps, headlines and inline tasks
  18861     have to start at column 0.
  18862 
  18863   - On the very first line of an element, consider, in order, the
  18864     next rules until one matches:
  18865 
  18866     1. If there's a sibling element before, ignoring footnote
  18867        definitions and inline tasks, indent like its first line.
  18868 
  18869     2. If element has a parent, indent like its contents.  More
  18870        precisely, if parent is an item, indent after the bullet.
  18871        Else, indent like parent's first line.
  18872 
  18873     3. Otherwise, indent relatively to current level, if
  18874        `org-adapt-indentation' is t, or to left margin.
  18875 
  18876   - On a blank line at the end of an element, indent according to
  18877     the type of the element.  More precisely
  18878 
  18879     1. If element is a plain list, an item, or a footnote
  18880        definition, indent like the very last element within.
  18881 
  18882     2. If element is a paragraph, indent like its last non blank
  18883        line.
  18884 
  18885     3. Otherwise, indent like its very first line.
  18886 
  18887   - In the code part of a source block, use language major mode
  18888     to indent current line if `org-src-tab-acts-natively' is
  18889     non-nil.  If it is nil, do nothing.
  18890 
  18891   - Otherwise, indent like the first non-blank line above.
  18892 
  18893 The function doesn't indent an item as it could break the whole
  18894 list structure.  Instead, use \\<org-mode-map>`\\[org-shiftmetaleft]' or \
  18895 `\\[org-shiftmetaright]'.
  18896 
  18897 Also align node properties according to `org-property-format'."
  18898   (interactive)
  18899   (let* ((element (save-excursion (beginning-of-line) (org-element-at-point-no-context)))
  18900 	 (type (org-element-type element)))
  18901     (unless (or (org-at-heading-p)
  18902                 (and (eq org-adapt-indentation 'headline-data)
  18903                      (not (org--at-headline-data-p nil element))
  18904                      (save-excursion
  18905                        (goto-char (1- (org-element-property :begin element)))
  18906                        (or (org-at-heading-p)
  18907                            (org--at-headline-data-p)))))
  18908       (cond ((and (memq type '(plain-list item))
  18909 		  (= (line-beginning-position)
  18910 		     (org-element-property :post-affiliated element)))
  18911 	     nil)
  18912 	    ((and (eq type 'latex-environment)
  18913 		  (>= (point) (org-element-property :post-affiliated element))
  18914 		  (< (point)
  18915 		     (org-with-point-at (org-element-property :end element)
  18916 		       (skip-chars-backward " \t\n")
  18917 		       (line-beginning-position 2))))
  18918 	     nil)
  18919 	    ((and (eq type 'src-block)
  18920 		  org-src-tab-acts-natively
  18921 		  (> (line-beginning-position)
  18922 		     (org-element-property :post-affiliated element))
  18923 		  (< (line-beginning-position)
  18924 		     (org-with-point-at (org-element-property :end element)
  18925 		       (skip-chars-backward " \t\n")
  18926 		       (line-beginning-position))))
  18927              ;; At the beginning of a blank line, do some preindentation.  This
  18928              ;; signals org-src--edit-element to preserve the indentation on exit
  18929              (when (and (looking-at-p "^[[:space:]]*$")
  18930                         (not org-src-preserve-indentation))
  18931                (let ((element (org-element-at-point))
  18932                      block-content-ind some-ind)
  18933                  (org-with-point-at (org-element-property :begin element)
  18934                    (setq block-content-ind (+ (org-current-text-indentation)
  18935                                               org-edit-src-content-indentation))
  18936                    (forward-line)
  18937 		   (save-match-data (re-search-forward "^[ \t]*\\S-" nil t))
  18938                    (backward-char)
  18939                    (setq some-ind (if (looking-at-p "#\\+end_src")
  18940                                       block-content-ind (org-current-text-indentation))))
  18941                  (indent-line-to (min block-content-ind some-ind))))
  18942 	     (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
  18943 	    (t
  18944 	     (let ((column (org--get-expected-indentation element nil)))
  18945 	       ;; Preserve current column.
  18946 	       (if (<= (current-column) (current-indentation))
  18947 		   (indent-line-to column)
  18948 		 (save-excursion (indent-line-to column))))
  18949 	     ;; Align node property.  Also preserve current column.
  18950 	     (when (eq type 'node-property)
  18951 	       (let ((column (current-column)))
  18952 		 (org--align-node-property)
  18953 		 (org-move-to-column column))))))))
  18954 
  18955 (defun org-indent-region (start end)
  18956   "Indent each non-blank line in the region.
  18957 Called from a program, START and END specify the region to
  18958 indent.  The function will not indent contents of example blocks,
  18959 verse blocks and export blocks as leading white spaces are
  18960 assumed to be significant there."
  18961   (interactive "r")
  18962   (save-excursion
  18963     (goto-char start)
  18964     (skip-chars-forward " \r\t\n")
  18965     (unless (eobp) (beginning-of-line))
  18966     (let ((indent-to
  18967 	   (lambda (ind pos)
  18968 	     ;; Set IND as indentation for all lines between point and
  18969 	     ;; POS.  Blank lines are ignored.  Leave point after POS
  18970 	     ;; once done.
  18971 	     (let ((limit (copy-marker pos)))
  18972 	       (while (< (point) limit)
  18973 		 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
  18974 		 (forward-line))
  18975 	       (set-marker limit nil))))
  18976 	  (end (copy-marker end)))
  18977       (while (< (point) end)
  18978 	(if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
  18979 	  (let* ((element (org-element-at-point))
  18980 		 (type (org-element-type element))
  18981 		 (element-end (copy-marker (org-element-property :end element)))
  18982 		 (ind (org--get-expected-indentation element nil)))
  18983 	    (cond
  18984 	     ;; Element indented as a single block.  Example blocks
  18985 	     ;; preserving indentation are a special case since the
  18986 	     ;; "contents" must not be indented whereas the block
  18987 	     ;; boundaries can.
  18988 	     ((or (memq type '(export-block latex-environment))
  18989 		  (and (eq type 'example-block)
  18990 		       (not
  18991 			(or org-src-preserve-indentation
  18992 			    (org-element-property :preserve-indent element)))))
  18993 	      (let ((offset (- ind (current-indentation))))
  18994 		(unless (zerop offset)
  18995 		  (indent-rigidly (org-element-property :begin element)
  18996 				  (org-element-property :end element)
  18997 				  offset)))
  18998 	      (goto-char element-end))
  18999 	     ;; Elements indented line wise.  Be sure to exclude
  19000 	     ;; example blocks (preserving indentation) and source
  19001 	     ;; blocks from this category as they are treated
  19002 	     ;; specially later.
  19003 	     ((or (memq type '(paragraph table table-row))
  19004 		  (not (or (org-element-property :contents-begin element)
  19005 			   (memq type '(example-block src-block)))))
  19006 	      (when (eq type 'node-property)
  19007 		(org--align-node-property)
  19008 		(beginning-of-line))
  19009 	      (funcall indent-to ind (min element-end end)))
  19010 	     ;; Elements consisting of three parts: before the
  19011 	     ;; contents, the contents, and after the contents.  The
  19012 	     ;; contents are treated specially, according to the
  19013 	     ;; element type, or not indented at all.  Other parts are
  19014 	     ;; indented as a single block.
  19015 	     (t
  19016 	      (let* ((post (copy-marker
  19017 			    (org-element-property :post-affiliated element)))
  19018 		     (cbeg
  19019 		      (copy-marker
  19020 		       (cond
  19021 			((not (org-element-property :contents-begin element))
  19022 			 ;; Fake contents for source blocks.
  19023 			 (org-with-wide-buffer
  19024 			  (goto-char post)
  19025 			  (line-beginning-position 2)))
  19026 			((memq type '(footnote-definition item plain-list))
  19027 			 ;; Contents in these elements could start on
  19028 			 ;; the same line as the beginning of the
  19029 			 ;; element.  Make sure we start indenting
  19030 			 ;; from the second line.
  19031 			 (org-with-wide-buffer
  19032 			  (goto-char post)
  19033 			  (end-of-line)
  19034 			  (skip-chars-forward " \r\t\n")
  19035 			  (if (eobp) (point) (line-beginning-position))))
  19036 			(t (org-element-property :contents-begin element)))))
  19037 		     (cend (copy-marker
  19038 			    (or (org-element-property :contents-end element)
  19039 				;; Fake contents for source blocks.
  19040 				(org-with-wide-buffer
  19041 				 (goto-char element-end)
  19042 				 (skip-chars-backward " \r\t\n")
  19043 				 (line-beginning-position)))
  19044 			    t)))
  19045 		;; Do not change items indentation individually as it
  19046 		;; might break the list as a whole.  On the other
  19047 		;; hand, when at a plain list, indent it as a whole.
  19048 		(cond ((eq type 'plain-list)
  19049 		       (let ((offset (- ind (org-current-text-indentation))))
  19050 			 (unless (zerop offset)
  19051 			   (indent-rigidly (org-element-property :begin element)
  19052 					   (org-element-property :end element)
  19053 					   offset))
  19054 			 (goto-char cbeg)))
  19055 		      ((eq type 'item) (goto-char cbeg))
  19056 		      (t (funcall indent-to ind (min cbeg end))))
  19057 		(when (< (point) end)
  19058 		  (cl-case type
  19059 		    ((example-block verse-block))
  19060 		    (src-block
  19061 		     ;; In a source block, indent source code
  19062 		     ;; according to language major mode, but only if
  19063 		     ;; `org-src-tab-acts-natively' is non-nil.
  19064 		     (when (and (< (point) end) org-src-tab-acts-natively)
  19065 		       (ignore-errors
  19066 			 (org-babel-do-in-edit-buffer
  19067 			  (indent-region (point-min) (point-max))))))
  19068 		    (t (org-indent-region (point) (min cend end))))
  19069 		  (goto-char (min cend end))
  19070 		  (when (< (point) end)
  19071 		    (funcall indent-to ind (min element-end end))))
  19072 		(set-marker post nil)
  19073 		(set-marker cbeg nil)
  19074 		(set-marker cend nil))))
  19075 	    (set-marker element-end nil))))
  19076       (set-marker end nil))))
  19077 
  19078 (defun org-indent-drawer ()
  19079   "Indent the drawer at point."
  19080   (interactive)
  19081   (unless (save-excursion
  19082 	    (beginning-of-line)
  19083 	    (looking-at-p org-drawer-regexp))
  19084     (user-error "Not at a drawer"))
  19085   (let ((element (org-element-at-point-no-context)))
  19086     (unless (memq (org-element-type element) '(drawer property-drawer))
  19087       (user-error "Not at a drawer"))
  19088     (org-with-wide-buffer
  19089      (org-indent-region (org-element-property :begin element)
  19090 			(org-element-property :end element))))
  19091   (message "Drawer at point indented"))
  19092 
  19093 (defun org-indent-block ()
  19094   "Indent the block at point."
  19095   (interactive)
  19096   (unless (save-excursion
  19097 	    (beginning-of-line)
  19098 	    (let ((case-fold-search t))
  19099 	      (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
  19100     (user-error "Not at a block"))
  19101   (let ((element (org-element-at-point-no-context)))
  19102     (unless (memq (org-element-type element)
  19103 		  '(comment-block center-block dynamic-block example-block
  19104 				  export-block quote-block special-block
  19105 				  src-block verse-block))
  19106       (user-error "Not at a block"))
  19107     (org-with-wide-buffer
  19108      (org-indent-region (org-element-property :begin element)
  19109 			(org-element-property :end element))))
  19110   (message "Block at point indented"))
  19111 
  19112 
  19113 ;;; Filling
  19114 
  19115 ;; We use our own fill-paragraph and auto-fill functions.
  19116 
  19117 ;; `org-fill-paragraph' relies on adaptive filling and context
  19118 ;; checking.  Appropriate `fill-prefix' is computed with
  19119 ;; `org-adaptive-fill-function'.
  19120 
  19121 ;; `org-auto-fill-function' takes care of auto-filling.  It calls
  19122 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
  19123 ;; `org-adaptive-fill-function' value.  Internally,
  19124 ;; `org-comment-line-break-function' breaks the line.
  19125 
  19126 ;; `org-setup-filling' installs filling and auto-filling related
  19127 ;; variables during `org-mode' initialization.
  19128 
  19129 (defvar org--single-lines-list-is-paragraph) ; defined later
  19130 
  19131 (defun org-setup-filling ()
  19132   (require 'org-element)
  19133   ;; Prevent auto-fill from inserting unwanted new items.
  19134   (setq-local fill-nobreak-predicate
  19135               (org-uniquify
  19136                (append fill-nobreak-predicate
  19137                        '(org-fill-line-break-nobreak-p
  19138                          org-fill-n-macro-as-item-nobreak-p
  19139                          org-fill-paragraph-with-timestamp-nobreak-p))))
  19140   (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
  19141     (setq-local paragraph-start paragraph-ending)
  19142     (setq-local paragraph-separate paragraph-ending))
  19143   (setq-local fill-paragraph-function 'org-fill-paragraph)
  19144   (setq-local fill-forward-paragraph-function
  19145               (lambda (&optional arg)
  19146                 (let ((org--single-lines-list-is-paragraph nil))
  19147                   (org-forward-paragraph arg))))
  19148   (setq-local auto-fill-inhibit-regexp nil)
  19149   (setq-local adaptive-fill-function 'org-adaptive-fill-function)
  19150   (setq-local normal-auto-fill-function 'org-auto-fill-function)
  19151   (setq-local comment-line-break-function 'org-comment-line-break-function))
  19152 
  19153 (defun org-fill-line-break-nobreak-p ()
  19154   "Non-nil when a new line at point would create an Org line break."
  19155   (save-excursion
  19156     (skip-chars-backward " \t")
  19157     (skip-chars-backward "\\\\")
  19158     (looking-at "\\\\\\\\\\($\\|[^\\]\\)")))
  19159 
  19160 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
  19161   "Non-nil when a new line at point would split a timestamp."
  19162   (and (org-at-timestamp-p 'lax)
  19163        (not (looking-at org-ts-regexp-both))))
  19164 
  19165 (defun org-fill-n-macro-as-item-nobreak-p ()
  19166   "Non-nil when a new line at point would create a new list."
  19167   ;; During export, a "n" macro followed by a dot or a closing
  19168   ;; parenthesis can end up being parsed as a new list item.
  19169   (looking-at-p "[ \t]*{{{n\\(?:([^\n)]*)\\)?}}}[.)]\\(?:$\\| \\)"))
  19170 
  19171 (defun org-adaptive-fill-function ()
  19172   "Compute a fill prefix for the current line.
  19173 Return fill prefix, as a string, or nil if current line isn't
  19174 meant to be filled.  For convenience, if `adaptive-fill-regexp'
  19175 matches in paragraphs or comments, use it."
  19176   (org-with-wide-buffer
  19177    (unless (org-at-heading-p)
  19178      (let* ((p (line-beginning-position))
  19179 	    (element (save-excursion
  19180 		       (beginning-of-line)
  19181 		       (org-element-at-point)))
  19182 	    (type (org-element-type element))
  19183 	    (post-affiliated (org-element-property :post-affiliated element)))
  19184        (unless (< p post-affiliated)
  19185 	 (cl-case type
  19186 	   (comment
  19187 	    (save-excursion
  19188 	      (beginning-of-line)
  19189 	      (looking-at "[ \t]*")
  19190 	      (concat (match-string 0) "# ")))
  19191 	   (footnote-definition "")
  19192 	   ((item plain-list)
  19193 	    (make-string (org-list-item-body-column post-affiliated) ?\s))
  19194 	   (paragraph
  19195 	    ;; Fill prefix is usually the same as the current line,
  19196 	    ;; unless the paragraph is at the beginning of an item.
  19197 	    (let ((parent (org-element-property :parent element)))
  19198 	      (save-excursion
  19199 		(beginning-of-line)
  19200 		(cond ((eq (org-element-type parent) 'item)
  19201 		       (make-string (org-list-item-body-column
  19202 				     (org-element-property :begin parent))
  19203 				    ?\s))
  19204 		      ((and adaptive-fill-regexp
  19205 			    ;; Locally disable
  19206 			    ;; `adaptive-fill-function' to let
  19207 			    ;; `fill-context-prefix' handle
  19208 			    ;; `adaptive-fill-regexp' variable.
  19209 			    (let (adaptive-fill-function)
  19210 			      (fill-context-prefix
  19211 			       post-affiliated
  19212 			       (org-element-property :end element)))))
  19213 		      ((looking-at "[ \t]+") (match-string 0))
  19214 		      (t  "")))))
  19215 	   (comment-block
  19216 	    ;; Only fill contents if P is within block boundaries.
  19217 	    (let* ((cbeg (save-excursion (goto-char post-affiliated)
  19218 					 (forward-line)
  19219 					 (point)))
  19220 		   (cend (save-excursion
  19221 			   (goto-char (org-element-property :end element))
  19222 			   (skip-chars-backward " \r\t\n")
  19223 			   (line-beginning-position))))
  19224 	      (when (and (>= p cbeg) (< p cend))
  19225 		(if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
  19226 		    (match-string 0)
  19227 		  ""))))))))))
  19228 
  19229 (defun org-fill-element (&optional justify)
  19230   "Fill element at point, when applicable.
  19231 
  19232 This function only applies to comment blocks, comments, example
  19233 blocks and paragraphs.  Also, as a special case, re-align table
  19234 when point is at one.
  19235 
  19236 If JUSTIFY is non-nil (interactively, with prefix argument),
  19237 justify as well.  If `sentence-end-double-space' is non-nil, then
  19238 period followed by one space does not end a sentence, so don't
  19239 break a line there.  The variable `fill-column' controls the
  19240 width for filling.
  19241 
  19242 For convenience, when point is at a plain list, an item or
  19243 a footnote definition, try to fill the first paragraph within."
  19244   (with-syntax-table org-mode-transpose-word-syntax-table
  19245     ;; Move to end of line in order to get the first paragraph within
  19246     ;; a plain list or a footnote definition.
  19247     (let ((element (save-excursion (end-of-line) (org-element-at-point))))
  19248       ;; First check if point is in a blank line at the beginning of
  19249       ;; the buffer.  In that case, ignore filling.
  19250       (cl-case (org-element-type element)
  19251 	;; Use major mode filling function is source blocks.
  19252         (src-block
  19253          (let ((regionp (region-active-p)))
  19254            (org-babel-do-in-edit-buffer
  19255             ;; `org-babel-do-in-edit-buffer' will preserve region if it
  19256             ;; is within src block contents.  Otherwise, the region
  19257             ;; crosses src block boundaries.  We re-fill the whole src
  19258             ;; block in such scenario.
  19259             (when (and regionp (not (region-active-p)))
  19260               (push-mark (point-min))
  19261               (goto-char (point-max))
  19262               (setq mark-active t))
  19263             (funcall-interactively #'fill-paragraph justify 'region))))
  19264 	;; Align Org tables, leave table.el tables as-is.
  19265 	(table-row (org-table-align) t)
  19266 	(table
  19267 	 (when (eq (org-element-property :type element) 'org)
  19268 	   (save-excursion
  19269 	     (goto-char (org-element-property :post-affiliated element))
  19270 	     (org-table-align)))
  19271 	 t)
  19272 	(paragraph
  19273 	 ;; Paragraphs may contain `line-break' type objects.
  19274 	 (let ((beg (max (point-min)
  19275 			 (org-element-property :contents-begin element)))
  19276 	       (end (min (point-max)
  19277 			 (org-element-property :contents-end element))))
  19278 	   ;; Do nothing if point is at an affiliated keyword.
  19279 	   (if (< (line-end-position) beg) t
  19280 	     ;; Fill paragraph, taking line breaks into account.
  19281 	     (save-excursion
  19282 	       (goto-char beg)
  19283 	       (let ((cuts (list beg)))
  19284 		 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
  19285 		   (when (eq 'line-break
  19286 			     (org-element-type
  19287 			      (save-excursion (backward-char)
  19288 					      (org-element-context))))
  19289 		     (push (point) cuts)))
  19290 		 (dolist (c (delq end cuts))
  19291 		   (fill-region-as-paragraph c end justify)
  19292 		   (setq end c))))
  19293 	     t)))
  19294 	;; Contents of `comment-block' type elements should be
  19295 	;; filled as plain text, but only if point is within block
  19296 	;; markers.
  19297 	(comment-block
  19298 	 (let* ((case-fold-search t)
  19299 		(beg (save-excursion
  19300 		       (goto-char (org-element-property :begin element))
  19301 		       (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
  19302 		       (forward-line)
  19303 		       (point)))
  19304 		(end (save-excursion
  19305 		       (goto-char (org-element-property :end element))
  19306 		       (re-search-backward "^[ \t]*#\\+end_comment" nil t)
  19307 		       (line-beginning-position))))
  19308 	   (if (or (< (point) beg) (> (point) end)) t
  19309 	     (fill-region-as-paragraph
  19310 	      (save-excursion (end-of-line)
  19311 			      (re-search-backward "^[ \t]*$" beg 'move)
  19312 			      (line-beginning-position))
  19313 	      (save-excursion (beginning-of-line)
  19314 			      (re-search-forward "^[ \t]*$" end 'move)
  19315 			      (line-beginning-position))
  19316 	      justify))))
  19317 	;; Fill comments.
  19318 	(comment
  19319 	 (let ((begin (org-element-property :post-affiliated element))
  19320 	       (end (org-element-property :end element)))
  19321 	   (when (and (>= (point) begin) (<= (point) end))
  19322 	     (let ((begin (save-excursion
  19323 			    (end-of-line)
  19324 			    (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
  19325 				(progn (forward-line) (point))
  19326 			      begin)))
  19327 		   (end (save-excursion
  19328 			  (end-of-line)
  19329 			  (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
  19330 			      (1- (line-beginning-position))
  19331 			    (skip-chars-backward " \r\t\n")
  19332 			    (line-end-position)))))
  19333 	       ;; Do not fill comments when at a blank line.
  19334 	       (when (> end begin)
  19335 		 (let ((fill-prefix
  19336 			(save-excursion
  19337 			  (beginning-of-line)
  19338 			  (looking-at "[ \t]*#")
  19339 			  (let ((comment-prefix (match-string 0)))
  19340 			    (goto-char (match-end 0))
  19341 			    (if (looking-at adaptive-fill-regexp)
  19342 				(concat comment-prefix (match-string 0))
  19343 			      (concat comment-prefix " "))))))
  19344 		   (save-excursion
  19345 		     (fill-region-as-paragraph begin end justify))))))
  19346 	   t))
  19347 	;; Ignore every other element.
  19348 	(otherwise t)))))
  19349 
  19350 (defun org-fill-paragraph (&optional justify region)
  19351   "Fill element at point, when applicable.
  19352 
  19353 This function only applies to comment blocks, comments, example
  19354 blocks and paragraphs.  Also, as a special case, re-align table
  19355 when point is at one.
  19356 
  19357 For convenience, when point is at a plain list, an item or
  19358 a footnote definition, try to fill the first paragraph within.
  19359 
  19360 If JUSTIFY is non-nil (interactively, with prefix argument),
  19361 justify as well.  If `sentence-end-double-space' is non-nil, then
  19362 period followed by one space does not end a sentence, so don't
  19363 break a line there.  The variable `fill-column' controls the
  19364 width for filling.
  19365 
  19366 The REGION argument is non-nil if called interactively; in that
  19367 case, if Transient Mark mode is enabled and the mark is active,
  19368 fill each of the elements in the active region, instead of just
  19369 filling the current element."
  19370   (interactive (progn
  19371 		 (barf-if-buffer-read-only)
  19372 		 (list (when current-prefix-arg 'full) t)))
  19373   (let ((hash (and (not (buffer-modified-p))
  19374 		   (org-buffer-hash))))
  19375     (cond
  19376      ((and region transient-mark-mode mark-active
  19377 	   (not (eq (region-beginning) (region-end))))
  19378       (let ((origin (point-marker))
  19379 	    (start (region-beginning)))
  19380 	(unwind-protect
  19381 	    (progn
  19382 	      (goto-char (region-end))
  19383 	      (skip-chars-backward " \t\n")
  19384 	      (let ((org--single-lines-list-is-paragraph nil))
  19385                 (while (> (point) start)
  19386 		  (org-fill-element justify)
  19387 		  (org-backward-paragraph)
  19388                   (skip-chars-backward " \t\n"))))
  19389 	  (goto-char origin)
  19390 	  (set-marker origin nil))))
  19391      (t
  19392       (save-excursion
  19393 	(when (org-match-line "[ \t]*$")
  19394 	  (skip-chars-forward " \t\n"))
  19395 	(org-fill-element justify))))
  19396     ;; If we didn't change anything in the buffer (and the buffer was
  19397     ;; previously unmodified), then flip the modification status back
  19398     ;; to "unchanged".
  19399     (when (and hash (equal hash (org-buffer-hash)))
  19400       (set-buffer-modified-p nil))
  19401     ;; Return non-nil.
  19402     t))
  19403 
  19404 (defun org-auto-fill-function ()
  19405   "Auto-fill function."
  19406   ;; Check if auto-filling is meaningful.
  19407   (let ((fc (current-fill-column)))
  19408     (when (and fc (> (current-column) fc))
  19409       (let* ((fill-prefix (org-adaptive-fill-function))
  19410 	     ;; Enforce empty fill prefix, if required.  Otherwise, it
  19411 	     ;; will be computed again.
  19412 	     (adaptive-fill-mode (not (equal fill-prefix ""))))
  19413 	(when fill-prefix (do-auto-fill))))))
  19414 
  19415 (defun org-comment-line-break-function (&optional soft)
  19416   "Break line at point and indent, continuing comment if within one.
  19417 The inserted newline is marked hard if variable
  19418 `use-hard-newlines' is true, unless optional argument SOFT is
  19419 non-nil.
  19420 
  19421 This function is a simplified version of `comment-indent-new-line'
  19422 that bypasses the complex Emacs machinery dealing with comments.
  19423 We instead rely on Org parser, utilizing `org-adaptive-fill-function'"
  19424   (let ((fill-prefix (org-adaptive-fill-function)))
  19425     (if soft (insert-and-inherit ?\n) (newline 1))
  19426     (save-excursion (forward-char -1) (delete-horizontal-space))
  19427     (delete-horizontal-space)
  19428     (indent-to-left-margin)
  19429     (when fill-prefix
  19430       (insert-before-markers-and-inherit fill-prefix))))
  19431 
  19432 
  19433 ;;; Fixed Width Areas
  19434 
  19435 (defun org-toggle-fixed-width ()
  19436   "Toggle fixed-width markup.
  19437 
  19438 Add or remove fixed-width markup on current line, whenever it
  19439 makes sense.  Return an error otherwise.
  19440 
  19441 If a region is active and if it contains only fixed-width areas
  19442 or blank lines, remove all fixed-width markup in it.  If the
  19443 region contains anything else, convert all non-fixed-width lines
  19444 to fixed-width ones.
  19445 
  19446 Blank lines at the end of the region are ignored unless the
  19447 region only contains such lines."
  19448   (interactive)
  19449   (if (not (org-region-active-p))
  19450       ;; No region:
  19451       ;;
  19452       ;; Remove fixed width marker only in a fixed-with element.
  19453       ;;
  19454       ;; Add fixed width maker in paragraphs, in blank lines after
  19455       ;; elements or at the beginning of a headline or an inlinetask,
  19456       ;; and before any one-line elements (e.g., a clock).
  19457       (progn
  19458         (beginning-of-line)
  19459         (let* ((element (org-element-at-point))
  19460                (type (org-element-type element)))
  19461           (cond
  19462            ((and (eq type 'fixed-width)
  19463                  (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
  19464             (replace-match
  19465 	     "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
  19466            ((and (memq type '(babel-call clock comment diary-sexp headline
  19467 					 horizontal-rule keyword paragraph
  19468 					 planning))
  19469 		 (<= (org-element-property :post-affiliated element) (point)))
  19470             (skip-chars-forward " \t")
  19471             (insert ": "))
  19472            ((and (looking-at-p "[ \t]*$")
  19473                  (or (eq type 'inlinetask)
  19474                      (save-excursion
  19475                        (skip-chars-forward " \r\t\n")
  19476                        (<= (org-element-property :end element) (point)))))
  19477             (delete-region (point) (line-end-position))
  19478             (org-indent-line)
  19479             (insert ": "))
  19480            (t (user-error "Cannot insert a fixed-width line here")))))
  19481     ;; Region active.
  19482     (let* ((begin (save-excursion
  19483                     (goto-char (region-beginning))
  19484                     (line-beginning-position)))
  19485            (end (copy-marker
  19486                  (save-excursion
  19487                    (goto-char (region-end))
  19488                    (unless (eolp) (beginning-of-line))
  19489                    (if (save-excursion (re-search-backward "\\S-" begin t))
  19490                        (progn (skip-chars-backward " \r\t\n") (point))
  19491                      (point)))))
  19492            (all-fixed-width-p
  19493             (catch 'not-all-p
  19494               (save-excursion
  19495                 (goto-char begin)
  19496                 (skip-chars-forward " \r\t\n")
  19497                 (when (eobp) (throw 'not-all-p nil))
  19498                 (while (< (point) end)
  19499                   (let ((element (org-element-at-point)))
  19500                     (if (eq (org-element-type element) 'fixed-width)
  19501                         (goto-char (org-element-property :end element))
  19502                       (throw 'not-all-p nil))))
  19503                 t))))
  19504       (if all-fixed-width-p
  19505           (save-excursion
  19506             (goto-char begin)
  19507             (while (< (point) end)
  19508               (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
  19509                 (replace-match
  19510                  "" nil nil nil
  19511                  (if (= (line-end-position) (match-end 0)) 0 1)))
  19512               (forward-line)))
  19513         (let ((min-ind (point-max)))
  19514           ;; Find minimum indentation across all lines.
  19515           (save-excursion
  19516             (goto-char begin)
  19517             (if (not (save-excursion (re-search-forward "\\S-" end t)))
  19518                 (setq min-ind 0)
  19519               (catch 'zerop
  19520                 (while (< (point) end)
  19521                   (unless (looking-at-p "[ \t]*$")
  19522                     (let ((ind (org-current-text-indentation)))
  19523                       (setq min-ind (min min-ind ind))
  19524                       (when (zerop ind) (throw 'zerop t))))
  19525                   (forward-line)))))
  19526           ;; Loop over all lines and add fixed-width markup everywhere
  19527           ;; but in fixed-width lines.
  19528           (save-excursion
  19529             (goto-char begin)
  19530             (while (< (point) end)
  19531               (cond
  19532                ((org-at-heading-p)
  19533                 (insert ": ")
  19534                 (forward-line)
  19535                 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
  19536                   (insert ":")
  19537                   (forward-line)))
  19538                ((looking-at-p "[ \t]*:\\( \\|$\\)")
  19539                 (let* ((element (org-element-at-point))
  19540                        (element-end (org-element-property :end element)))
  19541                   (if (eq (org-element-type element) 'fixed-width)
  19542                       (progn (goto-char element-end)
  19543                              (skip-chars-backward " \r\t\n")
  19544                              (forward-line))
  19545                     (let ((limit (min end element-end)))
  19546                       (while (< (point) limit)
  19547                         (org-move-to-column min-ind t)
  19548                         (insert ": ")
  19549                         (forward-line))))))
  19550                (t
  19551                 (org-move-to-column min-ind t)
  19552                 (insert ": ")
  19553                 (forward-line)))))))
  19554       (set-marker end nil))))
  19555 
  19556 
  19557 ;;; Blocks
  19558 
  19559 (defun org-block-map (function &optional start end)
  19560   "Call FUNCTION at the head of all source blocks in the current buffer.
  19561 Optional arguments START and END can be used to limit the range."
  19562   (let ((start (or start (point-min)))
  19563         (end (or end (point-max))))
  19564     (save-excursion
  19565       (goto-char start)
  19566       (while (and (< (point) end) (re-search-forward org-block-regexp end t))
  19567 	(save-excursion
  19568 	  (save-match-data
  19569             (goto-char (match-beginning 0))
  19570             (funcall function)))))))
  19571 
  19572 (defun org-next-block (arg &optional backward block-regexp)
  19573   "Jump to the next block.
  19574 
  19575 With a prefix argument ARG, jump forward ARG many blocks.
  19576 
  19577 When BACKWARD is non-nil, jump to the previous block.
  19578 
  19579 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
  19580 Match data is set according to this regexp when the function
  19581 returns.
  19582 
  19583 Return point at beginning of the opening line of found block.
  19584 Throw an error if no block is found."
  19585   (interactive "p")
  19586   (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
  19587 	(case-fold-search t)
  19588 	(search-fn (if backward #'re-search-backward #'re-search-forward))
  19589 	(count (or arg 1))
  19590 	(origin (point))
  19591 	last-element)
  19592     (if backward (beginning-of-line) (end-of-line))
  19593     (while (and (> count 0) (funcall search-fn re nil t))
  19594       (let ((element (save-excursion
  19595 		       (goto-char (match-beginning 0))
  19596 		       (save-match-data (org-element-at-point)))))
  19597 	(when (and (memq (org-element-type element)
  19598 			 '(center-block comment-block dynamic-block
  19599 					example-block export-block quote-block
  19600 					special-block src-block verse-block))
  19601 		   (<= (match-beginning 0)
  19602 		       (org-element-property :post-affiliated element)))
  19603 	  (setq last-element element)
  19604 	  (cl-decf count))))
  19605     (if (= count 0)
  19606 	(prog1 (goto-char (org-element-property :post-affiliated last-element))
  19607 	  (save-match-data (org-fold-show-context)))
  19608       (goto-char origin)
  19609       (user-error "No %s code blocks" (if backward "previous" "further")))))
  19610 
  19611 (defun org-previous-block (arg &optional block-regexp)
  19612   "Jump to the previous block.
  19613 With a prefix argument ARG, jump backward ARG many source blocks.
  19614 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
  19615   (interactive "p")
  19616   (org-next-block arg t block-regexp))
  19617 
  19618 
  19619 ;;; Comments
  19620 
  19621 ;; Org comments syntax is quite complex.  It requires the entire line
  19622 ;; to be just a comment.  Also, even with the right syntax at the
  19623 ;; beginning of line, some elements (e.g., verse-block or
  19624 ;; example-block) don't accept comments.  Usual Emacs comment commands
  19625 ;; cannot cope with those requirements.  Therefore, Org replaces them.
  19626 
  19627 ;; Org still relies on 'comment-dwim', but cannot trust
  19628 ;; 'comment-only-p'.  So, 'comment-region-function' and
  19629 ;; 'uncomment-region-function' both point
  19630 ;; to 'org-comment-or-uncomment-region'.  Eventually,
  19631 ;; 'org-insert-comment' takes care of insertion of comments at the
  19632 ;; beginning of line.
  19633 
  19634 ;; 'org-setup-comments-handling' install comments related variables
  19635 ;; during 'org-mode' initialization.
  19636 
  19637 (defun org-setup-comments-handling ()
  19638   (interactive)
  19639   (setq-local comment-use-syntax nil)
  19640   (setq-local comment-start "# ")
  19641   (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
  19642   (setq-local comment-insert-comment-function 'org-insert-comment)
  19643   (setq-local comment-region-function 'org-comment-or-uncomment-region)
  19644   (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
  19645 
  19646 (defun org-insert-comment ()
  19647   "Insert an empty comment above current line.
  19648 If the line is empty, insert comment at its beginning.  When
  19649 point is within a source block, comment according to the related
  19650 major mode."
  19651   (if (let ((element (org-element-at-point)))
  19652 	(and (eq (org-element-type element) 'src-block)
  19653 	     (< (save-excursion
  19654 		  (goto-char (org-element-property :post-affiliated element))
  19655 		  (line-end-position))
  19656 		(point))
  19657 	     (> (save-excursion
  19658 		  (goto-char (org-element-property :end element))
  19659 		  (skip-chars-backward " \r\t\n")
  19660 		  (line-beginning-position))
  19661 		(point))))
  19662       (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
  19663     (beginning-of-line)
  19664     (if (looking-at "\\s-*$") (delete-region (point) (line-end-position))
  19665       (open-line 1))
  19666     (org-indent-line)
  19667     (insert "# ")))
  19668 
  19669 (defvar comment-empty-lines)		; From newcomment.el.
  19670 (defun org-comment-or-uncomment-region (beg end &rest _)
  19671   "Comment or uncomment each non-blank line in the region.
  19672 Uncomment each non-blank line between BEG and END if it only
  19673 contains commented lines.  Otherwise, comment them.  If region is
  19674 strictly within a source block, use appropriate comment syntax."
  19675   (if (let ((element (org-element-at-point)))
  19676 	(and (eq (org-element-type element) 'src-block)
  19677 	     (< (save-excursion
  19678 		  (goto-char (org-element-property :post-affiliated element))
  19679 		  (line-end-position))
  19680 		beg)
  19681 	     (>= (save-excursion
  19682 		  (goto-char (org-element-property :end element))
  19683 		  (skip-chars-backward " \r\t\n")
  19684 		  (line-beginning-position))
  19685 		end)))
  19686       ;; Translate region boundaries for the Org buffer to the source
  19687       ;; buffer.
  19688       (let ((offset (- end beg)))
  19689 	(save-excursion
  19690 	  (goto-char beg)
  19691 	  (org-babel-do-in-edit-buffer
  19692 	   (comment-or-uncomment-region (point) (+ offset (point))))))
  19693     (save-restriction
  19694       ;; Restrict region
  19695       (narrow-to-region (save-excursion (goto-char beg)
  19696 					(skip-chars-forward " \r\t\n" end)
  19697 					(line-beginning-position))
  19698 			(save-excursion (goto-char end)
  19699 					(skip-chars-backward " \r\t\n" beg)
  19700 					(line-end-position)))
  19701       (let ((uncommentp
  19702 	     ;; UNCOMMENTP is non-nil when every non blank line between
  19703 	     ;; BEG and END is a comment.
  19704 	     (save-excursion
  19705 	       (goto-char (point-min))
  19706 	       (while (and (not (eobp))
  19707 			   (let ((element (org-element-at-point)))
  19708 			     (and (eq (org-element-type element) 'comment)
  19709 				  (goto-char (min (point-max)
  19710 						  (org-element-property
  19711 						   :end element)))))))
  19712 	       (eobp))))
  19713 	(if uncommentp
  19714 	    ;; Only blank lines and comments in region: uncomment it.
  19715 	    (save-excursion
  19716 	      (goto-char (point-min))
  19717 	      (while (not (eobp))
  19718 		(when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
  19719 		  (replace-match "" nil nil nil 1))
  19720 		(forward-line)))
  19721 	  ;; Comment each line in region.
  19722 	  (let ((min-indent (point-max)))
  19723 	    ;; First find the minimum indentation across all lines.
  19724 	    (save-excursion
  19725 	      (goto-char (point-min))
  19726 	      (while (and (not (eobp)) (not (zerop min-indent)))
  19727 		(unless (looking-at "[ \t]*$")
  19728 		  (setq min-indent (min min-indent (org-current-text-indentation))))
  19729 		(forward-line)))
  19730 	    ;; Then loop over all lines.
  19731 	    (save-excursion
  19732 	      (goto-char (point-min))
  19733 	      (while (not (eobp))
  19734 		(unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
  19735 		  ;; Don't get fooled by invisible text (e.g. link path)
  19736 		  ;; when moving to column MIN-INDENT.
  19737 		  (let ((buffer-invisibility-spec nil))
  19738 		    (org-move-to-column min-indent t))
  19739 		  (insert comment-start))
  19740 		(forward-line)))))))))
  19741 
  19742 (defun org-comment-dwim (_arg)
  19743   "Call the comment command you mean.
  19744 Call `org-toggle-comment' if on a heading, otherwise call
  19745 `comment-dwim', within a source edit buffer if needed."
  19746   (interactive "*P")
  19747   (cond ((org-at-heading-p)
  19748 	 (call-interactively #'org-toggle-comment))
  19749 	((org-in-src-block-p)
  19750 	 (org-babel-do-in-edit-buffer (call-interactively #'comment-dwim)))
  19751 	(t (call-interactively #'comment-dwim))))
  19752 
  19753 
  19754 ;;; Timestamps API
  19755 
  19756 ;; This section contains tools to operate on, or create, timestamp
  19757 ;; objects, as returned by, e.g. `org-element-context'.
  19758 
  19759 (defun org-timestamp-from-string (s)
  19760   "Convert Org timestamp S, as a string, into a timestamp object.
  19761 Return nil if S is not a valid timestamp string."
  19762   (when (org-string-nw-p s)
  19763     (with-temp-buffer
  19764       (save-excursion (insert s))
  19765       (org-element-timestamp-parser))))
  19766 
  19767 (defun org-timestamp-from-time (time &optional with-time inactive)
  19768   "Convert a time value into a timestamp object.
  19769 
  19770 TIME is an Emacs internal time representation, as returned, e.g.,
  19771 by `current-time'.
  19772 
  19773 When optional argument WITH-TIME is non-nil, return a timestamp
  19774 object with a time part, i.e., with hours and minutes.
  19775 
  19776 Return an inactive timestamp if INACTIVE is non-nil.  Otherwise,
  19777 return an active timestamp."
  19778   (pcase-let ((`(,_ ,minute ,hour ,day ,month ,year . ,_) (decode-time time)))
  19779     (org-element-create 'timestamp
  19780 			(list :type (if inactive 'inactive 'active)
  19781 			      :year-start year
  19782 			      :month-start month
  19783 			      :day-start day
  19784 			      :hour-start (and with-time hour)
  19785 			      :minute-start (and with-time minute)))))
  19786 
  19787 (defun org-timestamp-to-time (timestamp &optional end)
  19788   "Convert TIMESTAMP object into an Emacs internal time value.
  19789 Use end of date range or time range when END is non-nil.
  19790 Otherwise, use its start."
  19791   (org-encode-time
  19792    (append '(0)
  19793            (mapcar
  19794             (lambda (prop) (or (org-element-property prop timestamp) 0))
  19795             (if end '(:minute-end :hour-end :day-end :month-end :year-end)
  19796               '(:minute-start :hour-start :day-start :month-start
  19797                               :year-start)))
  19798            '(nil -1 nil))))
  19799 
  19800 (defun org-timestamp-has-time-p (timestamp)
  19801   "Non-nil when TIMESTAMP has a time specified."
  19802   (org-element-property :hour-start timestamp))
  19803 
  19804 (defun org-format-timestamp (timestamp format &optional end utc)
  19805   "Format a TIMESTAMP object into a string.
  19806 
  19807 FORMAT is a format specifier to be passed to
  19808 `format-time-string'.
  19809 
  19810 When optional argument END is non-nil, use end of date-range or
  19811 time-range, if possible.
  19812 
  19813 When optional argument UTC is non-nil, time is be expressed as
  19814 Universal Time."
  19815   (format-time-string format (org-timestamp-to-time timestamp end)
  19816 		      (and utc t)))
  19817 
  19818 (defun org-timestamp-split-range (timestamp &optional end)
  19819   "Extract a TIMESTAMP object from a date or time range.
  19820 
  19821 END, when non-nil, means extract the end of the range.
  19822 Otherwise, extract its start.
  19823 
  19824 Return a new timestamp object."
  19825   (let ((type (org-element-property :type timestamp)))
  19826     (if (memq type '(active inactive diary)) timestamp
  19827       (let ((split-ts (org-element-copy timestamp)))
  19828 	;; Set new type.
  19829 	(org-element-put-property
  19830 	 split-ts :type (if (eq type 'active-range) 'active 'inactive))
  19831 	;; Copy start properties over end properties if END is
  19832 	;; non-nil.  Otherwise, copy end properties over `start' ones.
  19833 	(let ((p-alist '((:minute-start . :minute-end)
  19834 			 (:hour-start . :hour-end)
  19835 			 (:day-start . :day-end)
  19836 			 (:month-start . :month-end)
  19837 			 (:year-start . :year-end))))
  19838 	  (dolist (p-cell p-alist)
  19839 	    (org-element-put-property
  19840 	     split-ts
  19841 	     (funcall (if end #'car #'cdr) p-cell)
  19842 	     (org-element-property
  19843 	      (funcall (if end #'cdr #'car) p-cell) split-ts)))
  19844 	  ;; Eventually refresh `:raw-value'.
  19845 	  (org-element-put-property split-ts :raw-value nil)
  19846 	  (org-element-put-property
  19847 	   split-ts :raw-value (org-element-interpret-data split-ts)))))))
  19848 
  19849 (defun org-timestamp-translate (timestamp &optional boundary)
  19850   "Translate TIMESTAMP object to custom format.
  19851 
  19852 Format string is defined in `org-time-stamp-custom-formats',
  19853 which see.
  19854 
  19855 When optional argument BOUNDARY is non-nil, it is either the
  19856 symbol `start' or `end'.  In this case, only translate the
  19857 starting or ending part of TIMESTAMP if it is a date or time
  19858 range.  Otherwise, translate both parts.
  19859 
  19860 Return timestamp as-is if `org-display-custom-times' is nil or if
  19861 it has a `diary' type."
  19862   (let ((type (org-element-property :type timestamp)))
  19863     (if (or (not org-display-custom-times) (eq type 'diary))
  19864 	(org-element-interpret-data timestamp)
  19865       (let ((fmt (org-time-stamp-format
  19866                   (org-timestamp-has-time-p timestamp) nil 'custom)))
  19867 	(if (and (not boundary) (memq type '(active-range inactive-range)))
  19868 	    (concat (org-format-timestamp timestamp fmt)
  19869 		    "--"
  19870 		    (org-format-timestamp timestamp fmt t))
  19871 	  (org-format-timestamp timestamp fmt (eq boundary 'end)))))))
  19872 
  19873 ;;; Other stuff
  19874 
  19875 (defvar reftex-docstruct-symbol)
  19876 (defvar org--rds)
  19877 
  19878 (defun org-reftex-citation ()
  19879   "Use `reftex-citation' to insert a citation into the buffer.
  19880 This looks for a line like
  19881 
  19882 #+BIBLIOGRAPHY: foo plain option:-d
  19883 
  19884 and derives from it that foo.bib is the bibliography file relevant
  19885 for this document.  It then installs the necessary environment for RefTeX
  19886 to work in this buffer and calls `reftex-citation'  to insert a citation
  19887 into the buffer.
  19888 
  19889 Export of such citations to both LaTeX and HTML is handled by the contributed
  19890 package ox-bibtex by Taru Karttunen."
  19891   (interactive)
  19892   (let ((reftex-docstruct-symbol 'org--rds)
  19893 	org--rds bib)
  19894     (org-with-wide-buffer
  19895      (let ((case-fold-search t)
  19896 	   (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
  19897        (if (not (save-excursion
  19898 		  (or (re-search-forward re nil t)
  19899 		      (re-search-backward re nil t))))
  19900 	   (user-error "No bibliography defined in file")
  19901 	 (setq bib (concat (match-string 1) ".bib")
  19902 	       org--rds (list (list 'bib bib))))))
  19903     (call-interactively 'reftex-citation)))
  19904 
  19905 ;;;; Functions extending outline functionality
  19906 
  19907 (defun org-beginning-of-line (&optional n)
  19908   "Go to the beginning of the current visible line.
  19909 
  19910 If this is a headline, and `org-special-ctrl-a/e' is not nil or
  19911 symbol `reversed', on the first attempt move to where the
  19912 headline text starts, and only move to beginning of line when the
  19913 cursor is already before the start of the text of the headline.
  19914 
  19915 If `org-special-ctrl-a/e' is symbol `reversed' then go to the
  19916 start of the text on the second attempt.
  19917 
  19918 With argument N not nil or 1, move forward N - 1 lines first."
  19919   (interactive "^p")
  19920   (let ((origin (point))
  19921 	(special (pcase org-special-ctrl-a/e
  19922 		   (`(,C-a . ,_) C-a) (_ org-special-ctrl-a/e)))
  19923 	deactivate-mark)
  19924     ;; First move to a visible line.
  19925     (if (bound-and-true-p visual-line-mode)
  19926 	(beginning-of-visual-line n)
  19927       (move-beginning-of-line n)
  19928       ;; `move-beginning-of-line' may leave point after invisible
  19929       ;; characters if line starts with such of these (e.g., with
  19930       ;; a link at column 0).  Really move to the beginning of the
  19931       ;; current visible line.
  19932       (beginning-of-line))
  19933     (cond
  19934      ;; No special behavior.  Point is already at the beginning of
  19935      ;; a line, logical or visual.
  19936      ((not special))
  19937      ;; `beginning-of-visual-line' left point before logical beginning
  19938      ;; of line: point is at the beginning of a visual line.  Bail
  19939      ;; out.
  19940      ((and (bound-and-true-p visual-line-mode) (not (bolp))))
  19941      ((let ((case-fold-search nil)) (looking-at org-complex-heading-regexp))
  19942       ;; At a headline, special position is before the title, but
  19943       ;; after any TODO keyword or priority cookie.
  19944       (let ((refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
  19945 			 (line-end-position)))
  19946 	    (bol (point)))
  19947 	(if (eq special 'reversed)
  19948 	    (when (and (= origin bol) (eq last-command this-command))
  19949 	      (goto-char refpos))
  19950 	  (when (or (> origin refpos) (= origin bol))
  19951 	    (goto-char refpos)))))
  19952      ((and (looking-at org-list-full-item-re)
  19953 	   (memq (org-element-type (save-match-data (org-element-at-point)))
  19954 		 '(item plain-list)))
  19955       ;; Set special position at first white space character after
  19956       ;; bullet, and check-box, if any.
  19957       (let ((after-bullet
  19958 	     (let ((box (match-end 3)))
  19959 	       (cond ((not box) (match-end 1))
  19960 		     ((eq (char-after box) ?\s) (1+ box))
  19961 		     (t box)))))
  19962 	(if (eq special 'reversed)
  19963 	    (when (and (= (point) origin) (eq last-command this-command))
  19964 	      (goto-char after-bullet))
  19965 	  (when (or (> origin after-bullet) (= (point) origin))
  19966 	    (goto-char after-bullet)))))
  19967      ;; No special context.  Point is already at beginning of line.
  19968      (t nil))))
  19969 
  19970 (defun org-end-of-line (&optional n)
  19971   "Go to the end of the line, but before ellipsis, if any.
  19972 
  19973 If this is a headline, and `org-special-ctrl-a/e' is not nil or
  19974 symbol `reversed', ignore tags on the first attempt, and only
  19975 move to after the tags when the cursor is already beyond the end
  19976 of the headline.
  19977 
  19978 If `org-special-ctrl-a/e' is symbol `reversed' then ignore tags
  19979 on the second attempt.
  19980 
  19981 With argument N not nil or 1, move forward N - 1 lines first."
  19982   (interactive "^p")
  19983   (let ((origin (point))
  19984 	(special (pcase org-special-ctrl-a/e
  19985 		   (`(,_ . ,C-e) C-e) (_ org-special-ctrl-a/e)))
  19986 	deactivate-mark)
  19987     ;; First move to a visible line.
  19988     (if (bound-and-true-p visual-line-mode)
  19989 	(beginning-of-visual-line n)
  19990       (move-beginning-of-line n))
  19991     (cond
  19992      ;; At a headline, with tags.
  19993      ((and special
  19994 	   (save-excursion
  19995 	     (beginning-of-line)
  19996 	     (let ((case-fold-search nil))
  19997 	       (looking-at org-complex-heading-regexp)))
  19998 	   (match-end 5))
  19999       (let ((tags (save-excursion
  20000 		    (goto-char (match-beginning 5))
  20001 		    (skip-chars-backward " \t")
  20002 		    (point)))
  20003 	    (visual-end (and (bound-and-true-p visual-line-mode)
  20004 			     (save-excursion
  20005 			       (end-of-visual-line)
  20006 			       (point)))))
  20007 	;; If `end-of-visual-line' brings us before end of line or
  20008 	;; even tags, i.e., the headline spans over multiple visual
  20009 	;; lines, move there.
  20010 	(cond ((and visual-end
  20011 		    (< visual-end tags)
  20012 		    (<= origin visual-end))
  20013 	       (goto-char visual-end))
  20014 	      ((eq special 'reversed)
  20015 	       (if (and (= origin (line-end-position))
  20016 			(eq this-command last-command))
  20017 		   (goto-char tags)
  20018 		 (end-of-line)))
  20019 	      (t
  20020 	       (if (or (< origin tags) (= origin (line-end-position)))
  20021 		   (goto-char tags)
  20022 		 (end-of-line))))))
  20023      ((bound-and-true-p visual-line-mode)
  20024       (let ((bol (line-beginning-position)))
  20025 	(end-of-visual-line)
  20026 	;; If `end-of-visual-line' gets us past the ellipsis at the
  20027 	;; end of a line, backtrack and use `end-of-line' instead.
  20028 	(when (/= bol (line-beginning-position))
  20029 	  (goto-char bol)
  20030 	  (end-of-line))))
  20031      (t (end-of-line)))))
  20032 
  20033 (defun org-backward-sentence (&optional _arg)
  20034   "Go to beginning of sentence, or beginning of table field.
  20035 This will call `backward-sentence' or `org-table-beginning-of-field',
  20036 depending on context."
  20037   (interactive)
  20038   (let* ((element (org-element-at-point))
  20039 	 (contents-begin (org-element-property :contents-begin element))
  20040 	 (table (org-element-lineage element '(table) t)))
  20041     (if (and table
  20042 	     (> (point) contents-begin)
  20043 	     (<= (point) (org-element-property :contents-end table)))
  20044 	(call-interactively #'org-table-beginning-of-field)
  20045       (save-restriction
  20046 	(when (and contents-begin
  20047 		   (< (point-min) contents-begin)
  20048 		   (> (point) contents-begin))
  20049 	  (narrow-to-region contents-begin
  20050 			    (org-element-property :contents-end element)))
  20051 	(call-interactively #'backward-sentence)))))
  20052 
  20053 (defun org-forward-sentence (&optional _arg)
  20054   "Go to end of sentence, or end of table field.
  20055 This will call `forward-sentence' or `org-table-end-of-field',
  20056 depending on context."
  20057   (interactive)
  20058   (if (and (org-at-heading-p)
  20059 	   (save-restriction (skip-chars-forward " \t") (not (eolp))))
  20060       (save-restriction
  20061 	(narrow-to-region (line-beginning-position) (line-end-position))
  20062 	(call-interactively #'forward-sentence))
  20063     (let* ((element (org-element-at-point))
  20064 	   (contents-end (org-element-property :contents-end element))
  20065 	   (table (org-element-lineage element '(table) t)))
  20066       (if (and table
  20067 	       (>= (point) (org-element-property :contents-begin table))
  20068 	       (< (point) contents-end))
  20069 	  (call-interactively #'org-table-end-of-field)
  20070 	(save-restriction
  20071 	  (when (and contents-end
  20072 		     (> (point-max) contents-end)
  20073 		     ;; Skip blank lines between elements.
  20074 		     (< (org-element-property :end element)
  20075 			(save-excursion (goto-char contents-end)
  20076 					(skip-chars-forward " \r\t\n"))))
  20077 	    (narrow-to-region (org-element-property :contents-begin element)
  20078 			      contents-end))
  20079 	  ;; End of heading is considered as the end of a sentence.
  20080 	  (let ((sentence-end (concat (sentence-end) "\\|^\\*+ .*$")))
  20081 	    (call-interactively #'forward-sentence)))))))
  20082 
  20083 (defun org-kill-line (&optional _arg)
  20084   "Kill line, to tags or end of line.
  20085 
  20086 The behavior of this command depends on the user options
  20087 `org-special-ctrl-k' and `org-ctrl-k-protect-subtree' (which
  20088 see)."
  20089   (interactive)
  20090   (cond
  20091    ((or (not org-special-ctrl-k)
  20092 	(bolp)
  20093 	(not (org-at-heading-p)))
  20094     (when (and (org-invisible-p (line-end-position))
  20095 	       org-ctrl-k-protect-subtree
  20096 	       (or (eq org-ctrl-k-protect-subtree 'error)
  20097 		   (not (y-or-n-p "Kill hidden subtree along with headline? "))))
  20098       (user-error
  20099        (substitute-command-keys
  20100 	"`\\[org-kill-line]' aborted as it would kill a hidden subtree")))
  20101     (call-interactively
  20102      (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
  20103    ((org-match-line org-tag-line-re)
  20104     (let ((end (save-excursion
  20105 		 (goto-char (match-beginning 1))
  20106 		 (skip-chars-backward " \t")
  20107 		 (point))))
  20108       (if (<= end (point))		;on tags part
  20109 	  (kill-region (point) (line-end-position))
  20110 	(kill-region (point) end)))
  20111     ;; Only align tags when we are still on a heading:
  20112     (if (org-at-heading-p) (org-align-tags)))
  20113    (t (kill-region (point) (line-end-position)))))
  20114 
  20115 (defun org-yank (&optional arg)
  20116   "Yank.  If the kill is a subtree, treat it specially.
  20117 This command will look at the current kill and check if is a single
  20118 subtree, or a series of subtrees[1].  If it passes the test, and if the
  20119 cursor is at the beginning of a line or after the stars of a currently
  20120 empty headline, then the yank is handled specially.  How exactly depends
  20121 on the value of the following variables.
  20122 
  20123 `org-yank-folded-subtrees'
  20124     By default, this variable is non-nil, which results in
  20125     subtree(s) being folded after insertion, except if doing so
  20126     would swallow text after the yanked text.
  20127 
  20128 `org-yank-adjusted-subtrees'
  20129     When non-nil (the default value is nil), the subtree will be
  20130     promoted or demoted in order to fit into the local outline tree
  20131     structure, which means that the level will be adjusted so that it
  20132     becomes the smaller one of the two *visible* surrounding headings.
  20133 
  20134 Any prefix to this command will cause `yank' to be called directly with
  20135 no special treatment.  In particular, a simple `\\[universal-argument]' prefix \
  20136 will just
  20137 plainly yank the text as it is.
  20138 
  20139 \[1] The test checks if the first non-white line is a heading
  20140     and if there are no other headings with fewer stars."
  20141   (interactive "P")
  20142   (org-yank-generic 'yank arg))
  20143 
  20144 (defun org-yank-generic (command arg)
  20145   "Perform some yank-like command.
  20146 
  20147 This function implements the behavior described in the `org-yank'
  20148 documentation.  However, it has been generalized to work for any
  20149 interactive command with similar behavior."
  20150 
  20151   ;; pretend to be command COMMAND
  20152   (setq this-command command)
  20153 
  20154   (if arg
  20155       (call-interactively command)
  20156 
  20157     (let ((subtreep ; is kill a subtree, and the yank position appropriate?
  20158 	   (and (org-kill-is-subtree-p)
  20159 		(or (bolp)
  20160 		    (and (looking-at "[ \t]*$")
  20161 			 (string-match
  20162 			  "\\`\\*+\\'"
  20163                           (buffer-substring (line-beginning-position) (point)))))))
  20164 	  swallowp)
  20165       (cond
  20166        ((and subtreep org-yank-folded-subtrees)
  20167 	(let ((beg (point))
  20168 	      end)
  20169 	  (if (and subtreep org-yank-adjusted-subtrees)
  20170 	      (org-paste-subtree nil nil 'for-yank)
  20171 	    (call-interactively command))
  20172 
  20173 	  (setq end (point))
  20174 	  (goto-char beg)
  20175 	  (when (and (bolp) subtreep
  20176 		     (not (setq swallowp
  20177 				(org-yank-folding-would-swallow-text beg end))))
  20178 	    (org-with-limited-levels
  20179 	     (or (looking-at org-outline-regexp)
  20180 		 (re-search-forward org-outline-regexp-bol end t))
  20181 	     (while (and (< (point) end) (looking-at org-outline-regexp))
  20182 	       (org-fold-subtree t)
  20183 	       (org-cycle-show-empty-lines 'folded)
  20184 	       (condition-case nil
  20185 		   (outline-forward-same-level 1)
  20186 		 (error (goto-char end))))))
  20187 	  (when swallowp
  20188 	    (message
  20189 	     "Inserted text not folded because that would swallow text"))
  20190 
  20191 	  (goto-char end)
  20192 	  (skip-chars-forward " \t\n\r")
  20193 	  (beginning-of-line 1)
  20194 	  (push-mark beg 'nomsg)))
  20195        ((and subtreep org-yank-adjusted-subtrees)
  20196         (let ((beg (line-beginning-position)))
  20197 	  (org-paste-subtree nil nil 'for-yank)
  20198 	  (push-mark beg 'nomsg)))
  20199        (t
  20200 	(call-interactively command))))))
  20201 
  20202 (defun org-yank-folding-would-swallow-text (beg end)
  20203   "Would `hide-subtree' at BEG swallow any text after END?"
  20204   (let (level)
  20205     (org-with-limited-levels
  20206      (save-excursion
  20207        (goto-char beg)
  20208        (when (or (looking-at org-outline-regexp)
  20209 		 (re-search-forward org-outline-regexp-bol end t))
  20210 	 (setq level (org-outline-level)))
  20211        (goto-char end)
  20212        (skip-chars-forward " \t\r\n\v\f")
  20213        (not (or (eobp)
  20214 		(and (bolp) (looking-at-p org-outline-regexp)
  20215 		     (<= (org-outline-level) level))))))))
  20216 
  20217 (defun org-back-to-heading (&optional invisible-ok)
  20218   "Go back to beginning of heading."
  20219   (beginning-of-line)
  20220   (or (and (org-at-heading-p (not invisible-ok))
  20221            (not (and (featurep 'org-inlinetask)
  20222                    (fboundp 'org-inlinetask-end-p)
  20223                    (org-inlinetask-end-p))))
  20224       (if (org-element--cache-active-p)
  20225           (let ((heading (org-element-lineage (org-element-at-point)
  20226                                            '(headline inlinetask)
  20227                                            'include-self)))
  20228             (when heading
  20229               (goto-char (org-element-property :begin heading)))
  20230             (while (and (not invisible-ok)
  20231                         heading
  20232                         (org-fold-folded-p))
  20233               (goto-char (org-fold-core-previous-visibility-change))
  20234               (setq heading (org-element-lineage (org-element-at-point)
  20235                                               '(headline inlinetask)
  20236                                               'include-self))
  20237               (when heading
  20238                 (goto-char (org-element-property :begin heading))))
  20239             (unless heading
  20240               (user-error "Before first headline at position %d in buffer %s"
  20241 		          (point) (current-buffer)))
  20242             (point))
  20243         (let (found)
  20244 	  (save-excursion
  20245             ;; At inlinetask end.  Move to bol, so that the following
  20246             ;; search goes to the beginning of the inlinetask.
  20247             (when (and (featurep 'org-inlinetask)
  20248                        (fboundp 'org-inlinetask-end-p)
  20249                        (org-inlinetask-end-p))
  20250               (goto-char (line-beginning-position)))
  20251 	    (while (not found)
  20252 	      (or (re-search-backward (concat "^\\(?:" outline-regexp "\\)")
  20253 				      nil t)
  20254                   (user-error "Before first headline at position %d in buffer %s"
  20255 		              (point) (current-buffer)))
  20256               ;; Skip inlinetask end.
  20257               (if (and (featurep 'org-inlinetask)
  20258                        (fboundp 'org-inlinetask-end-p)
  20259                        (org-inlinetask-end-p))
  20260                   (org-inlinetask-goto-beginning)
  20261 	        (setq found (and (or invisible-ok (not (org-fold-folded-p)))
  20262 			         (point))))))
  20263 	  (goto-char found)
  20264 	  found))))
  20265 
  20266 (defun org-back-to-heading-or-point-min (&optional invisible-ok)
  20267   "Go back to heading or first point in buffer.
  20268 If point is before first heading go to first point in buffer
  20269 instead of back to heading."
  20270   (if (org-before-first-heading-p)
  20271       (goto-char (point-min))
  20272     (org-back-to-heading invisible-ok)))
  20273 
  20274 (defun org-before-first-heading-p ()
  20275   "Before first heading?
  20276 Respect narrowing."
  20277   (let ((cached (org-element-at-point nil 'cached)))
  20278     (if cached
  20279         (let ((cached-headline (org-element-lineage cached '(headline) t)))
  20280           (or (not cached-headline)
  20281               (< (org-element-property :begin cached-headline) (point-min))))
  20282       (org-with-limited-levels
  20283        (save-excursion
  20284          (end-of-line)
  20285          (null (re-search-backward org-outline-regexp-bol nil t)))))))
  20286 
  20287 (defun org-at-heading-p (&optional invisible-not-ok)
  20288   "Return t if point is on a (possibly invisible) heading line.
  20289 If INVISIBLE-NOT-OK is non-nil, an invisible heading line is not ok."
  20290   (save-excursion
  20291     (beginning-of-line)
  20292     (and (bolp) (or (not invisible-not-ok) (not (org-fold-folded-p)))
  20293 	 (looking-at outline-regexp))))
  20294 
  20295 (defun org-in-commented-heading-p (&optional no-inheritance element)
  20296   "Non-nil if point is under a commented heading.
  20297 This function also checks ancestors of the current headline,
  20298 unless optional argument NO-INHERITANCE is non-nil.
  20299 
  20300 Optional argument ELEMENT contains element at point."
  20301   (save-match-data
  20302     (let ((el (or element
  20303                   (org-element-at-point nil 'cached)
  20304                   (org-with-wide-buffer
  20305                    (org-back-to-heading-or-point-min t)
  20306                    (org-element-at-point)))))
  20307       (catch :found
  20308         (setq el (org-element-lineage el '(headline inlinetask) 'include-self))
  20309         (if no-inheritance
  20310             (org-element-property :commentedp el)
  20311           (while el
  20312             (when (org-element-property :commentedp el)
  20313               (throw :found t))
  20314             (setq el (org-element-property :parent el))))))))
  20315 
  20316 (defun org-in-archived-heading-p (&optional no-inheritance element)
  20317   "Non-nil if point is under an archived heading.
  20318 This function also checks ancestors of the current headline,
  20319 unless optional argument NO-INHERITANCE is non-nil.
  20320 
  20321 Optional argument ELEMENT contains element at point."
  20322   (cond
  20323    ((and (not element) (org-before-first-heading-p)) nil)
  20324    ((if element
  20325         (org-element-property :archivedp element)
  20326       (let ((tags (org-get-tags element 'local)))
  20327         (and tags
  20328 	     (cl-some (apply-partially #'string= org-archive-tag) tags)))))
  20329    (no-inheritance nil)
  20330    (t
  20331     (if (or element (org-element--cache-active-p))
  20332         (catch :archived
  20333           (unless element (setq element (org-element-at-point)))
  20334           (while element
  20335             (when (org-element-property :archivedp element)
  20336               (throw :archived t))
  20337             (setq element (org-element-property :parent element))))
  20338       (save-excursion (and (org-up-heading-safe) (org-in-archived-heading-p)))))))
  20339 
  20340 (defun org-at-comment-p nil
  20341   "Return t if cursor is in a commented line."
  20342   (save-excursion
  20343     (save-match-data
  20344       (beginning-of-line)
  20345       (looking-at org-comment-regexp))))
  20346 
  20347 (defun org-at-keyword-p nil
  20348   "Return t if cursor is at a keyword-line."
  20349   (save-excursion
  20350     (move-beginning-of-line 1)
  20351     (looking-at org-keyword-regexp)))
  20352 
  20353 (defun org-at-drawer-p nil
  20354   "Return t if cursor is at a drawer keyword."
  20355   (save-excursion
  20356     (move-beginning-of-line 1)
  20357     (looking-at org-drawer-regexp)))
  20358 
  20359 (defun org-at-block-p nil
  20360   "Return t if cursor is at a block keyword."
  20361   (save-excursion
  20362     (move-beginning-of-line 1)
  20363     (looking-at org-block-regexp)))
  20364 
  20365 (defun org-point-at-end-of-empty-headline ()
  20366   "If point is at the end of an empty headline, return t, else nil.
  20367 If the heading only contains a TODO keyword, it is still considered
  20368 empty."
  20369   (let ((case-fold-search nil))
  20370     (and (looking-at "[ \t]*$")
  20371 	 org-todo-line-regexp
  20372 	 (save-excursion
  20373 	   (beginning-of-line)
  20374 	   (looking-at org-todo-line-regexp)
  20375 	   (string= (match-string 3) "")))))
  20376 
  20377 (defun org-at-heading-or-item-p ()
  20378   (or (org-at-heading-p) (org-at-item-p)))
  20379 
  20380 (defun org-up-heading-all (arg)
  20381   "Move to the heading line of which the present line is a subheading.
  20382 This function considers both visible and invisible heading lines.
  20383 With argument, move up ARG levels."
  20384   (outline-up-heading arg t))
  20385 
  20386 (defvar-local org--up-heading-cache nil
  20387   "Buffer-local `org-up-heading-safe' cache.")
  20388 (defvar-local org--up-heading-cache-tick nil
  20389   "Buffer `buffer-chars-modified-tick' in `org--up-heading-cache'.")
  20390 (defun org-up-heading-safe ()
  20391   "Move to the heading line of which the present line is a subheading.
  20392 This version will not throw an error.  It will return the level of the
  20393 headline found, or nil if no higher level is found.
  20394 
  20395 Also, this function will be a lot faster than `outline-up-heading',
  20396 because it relies on stars being the outline starters.  This can really
  20397 make a significant difference in outlines with very many siblings."
  20398   (let ((element (and (org-element--cache-active-p)
  20399                       (org-element-at-point nil t))))
  20400     (if element
  20401         (let* ((current-heading (org-element-lineage element '(headline inlinetask) 'with-self))
  20402                (parent (org-element-lineage current-heading '(headline))))
  20403           (if (and parent
  20404                    (<= (point-min) (org-element-property :begin parent)))
  20405               (progn
  20406                 (goto-char (org-element-property :begin parent))
  20407                 (org-element-property :level parent))
  20408             (when (and current-heading
  20409                        (<= (point-min) (org-element-property :begin current-heading)))
  20410               (goto-char (org-element-property :begin current-heading))
  20411               nil)))
  20412       (when (ignore-errors (org-back-to-heading t))
  20413         (let (level-cache)
  20414           (unless org--up-heading-cache
  20415             (setq org--up-heading-cache (make-hash-table)))
  20416           (if (and (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  20417                    (setq level-cache (gethash (point) org--up-heading-cache)))
  20418               (when (<= (point-min) (car level-cache) (point-max))
  20419                 ;; Parent is inside accessible part of the buffer.
  20420                 (progn (goto-char (car level-cache))
  20421                        (cdr level-cache)))
  20422             ;; Buffer modified.  Invalidate cache.
  20423             (unless (eq (buffer-chars-modified-tick) org--up-heading-cache-tick)
  20424               (setq-local org--up-heading-cache-tick
  20425                           (buffer-chars-modified-tick))
  20426               (clrhash org--up-heading-cache))
  20427             (let* ((level-up (1- (funcall outline-level)))
  20428                    (pos (point))
  20429                    (result (and (> level-up 0)
  20430 	                        (re-search-backward
  20431                                  (format "^\\*\\{1,%d\\} " level-up) nil t)
  20432 	                        (funcall outline-level))))
  20433               (when result (puthash pos (cons (point) result) org--up-heading-cache))
  20434               result)))))))
  20435 
  20436 (defun org-up-heading-or-point-min ()
  20437   "Move to the heading line of which the present is a subheading, or point-min.
  20438 This version is needed to make point-min behave like a virtual
  20439 heading of level 0 for property-inheritance.  It will return the
  20440 level of the headline found (down to 0) or nil if already at a
  20441 point before the first headline or at point-min."
  20442   (when (ignore-errors (org-back-to-heading t))
  20443     (if (< 1 (funcall outline-level))
  20444 	(or (org-up-heading-safe)
  20445             ;; The first heading may not be level 1 heading.
  20446             (goto-char (point-min)))
  20447       (unless (= (point) (point-min)) (goto-char (point-min))))))
  20448 
  20449 (defun org-first-sibling-p ()
  20450   "Is this heading the first child of its parents?"
  20451   (interactive)
  20452   (let ((re org-outline-regexp-bol)
  20453 	level l)
  20454     (unless (org-at-heading-p t)
  20455       (user-error "Not at a heading"))
  20456     (setq level (funcall outline-level))
  20457     (save-excursion
  20458       (if (not (re-search-backward re nil t))
  20459 	  t
  20460 	(setq l (funcall outline-level))
  20461 	(< l level)))))
  20462 
  20463 (defun org-goto-sibling (&optional previous)
  20464   "Goto the next sibling, even if it is invisible.
  20465 When PREVIOUS is set, go to the previous sibling instead.  Returns t
  20466 when a sibling was found.  When none is found, return nil and don't
  20467 move point."
  20468   (let ((fun (if previous 're-search-backward 're-search-forward))
  20469 	(pos (point))
  20470 	(re org-outline-regexp-bol)
  20471 	level l)
  20472     (when (ignore-errors (org-back-to-heading t))
  20473       (setq level (funcall outline-level))
  20474       (catch 'exit
  20475 	(or previous (forward-char 1))
  20476 	(while (funcall fun re nil t)
  20477 	  (setq l (funcall outline-level))
  20478 	  (when (< l level) (goto-char pos) (throw 'exit nil))
  20479 	  (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
  20480 	(goto-char pos)
  20481 	nil))))
  20482 
  20483 (defun org-goto-first-child (&optional element)
  20484   "Goto the first child, even if it is invisible.
  20485 Return t when a child was found.  Otherwise don't move point and
  20486 return nil."
  20487   (if (org-element--cache-active-p)
  20488       (let ((heading (org-element-lineage
  20489                       (or element (org-element-at-point))
  20490                       '(headline inlinetask org-data)
  20491                       t)))
  20492         (when heading
  20493           (unless (or (eq 'inlinetask (org-element-type heading))
  20494                       (not (org-element-property :contents-begin heading)))
  20495             (let ((pos (point)))
  20496               (goto-char (org-element-property :contents-begin heading))
  20497               (if (re-search-forward
  20498                    org-outline-regexp-bol
  20499                    (org-element-property :end heading)
  20500                    t)
  20501                   (progn (goto-char (match-beginning 0)) t)
  20502                 (goto-char pos) nil)))))
  20503     (let (level (pos (point)) (re org-outline-regexp-bol))
  20504       (when (org-back-to-heading-or-point-min t)
  20505         (setq level (org-outline-level))
  20506         (forward-char 1)
  20507         (if (and (re-search-forward re nil t) (> (org-outline-level) level))
  20508 	    (progn (goto-char (match-beginning 0)) t)
  20509 	  (goto-char pos) nil)))))
  20510 
  20511 (defun org-get-next-sibling ()
  20512   "Move to next heading of the same level, and return point.
  20513 If there is no such heading, return nil.
  20514 This is like outline-next-sibling, but invisible headings are ok."
  20515   (let ((level (funcall outline-level)))
  20516     (outline-next-heading)
  20517     (while (and (not (eobp)) (> (funcall outline-level) level))
  20518       (outline-next-heading))
  20519     (unless (or (eobp) (< (funcall outline-level) level))
  20520       (point))))
  20521 
  20522 (defun org-get-previous-sibling ()
  20523   "Move to previous heading of the same level, and return point.
  20524 If there is no such heading, return nil."
  20525   (let ((opoint (point))
  20526 	(level (funcall outline-level)))
  20527     (outline-previous-heading)
  20528     (when (and (/= (point) opoint) (outline-on-heading-p t))
  20529       (while (and (> (funcall outline-level) level)
  20530 		  (not (bobp)))
  20531 	(outline-previous-heading))
  20532       (unless (< (funcall outline-level) level)
  20533         (point)))))
  20534 
  20535 (defun org-end-of-subtree (&optional invisible-ok to-heading element)
  20536   "Goto to the end of a subtree at point or for ELEMENT heading."
  20537   ;; This contains an exact copy of the original function, but it uses
  20538   ;; `org-back-to-heading-or-point-min', to make it work also in invisible
  20539   ;; trees and before first headline.  And is uses an invisible-ok argument.
  20540   ;; Under Emacs this is not needed, but the old outline.el needs this fix.
  20541   ;; Furthermore, when used inside Org, finding the end of a large subtree
  20542   ;; with many children and grandchildren etc, this can be much faster
  20543   ;; than the outline version.
  20544   (if element
  20545       (setq element (org-element-lineage element '(headline inlinetask) 'include-self))
  20546     (org-back-to-heading-or-point-min invisible-ok))
  20547   (unless (and (org-element--cache-active-p)
  20548                (let ((cached (or element (org-element-at-point nil t))))
  20549                  (and cached
  20550                       (eq 'headline (org-element-type cached))
  20551                       (goto-char (org-element-property
  20552                                   :end cached)))))
  20553     (let ((first t)
  20554 	  (level (funcall outline-level)))
  20555       (cond ((= level 0)
  20556 	     (goto-char (point-max)))
  20557 	    ((and (derived-mode-p 'org-mode) (< level 1000))
  20558 	     ;; A true heading (not a plain list item), in Org
  20559 	     ;; This means we can easily find the end by looking
  20560 	     ;; only for the right number of stars.  Using a regexp to do
  20561 	     ;; this is so much faster than using a Lisp loop.
  20562 	     (let ((re (concat "^\\*\\{1," (number-to-string level) "\\} ")))
  20563 	       (forward-char 1)
  20564 	       (and (re-search-forward re nil 'move) (beginning-of-line 1))))
  20565 	    (t
  20566 	     ;; something else, do it the slow way
  20567 	     (while (and (not (eobp))
  20568 		         (or first (> (funcall outline-level) level)))
  20569 	       (setq first nil)
  20570 	       (outline-next-heading))))))
  20571   (unless to-heading
  20572     (when (memq (preceding-char) '(?\n ?\^M))
  20573       ;; Go to end of line before heading
  20574       (forward-char -1)
  20575       (when (memq (preceding-char) '(?\n ?\^M))
  20576 	;; leave blank line before heading
  20577 	(forward-char -1))))
  20578   (point))
  20579 
  20580 (defun org-end-of-meta-data (&optional full)
  20581   "Skip planning line and properties drawer in current entry.
  20582 
  20583 When optional argument FULL is t, also skip planning information,
  20584 clocking lines and any kind of drawer.
  20585 
  20586 When FULL is non-nil but not t, skip planning information,
  20587 properties, clocking lines and logbook drawers."
  20588   (org-back-to-heading t)
  20589   (forward-line)
  20590   ;; Skip planning information.
  20591   (when (looking-at-p org-planning-line-re) (forward-line))
  20592   ;; Skip property drawer.
  20593   (when (looking-at org-property-drawer-re)
  20594     (goto-char (match-end 0))
  20595     (forward-line))
  20596   ;; When FULL is not nil, skip more.
  20597   (when (and full (not (org-at-heading-p)))
  20598     (catch 'exit
  20599       (let ((end (save-excursion (outline-next-heading) (point)))
  20600 	    (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
  20601 	(while (not (eobp))
  20602 	  (cond ;; Skip clock lines.
  20603 	   ((looking-at-p re) (forward-line))
  20604 	   ;; Skip logbook drawer.
  20605 	   ((looking-at-p org-logbook-drawer-re)
  20606 	    (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  20607 		(forward-line)
  20608 	      (throw 'exit t)))
  20609 	   ;; When FULL is t, skip regular drawer too.
  20610 	   ((and (eq full t) (looking-at-p org-drawer-regexp))
  20611 	    (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
  20612 		(forward-line)
  20613 	      (throw 'exit t)))
  20614 	   (t (throw 'exit t))))))))
  20615 
  20616 (defun org--line-fully-invisible-p ()
  20617   "Return non-nil if the current line is fully invisible."
  20618   (let ((line-beg (line-beginning-position))
  20619 	(line-pos (1- (line-end-position)))
  20620 	(is-invisible t))
  20621     (while (and (< line-beg line-pos) is-invisible)
  20622       (setq is-invisible (org-invisible-p line-pos))
  20623       (setq line-pos (1- line-pos)))
  20624     is-invisible))
  20625 
  20626 (defun org-forward-heading-same-level (arg &optional invisible-ok)
  20627   "Move forward to the ARG'th subheading at same level as this one.
  20628 Stop at the first and last subheadings of a superior heading.
  20629 Normally this only looks at visible headings, but when INVISIBLE-OK is
  20630 non-nil it will also look at invisible ones."
  20631   (interactive "p")
  20632   (let ((backward? (and arg (< arg 0))))
  20633     (if (org-before-first-heading-p)
  20634 	(if backward? (goto-char (point-min)) (outline-next-heading))
  20635       (org-back-to-heading invisible-ok)
  20636       (unless backward? (end-of-line))	;do not match current headline
  20637       (let ((level (- (match-end 0) (match-beginning 0) 1))
  20638 	    (f (if backward? #'re-search-backward #'re-search-forward))
  20639 	    (count (if arg (abs arg) 1))
  20640 	    (result (point)))
  20641 	(while (and (> count 0)
  20642 		    (funcall f org-outline-regexp-bol nil 'move))
  20643 	  (let ((l (- (match-end 0) (match-beginning 0) 1)))
  20644 	    (cond ((< l level) (setq count 0))
  20645 		  ((and (= l level)
  20646 			(or invisible-ok
  20647 			    ;; FIXME: See commit a700fadd72 and the
  20648 			    ;; related discussion on why using
  20649 			    ;; `org--line-fully-invisible-p' is needed
  20650 			    ;; here, which is to serve the needs of an
  20651 			    ;; external package.  If the change is
  20652 			    ;; wrong regarding Org itself, it should
  20653 			    ;; be removed.
  20654 			    (not (org--line-fully-invisible-p))))
  20655 		   (cl-decf count)
  20656 		   (when (= l level) (setq result (point)))))))
  20657 	(goto-char result))
  20658       (beginning-of-line))))
  20659 
  20660 (defun org-backward-heading-same-level (arg &optional invisible-ok)
  20661   "Move backward to the ARG'th subheading at same level as this one.
  20662 Stop at the first and last subheadings of a superior heading."
  20663   (interactive "p")
  20664   (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
  20665 
  20666 (defun org-next-visible-heading (arg)
  20667   "Move to the next visible heading line.
  20668 With ARG, repeats or can move backward if negative."
  20669   (interactive "p")
  20670   (let ((regexp (concat "^" (org-get-limited-outline-regexp))))
  20671     (if (< arg 0)
  20672 	(beginning-of-line)
  20673       (end-of-line))
  20674     (while (and (< arg 0) (re-search-backward regexp nil :move))
  20675       (unless (bobp)
  20676 	(when (org-fold-folded-p)
  20677 	  (goto-char (org-fold-previous-visibility-change))
  20678           (unless (looking-at-p regexp)
  20679             (re-search-backward regexp nil :mode))))
  20680       (cl-incf arg))
  20681     (while (and (> arg 0) (re-search-forward regexp nil :move))
  20682       (when (org-fold-folded-p)
  20683 	(goto-char (org-fold-next-visibility-change))
  20684         (skip-chars-forward " \t\n")
  20685 	(end-of-line))
  20686       (cl-decf arg))
  20687     (if (> arg 0) (goto-char (point-max)) (beginning-of-line))))
  20688 
  20689 (defun org-previous-visible-heading (arg)
  20690   "Move to the previous visible heading.
  20691 With ARG, repeats or can move forward if negative."
  20692   (interactive "p")
  20693   (org-next-visible-heading (- arg)))
  20694 
  20695 (defun org-forward-paragraph (&optional arg)
  20696   "Move forward by a paragraph, or equivalent, unit.
  20697 
  20698 With argument ARG, do it ARG times;
  20699 a negative argument ARG = -N means move backward N paragraphs.
  20700 
  20701 The function moves point between two structural
  20702 elements (paragraphs, tables, lists, etc.).
  20703 
  20704 It also provides the following special moves for convenience:
  20705 
  20706   - on a table or a property drawer, move to its beginning;
  20707   - on comment, example, export, source and verse blocks, stop
  20708     at blank lines;
  20709   - skip consecutive clocks, diary S-exps, and keywords."
  20710   (interactive "^p")
  20711   (unless arg (setq arg 1))
  20712   (if (< arg 0) (org-backward-paragraph (- arg))
  20713     (while (and (> arg 0) (not (eobp)))
  20714       (org--forward-paragraph-once)
  20715       (cl-decf arg))
  20716     ;; Return moves left.
  20717     arg))
  20718 
  20719 (defun org-backward-paragraph (&optional arg)
  20720   "Move backward by a paragraph, or equivalent, unit.
  20721 
  20722 With argument ARG, do it ARG times;
  20723 a negative argument ARG = -N means move forward N paragraphs.
  20724 
  20725 The function moves point between two structural
  20726 elements (paragraphs, tables, lists, etc.).
  20727 
  20728 It also provides the following special moves for convenience:
  20729 
  20730   - on a table or a property drawer, move to its beginning;
  20731   - on comment, example, export, source and verse blocks, stop
  20732     at blank lines;
  20733   - skip consecutive clocks, diary S-exps, and keywords."
  20734   (interactive "^p")
  20735   (unless arg (setq arg 1))
  20736   (if (< arg 0) (org-forward-paragraph (- arg))
  20737     (while (and (> arg 0) (not (bobp)))
  20738       (org--backward-paragraph-once)
  20739       (cl-decf arg))
  20740     ;; Return moves left.
  20741     arg))
  20742 
  20743 (defvar org--single-lines-list-is-paragraph t
  20744   "Treat plain lists with single line items as a whole paragraph")
  20745 
  20746 (defun org--paragraph-at-point ()
  20747   "Return paragraph, or equivalent, element at point.
  20748 
  20749 Paragraph element at point is the element at point, with the
  20750 following special cases:
  20751 
  20752 - treat table rows (resp. node properties) as the table
  20753   \(resp. property drawer) containing them.
  20754 
  20755 - treat plain lists with an item every line as a whole.
  20756 
  20757 - treat consecutive keywords, clocks, and diary-sexps as a single
  20758   block.
  20759 
  20760 Function may return a real element, or a pseudo-element with type
  20761 `pseudo-paragraph'."
  20762   (let* ((e (org-element-at-point))
  20763 	 (type (org-element-type e))
  20764 	 ;; If we need to fake a new pseudo-element, triplet is
  20765 	 ;;
  20766 	 ;;   (BEG END PARENT)
  20767 	 ;;
  20768 	 ;; where BEG and END are element boundaries, and PARENT the
  20769 	 ;; element containing it, or nil.
  20770 	 (triplet
  20771 	  (cond
  20772 	   ((memq type '(table property-drawer))
  20773 	    (list (org-element-property :begin e)
  20774 		  (org-element-property :end e)
  20775 		  (org-element-property :parent e)))
  20776 	   ((memq type '(node-property table-row))
  20777 	    (let ((e (org-element-property :parent e)))
  20778 	      (list (org-element-property :begin e)
  20779 		    (org-element-property :end e)
  20780 		    (org-element-property :parent e))))
  20781 	   ((memq type '(clock diary-sexp keyword))
  20782 	    (let* ((regexp (pcase type
  20783 			     (`clock org-clock-line-re)
  20784 			     (`diary-sexp "%%(")
  20785 			     (_ org-keyword-regexp)))
  20786 		   (end (if (< 0 (org-element-property :post-blank e))
  20787 			    (org-element-property :end e)
  20788 			  (org-with-wide-buffer
  20789 			   (forward-line)
  20790 			   (while (looking-at regexp) (forward-line))
  20791 			   (skip-chars-forward " \t\n")
  20792 			   (line-beginning-position))))
  20793 		   (begin (org-with-point-at (org-element-property :begin e)
  20794 			    (while (and (not (bobp)) (looking-at regexp))
  20795 			      (forward-line -1))
  20796 			    ;; We may have gotten one line too far.
  20797 			    (if (looking-at regexp)
  20798 				(point)
  20799 			      (line-beginning-position 2)))))
  20800 	      (list begin end (org-element-property :parent e))))
  20801 	   ;; Find the full plain list containing point, the check it
  20802 	   ;; contains exactly one line per item.
  20803 	   ((let ((l (org-element-lineage e '(plain-list) t)))
  20804 	      (while (memq (org-element-type (org-element-property :parent l))
  20805 			   '(item plain-list))
  20806 		(setq l (org-element-property :parent l)))
  20807 	      (and l org--single-lines-list-is-paragraph
  20808 		   (org-with-point-at (org-element-property :post-affiliated l)
  20809 		     (forward-line (length (org-element-property :structure l)))
  20810 		     (= (point) (org-element-property :contents-end l)))
  20811 		   ;; Return value.
  20812 		   (list (org-element-property :begin l)
  20813 			 (org-element-property :end l)
  20814 			 (org-element-property :parent l)))))
  20815 	   (t nil))))			;no triplet: return element
  20816     (pcase triplet
  20817       (`(,b ,e ,p)
  20818        (org-element-create
  20819 	'pseudo-paragraph
  20820 	(list :begin b :end e :parent p :post-blank 0 :post-affiliated b)))
  20821       (_ e))))
  20822 
  20823 (defun org--forward-paragraph-once ()
  20824   "Move forward to end of paragraph or equivalent, once.
  20825 See `org-forward-paragraph'."
  20826   (interactive)
  20827   (save-restriction
  20828     (widen)
  20829     (skip-chars-forward " \t\n")
  20830     (cond
  20831      ((eobp) nil)
  20832      ;; When inside a folded part, move out of it.
  20833      ((when (org-invisible-p nil t)
  20834         (goto-char (cdr (org-fold-get-region-at-point)))
  20835         (forward-line)
  20836         t))
  20837      (t
  20838       (let* ((element (org--paragraph-at-point))
  20839 	     (type (org-element-type element))
  20840 	     (contents-begin (org-element-property :contents-begin element))
  20841 	     (end (org-element-property :end element))
  20842 	     (post-affiliated (org-element-property :post-affiliated element)))
  20843 	(cond
  20844 	 ((eq type 'plain-list)
  20845 	  (forward-char)
  20846 	  (org--forward-paragraph-once))
  20847 	 ;; If the element is folded, skip it altogether.
  20848          ((when (org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  20849             (goto-char (cdr (org-fold-get-region-at-point
  20850 			     nil
  20851 			     (org-with-point-at post-affiliated
  20852 			       (line-end-position)))))
  20853 	    (forward-line)
  20854 	    t))
  20855 	 ;; At a greater element, move inside.
  20856 	 ((and contents-begin
  20857 	       (> contents-begin (point))
  20858 	       (not (eq type 'paragraph)))
  20859 	  (goto-char contents-begin)
  20860 	  ;; Items and footnote definitions contents may not start at
  20861 	  ;; the beginning of the line.  In this case, skip until the
  20862 	  ;; next paragraph.
  20863 	  (cond
  20864 	   ((not (bolp)) (org--forward-paragraph-once))
  20865 	   ((org-previous-line-empty-p) (forward-line -1))
  20866 	   (t nil)))
  20867 	 ;; Move between empty lines in some blocks.
  20868 	 ((memq type '(comment-block example-block export-block src-block
  20869 				     verse-block))
  20870 	  (let ((contents-start
  20871 		 (org-with-point-at post-affiliated
  20872 		   (line-beginning-position 2))))
  20873 	    (if (< (point) contents-start)
  20874 		(goto-char contents-start)
  20875 	      (let ((contents-end
  20876 		     (org-with-point-at end
  20877 		       (skip-chars-backward " \t\n")
  20878 		       (line-beginning-position))))
  20879 		(cond
  20880 		 ((>= (point) contents-end)
  20881 		  (goto-char end)
  20882 		  (skip-chars-backward " \t\n")
  20883 		  (forward-line))
  20884 		 ((re-search-forward "^[ \t]*\n" contents-end :move)
  20885 		  (forward-line -1))
  20886 		 (t nil))))))
  20887 	 (t
  20888 	  ;; Move to element's end.
  20889 	  (goto-char end)
  20890 	  (skip-chars-backward " \t\n")
  20891 	  (forward-line))))))))
  20892 
  20893 (defun org--backward-paragraph-once ()
  20894   "Move backward to start of paragraph or equivalent, once.
  20895 See `org-backward-paragraph'."
  20896   (interactive)
  20897   (save-restriction
  20898     (widen)
  20899     (cond
  20900      ((bobp) nil)
  20901      ;; Blank lines at the beginning of the buffer.
  20902      ((and (org-match-line "^[ \t]*$")
  20903 	   (save-excursion (skip-chars-backward " \t\n") (bobp)))
  20904       (goto-char (point-min)))
  20905      ;; When inside a folded part, move out of it.
  20906      ((when (org-invisible-p (1- (point)) t)
  20907         (goto-char (1- (car (org-fold-get-region-at-point nil (1- (point))))))
  20908 	(org--backward-paragraph-once)
  20909 	t))
  20910      (t
  20911       (let* ((element (org--paragraph-at-point))
  20912 	     (type (org-element-type element))
  20913 	     (begin (org-element-property :begin element))
  20914 	     (post-affiliated (org-element-property :post-affiliated element))
  20915 	     (contents-end (org-element-property :contents-end element))
  20916 	     (end (org-element-property :end element))
  20917 	     (parent (org-element-property :parent element))
  20918 	     (reach
  20919 	      ;; Move to the visible empty line above position P, or
  20920 	      ;; to position P.  Return t.
  20921 	      (lambda (p)
  20922 		(goto-char p)
  20923 		(when (and (org-previous-line-empty-p)
  20924 			   (let ((end (line-end-position 0)))
  20925 			     (or (= end (point-min))
  20926 				 (not (org-invisible-p (1- end))))))
  20927 		  (forward-line -1))
  20928 		t)))
  20929 	(cond
  20930 	 ;; Already at the beginning of an element.
  20931 	 ((= begin (point))
  20932 	  (cond
  20933 	   ;; There is a blank line above.  Move there.
  20934 	   ((and (org-previous-line-empty-p)
  20935 		 (not (org-invisible-p (1- (line-end-position 0)))))
  20936 	    (forward-line -1))
  20937 	   ;; At the beginning of the first element within a greater
  20938 	   ;; element.  Move to the beginning of the greater element.
  20939 	   ((and parent
  20940                  (not (eq 'section (org-element-type parent)))
  20941                  (= begin (org-element-property :contents-begin parent)))
  20942 	    (funcall reach (org-element-property :begin parent)))
  20943 	   ;; Since we have to move anyway, find the beginning
  20944 	   ;; position of the element above.
  20945 	   (t
  20946 	    (forward-char -1)
  20947 	    (org--backward-paragraph-once))))
  20948 	 ;; Skip paragraphs at the very beginning of footnote
  20949 	 ;; definitions or items.
  20950 	 ((and (eq type 'paragraph)
  20951 	       (org-with-point-at begin (not (bolp))))
  20952 	  (funcall reach (progn (goto-char begin) (line-beginning-position))))
  20953 	 ;; If the element is folded, skip it altogether.
  20954 	 ((org-with-point-at post-affiliated (org-invisible-p (line-end-position) t))
  20955 	  (funcall reach begin))
  20956 	 ;; At the end of a greater element, move inside.
  20957 	 ((and contents-end
  20958 	       (<= contents-end (point))
  20959 	       (not (eq type 'paragraph)))
  20960 	  (cond
  20961 	   ((memq type '(footnote-definition plain-list))
  20962 	    (skip-chars-backward " \t\n")
  20963 	    (org--backward-paragraph-once))
  20964 	   ((= contents-end (point))
  20965 	    (forward-char -1)
  20966 	    (org--backward-paragraph-once))
  20967 	   (t
  20968 	    (goto-char contents-end))))
  20969 	 ;; Move between empty lines in some blocks.
  20970 	 ((and (memq type '(comment-block example-block export-block src-block
  20971 					  verse-block))
  20972 	       (let ((contents-start
  20973 		      (org-with-point-at post-affiliated
  20974 			(line-beginning-position 2))))
  20975 		 (when (> (point) contents-start)
  20976 		   (let ((contents-end
  20977 			  (org-with-point-at end
  20978 			    (skip-chars-backward " \t\n")
  20979 			    (line-beginning-position))))
  20980 		     (if (> (point) contents-end)
  20981 			 (progn (goto-char contents-end) t)
  20982 		       (skip-chars-backward " \t\n" begin)
  20983 		       (re-search-backward "^[ \t]*\n" contents-start :move)
  20984 		       t))))))
  20985 	 ;; Move to element's start.
  20986 	 (t
  20987 	  (funcall reach begin))))))))
  20988 
  20989 (defun org-forward-element ()
  20990   "Move forward by one element.
  20991 Move to the next element at the same level, when possible."
  20992   (interactive)
  20993   (cond ((eobp) (user-error "Cannot move further down"))
  20994 	((org-with-limited-levels (org-at-heading-p))
  20995 	 (let ((origin (point)))
  20996 	   (goto-char (org-end-of-subtree nil t))
  20997 	   (unless (org-with-limited-levels (org-at-heading-p))
  20998 	     (goto-char origin)
  20999 	     (user-error "Cannot move further down"))))
  21000 	(t
  21001 	 (let* ((elem (org-element-at-point))
  21002 		(end (org-element-property :end elem))
  21003 		(parent (org-element-property :parent elem)))
  21004 	   (cond ((and parent (= (org-element-property :contents-end parent) end))
  21005 		  (goto-char (org-element-property :end parent)))
  21006 		 ((integer-or-marker-p end) (goto-char end))
  21007 		 (t (message "No element at point")))))))
  21008 
  21009 (defun org-backward-element ()
  21010   "Move backward by one element.
  21011 Move to the previous element at the same level, when possible."
  21012   (interactive)
  21013   (cond ((bobp) (user-error "Cannot move further up"))
  21014 	((org-with-limited-levels (org-at-heading-p))
  21015 	 ;; At a headline, move to the previous one, if any, or stay
  21016 	 ;; here.
  21017 	 (let ((origin (point)))
  21018 	   (org-with-limited-levels (org-backward-heading-same-level 1))
  21019 	   ;; When current headline has no sibling above, move to its
  21020 	   ;; parent.
  21021 	   (when (= (point) origin)
  21022 	     (or (org-with-limited-levels (org-up-heading-safe))
  21023 		 (progn (goto-char origin)
  21024 			(user-error "Cannot move further up"))))))
  21025 	(t
  21026 	 (let* ((elem (org-element-at-point))
  21027 		(beg (org-element-property :begin elem)))
  21028 	   (cond
  21029 	    ;; Move to beginning of current element if point isn't
  21030 	    ;; there already.
  21031 	    ((null beg) (message "No element at point"))
  21032 	    ((/= (point) beg) (goto-char beg))
  21033 	    (t (goto-char beg)
  21034 	       (skip-chars-backward " \r\t\n")
  21035 	       (unless (bobp)
  21036 		 (let ((prev (org-element-at-point)))
  21037 		   (goto-char (org-element-property :begin prev))
  21038 		   (while (and (setq prev (org-element-property :parent prev))
  21039 			       (<= (org-element-property :end prev) beg))
  21040 		     (goto-char (org-element-property :begin prev)))))))))))
  21041 
  21042 (defun org-up-element ()
  21043   "Move to upper element."
  21044   (interactive)
  21045   (if (org-with-limited-levels (org-at-heading-p))
  21046       (unless (org-up-heading-safe) (user-error "No surrounding element"))
  21047     (let* ((elem (org-element-at-point))
  21048 	   (parent (org-element-property :parent elem)))
  21049       ;; Skip sections
  21050       (when (eq 'section (org-element-type parent))
  21051         (setq parent (org-element-property :parent parent)))
  21052       (if (and parent
  21053                (not (eq (org-element-type parent) 'org-data)))
  21054           (goto-char (org-element-property :begin parent))
  21055 	(if (org-with-limited-levels (org-before-first-heading-p))
  21056 	    (user-error "No surrounding element")
  21057 	  (org-with-limited-levels (org-back-to-heading)))))))
  21058 
  21059 (defun org-down-element ()
  21060   "Move to inner element."
  21061   (interactive)
  21062   (let ((element (org-element-at-point)))
  21063     (cond
  21064      ((memq (org-element-type element) '(plain-list table))
  21065       (goto-char (org-element-property :contents-begin element))
  21066       (forward-char))
  21067      ((memq (org-element-type element) org-element-greater-elements)
  21068       ;; If contents are hidden, first disclose them.
  21069       (when (org-invisible-p (line-end-position)) (org-cycle))
  21070       (goto-char (or (org-element-property :contents-begin element)
  21071 		     (user-error "No content for this element"))))
  21072      (t (user-error "No inner element")))))
  21073 
  21074 (defun org-drag-element-backward ()
  21075   "Move backward element at point."
  21076   (interactive)
  21077   (let ((elem (or (org-element-at-point)
  21078 		  (user-error "No element at point"))))
  21079     (if (eq (org-element-type elem) 'headline)
  21080 	;; Preserve point when moving a whole tree, even if point was
  21081 	;; on blank lines below the headline.
  21082 	(let ((offset (skip-chars-backward " \t\n")))
  21083 	  (unwind-protect (org-move-subtree-up)
  21084 	    (forward-char (- offset))))
  21085       (let ((prev-elem
  21086 	     (save-excursion
  21087 	       (goto-char (org-element-property :begin elem))
  21088 	       (skip-chars-backward " \r\t\n")
  21089 	       (unless (bobp)
  21090 		 (let* ((beg (org-element-property :begin elem))
  21091 			(prev (org-element-at-point))
  21092 			(up prev))
  21093 		   (while (and (setq up (org-element-property :parent up))
  21094 			       (<= (org-element-property :end up) beg))
  21095 		     (setq prev up))
  21096 		   prev)))))
  21097 	;; Error out if no previous element or previous element is
  21098 	;; a parent of the current one.
  21099 	(if (or (not prev-elem) (org-element-nested-p elem prev-elem))
  21100 	    (user-error "Cannot drag element backward")
  21101 	  (let ((pos (point)))
  21102 	    (org-element-swap-A-B prev-elem elem)
  21103 	    (goto-char (+ (org-element-property :begin prev-elem)
  21104 			  (- pos (org-element-property :begin elem))))))))))
  21105 
  21106 (defun org-drag-element-forward ()
  21107   "Move forward element at point."
  21108   (interactive)
  21109   (let* ((pos (point))
  21110 	 (elem (or (org-element-at-point)
  21111 		   (user-error "No element at point"))))
  21112     (when (= (point-max) (org-element-property :end elem))
  21113       (user-error "Cannot drag element forward"))
  21114     (goto-char (org-element-property :end elem))
  21115     (let ((next-elem (org-element-at-point)))
  21116       (when (or (org-element-nested-p elem next-elem)
  21117 		(and (eq (org-element-type next-elem) 'headline)
  21118 		     (not (eq (org-element-type elem) 'headline))))
  21119 	(goto-char pos)
  21120 	(user-error "Cannot drag element forward"))
  21121       ;; Compute new position of point: it's shifted by NEXT-ELEM
  21122       ;; body's length (without final blanks) and by the length of
  21123       ;; blanks between ELEM and NEXT-ELEM.
  21124       (let ((size-next (- (save-excursion
  21125 			    (goto-char (org-element-property :end next-elem))
  21126 			    (skip-chars-backward " \r\t\n")
  21127 			    (forward-line)
  21128 			    ;; Small correction if buffer doesn't end
  21129 			    ;; with a newline character.
  21130 			    (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
  21131 			  (org-element-property :begin next-elem)))
  21132 	    (size-blank (- (org-element-property :end elem)
  21133 			   (save-excursion
  21134 			     (goto-char (org-element-property :end elem))
  21135 			     (skip-chars-backward " \r\t\n")
  21136 			     (forward-line)
  21137 			     (point)))))
  21138 	(org-element-swap-A-B elem next-elem)
  21139 	(goto-char (+ pos size-next size-blank))))))
  21140 
  21141 (defun org-drag-line-forward (arg)
  21142   "Drag the line at point ARG lines forward."
  21143   (interactive "p")
  21144   (dotimes (_ (abs arg))
  21145     (let ((c (current-column)))
  21146       (if (< 0 arg)
  21147 	  (progn
  21148 	    (beginning-of-line 2)
  21149 	    (transpose-lines 1)
  21150 	    (beginning-of-line 0))
  21151 	(transpose-lines 1)
  21152 	(beginning-of-line -1))
  21153       (org-move-to-column c))))
  21154 
  21155 (defun org-drag-line-backward (arg)
  21156   "Drag the line at point ARG lines backward."
  21157   (interactive "p")
  21158   (org-drag-line-forward (- arg)))
  21159 
  21160 (defun org-mark-element ()
  21161   "Put point at beginning of this element, mark at end.
  21162 
  21163 Interactively, if this command is repeated or (in Transient Mark
  21164 mode) if the mark is active, it marks the next element after the
  21165 ones already marked."
  21166   (interactive)
  21167   (let (deactivate-mark)
  21168     (if (and (called-interactively-p 'any)
  21169 	     (or (and (eq last-command this-command) (mark t))
  21170 		 (and transient-mark-mode mark-active)))
  21171 	(set-mark
  21172 	 (save-excursion
  21173 	   (goto-char (mark))
  21174 	   (goto-char (org-element-property :end (org-element-at-point)))
  21175 	   (point)))
  21176       (let ((element (org-element-at-point)))
  21177 	(end-of-line)
  21178 	(push-mark (min (point-max) (org-element-property :end element)) t t)
  21179 	(goto-char (org-element-property :begin element))))))
  21180 
  21181 (defun org-narrow-to-element ()
  21182   "Narrow buffer to current element."
  21183   (interactive)
  21184   (let ((elem (org-element-at-point)))
  21185     (cond
  21186      ((eq (car elem) 'headline)
  21187       (narrow-to-region
  21188        (org-element-property :begin elem)
  21189        (org-element-property :end elem)))
  21190      ((memq (car elem) org-element-greater-elements)
  21191       (narrow-to-region
  21192        (org-element-property :contents-begin elem)
  21193        (org-element-property :contents-end elem)))
  21194      (t
  21195       (narrow-to-region
  21196        (org-element-property :begin elem)
  21197        (org-element-property :end elem))))))
  21198 
  21199 (defun org-transpose-element ()
  21200   "Transpose current and previous elements, keeping blank lines between.
  21201 Point is moved after both elements."
  21202   (interactive)
  21203   (org-skip-whitespace)
  21204   (let ((end (org-element-property :end (org-element-at-point))))
  21205     (org-drag-element-backward)
  21206     (goto-char end)))
  21207 
  21208 (defun org-unindent-buffer ()
  21209   "Un-indent the visible part of the buffer.
  21210 Relative indentation (between items, inside blocks, etc.) isn't
  21211 modified."
  21212   (interactive)
  21213   (unless (eq major-mode 'org-mode)
  21214     (user-error "Cannot un-indent a buffer not in Org mode"))
  21215   (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
  21216 	   (unindent-tree
  21217 	    (lambda (contents)
  21218 	      (dolist (element (reverse contents))
  21219 		(if (memq (org-element-type element) '(headline section))
  21220 		    (funcall unindent-tree (org-element-contents element))
  21221 		  (save-excursion
  21222 		    (save-restriction
  21223 		      (narrow-to-region
  21224 		       (org-element-property :begin element)
  21225 		       (org-element-property :end element))
  21226 		      (org-do-remove-indentation))))))))
  21227     (funcall unindent-tree (org-element-contents parse-tree))))
  21228 
  21229 (defun org-make-options-regexp (kwds &optional extra)
  21230   "Make a regular expression for keyword lines.
  21231 KWDS is a list of keywords, as strings.  Optional argument EXTRA,
  21232 when non-nil, is a regexp matching keywords names."
  21233   (concat "^[ \t]*#\\+\\("
  21234 	  (regexp-opt kwds)
  21235 	  (and extra (concat (and kwds "\\|") extra))
  21236 	  "\\):[ \t]*\\(.*\\)"))
  21237 
  21238 
  21239 ;;; Conveniently switch to Info nodes
  21240 
  21241 (defun org-info-find-node (&optional nodename)
  21242   "Find Info documentation NODENAME or Org documentation according context.
  21243 Started from `gnus-info-find-node'."
  21244   (interactive)
  21245   (Info-goto-node
  21246    (or nodename
  21247        (let ((default-org-info-node "(org) Top"))
  21248          (cond
  21249           ((eq 'org-agenda-mode major-mode) "(org) Agenda Views")
  21250           ((eq 'org-mode major-mode)
  21251            (let* ((context (org-element-at-point))
  21252                   (element-info-nodes ; compare to `org-element-all-elements'.
  21253                    `((babel-call . "(org) Evaluating Code Blocks")
  21254                      (center-block . "(org) Paragraphs")
  21255                      (clock . ,default-org-info-node)
  21256                      (comment . "(org) Comment Lines")
  21257                      (comment-block . "(org) Comment Lines")
  21258                      (diary-sexp . ,default-org-info-node)
  21259                      (drawer . "(org) Drawers")
  21260                      (dynamic-block . "(org) Dynamic Blocks")
  21261                      (example-block . "(org) Literal Examples")
  21262                      (export-block . "(org) ASCII/Latin-1/UTF-8 export")
  21263                      (fixed-width . ,default-org-info-node)
  21264                      (footnote-definition . "(org) Creating Footnotes")
  21265                      (headline . "(org) Document Structure")
  21266                      (horizontal-rule . "(org) Built-in Table Editor")
  21267                      (inlinetask . ,default-org-info-node)
  21268                      (item . "(org) Plain Lists")
  21269                      (keyword . "(org) Per-file keywords")
  21270                      (latex-environment . "(org) LaTeX Export")
  21271                      (node-property . "(org) Properties and Columns")
  21272                      (paragraph . "(org) Paragraphs")
  21273                      (plain-list . "(org) Plain Lists")
  21274                      (planning . "(org) Deadlines and Scheduling")
  21275                      (property-drawer . "(org) Properties and Columns")
  21276                      (quote-block . "(org) Paragraphs")
  21277                      (section . ,default-org-info-node)
  21278                      (special-block . ,default-org-info-node)
  21279                      (src-block . "(org) Working with Source Code")
  21280                      (table . "(org) Tables")
  21281                      (table-row . "(org) Tables")
  21282                      (verse-block . "(org) Paragraphs"))))
  21283              (or (cdr (assoc (car context) element-info-nodes))
  21284                  default-org-info-node)))
  21285           (t default-org-info-node))))))
  21286 
  21287 
  21288 ;;; Finish up
  21289 
  21290 (add-hook 'org-mode-hook     ;remove folds when changing major mode
  21291 	  (lambda () (add-hook 'change-major-mode-hook
  21292 			  'org-fold-show-all 'append 'local)))
  21293 
  21294 (provide 'org)
  21295 
  21296 (run-hooks 'org-load-hook)
  21297 
  21298 ;;; org.el ends here