config

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

org-capture.el (82303B)


      1 ;;; org-capture.el --- Fast note taking in Org       -*- lexical-binding: t; -*-
      2 
      3 ;; Copyright (C) 2010-2024 Free Software Foundation, Inc.
      4 
      5 ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
      6 ;; Keywords: outlines, hypermedia, calendar, text
      7 ;; URL: https://orgmode.org
      8 ;;
      9 ;; This file is part of GNU Emacs.
     10 ;;
     11 ;; GNU Emacs is free software: you can redistribute it and/or modify
     12 ;; it under the terms of the GNU General Public License as published by
     13 ;; the Free Software Foundation, either version 3 of the License, or
     14 ;; (at your option) any later version.
     15 
     16 ;; GNU Emacs is distributed in the hope that it will be useful,
     17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     19 ;; GNU General Public License for more details.
     20 
     21 ;; You should have received a copy of the GNU General Public License
     22 ;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
     23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
     24 ;;
     25 ;;; Commentary:
     26 
     27 ;; This file contains an alternative implementation of the functionality
     28 ;; that used to be provided by org-remember.el.  The implementation is more
     29 ;; streamlined, can produce more target types (e.g. plain list items or
     30 ;; table lines).  Also, it does not use a temporary buffer for editing
     31 ;; the captured entry - instead it uses an indirect buffer that visits
     32 ;; the new entry already in the target buffer (this was an idea by Samuel
     33 ;; Wales).  John Wiegley's excellent `remember.el' is not needed anymore
     34 ;; for this implementation, even though we borrow heavily from its ideas.
     35 
     36 ;; This implementation heavily draws on ideas by James TD Smith and
     37 ;; Samuel Wales, and, of cause, uses John Wiegley's remember.el as inspiration.
     38 
     39 ;;; TODO
     40 
     41 ;; - find a clever way to not always insert an annotation maybe a
     42 ;;   predicate function that can check for conditions for %a to be
     43 ;;   used.  This could be one of the properties.
     44 
     45 ;; - Should there be plist members that arrange for properties to be
     46 ;;   asked for, like James proposed in his RFC?
     47 
     48 ;;; Code:
     49 
     50 (require 'org-macs)
     51 (org-assert-version)
     52 
     53 (require 'cl-lib)
     54 (require 'org)
     55 (require 'org-refile)
     56 
     57 (declare-function org-at-encrypted-entry-p "org-crypt" ())
     58 (declare-function org-at-table-p "org-table" (&optional table-type))
     59 (declare-function org-clock-update-mode-line "org-clock" (&optional refresh))
     60 (declare-function org-datetree-find-date-create "org-datetree" (date &optional keep-restriction))
     61 (declare-function org-datetree-find-month-create "org-datetree" (d &optional keep-restriction))
     62 (declare-function org-decrypt-entry "org-crypt" ())
     63 (declare-function org-element-at-point "org-element" (&optional pom cached-only))
     64 (declare-function org-element-lineage "org-element-ast" (datum &optional types with-self))
     65 (declare-function org-element-property "org-element-ast" (property node))
     66 (declare-function org-element-contents-end "org-element" (node))
     67 (declare-function org-element-post-affiliated "org-element" (node))
     68 (declare-function org-encrypt-entry "org-crypt" ())
     69 (declare-function org-insert-link "ol" (&optional complete-file link-location default-description))
     70 (declare-function org-link-make-string "ol" (link &optional description))
     71 (declare-function org-table-analyze "org-table" ())
     72 (declare-function org-table-current-dline "org-table" ())
     73 (declare-function org-table-fix-formulas "org-table" (key replace &optional limit delta remove))
     74 (declare-function org-table-goto-line "org-table" (N))
     75 
     76 (defvar dired-buffers)
     77 (defvar crm-separator)
     78 (defvar org-end-time-was-given)
     79 (defvar org-keyword-properties)
     80 (defvar org-remember-default-headline)
     81 (defvar org-remember-templates)
     82 (defvar org-store-link-plist)
     83 (defvar org-table-border-regexp)
     84 (defvar org-table-current-begin-pos)
     85 (defvar org-table-dataline-regexp)
     86 (defvar org-table-fix-formulas-confirm)
     87 (defvar org-table-hline-regexp)
     88 (defvar org-table-hlines)
     89 
     90 (defvar org-capture-clock-was-started nil
     91   "Internal flag, keeping marker to the started clock.")
     92 
     93 (defvar org-capture-last-stored-marker (make-marker)
     94   "Marker pointing to the entry most recently stored with `org-capture'.")
     95 
     96 ;; The following variable is scoped dynamically by org-protocol
     97 ;; to indicate that the link properties have already been stored
     98 (defvar org-capture-link-is-already-stored nil)
     99 
    100 (defvar org-capture-is-refiling nil
    101   "Non-nil when capture process is refiling an entry.")
    102 
    103 (defvar org-capture--prompt-history-table (make-hash-table :test #'equal)
    104   "Hash table for all history lists per prompt.")
    105 
    106 (defvar org-capture--prompt-history nil
    107   "History list for prompt placeholders.")
    108 
    109 (defgroup org-capture nil
    110   "Options concerning capturing new entries."
    111   :tag "Org Capture"
    112   :group 'org)
    113 
    114 (defun org-capture-upgrade-templates (templates)
    115   "Update the template list to the new format.
    116 TEMPLATES is a template list, as in `org-capture-templates'.  The
    117 new format unifies all the date/week tree targets into one that
    118 also allows for an optional outline path to specify a target."
    119   (let ((modified-templates
    120 	 (mapcar
    121 	  (lambda (entry)
    122 	    (pcase entry
    123 	      ;; Match templates with an obsolete "tree" target type. Replace
    124 	      ;; it with common `file+olp-datetree'.  Add new properties
    125 	      ;; (i.e., `:time-prompt' and `:tree-type') if needed.
    126 	      (`(,key ,desc ,type (file+datetree . ,path) ,tpl . ,props)
    127 	       `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl ,@props))
    128 	      (`(,key ,desc ,type (file+datetree+prompt . ,path) ,tpl . ,props)
    129 	       `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl
    130 		      :time-prompt t ,@props))
    131 	      (`(,key ,desc ,type (file+weektree . ,path) ,tpl . ,props)
    132 	       `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl
    133 		      :tree-type week ,@props))
    134 	      (`(,key ,desc ,type (file+weektree+prompt . ,path) ,tpl . ,props)
    135 	       `(,key ,desc ,type (file+olp+datetree ,@path) ,tpl
    136 		      :tree-type week :time-prompt t ,@props))
    137 	      ;; Other templates are left unchanged.
    138 	      (_ entry)))
    139 	  templates)))
    140     (unless (equal modified-templates templates)
    141       (message "Deprecated date/weektree capture templates changed to `file+olp+datetree'."))
    142     modified-templates))
    143 
    144 (defcustom org-capture-templates nil
    145   "Templates for the creation of new entries.
    146 
    147 Each entry is a list with the following items:
    148 
    149 keys         The keys that will select the template, as a string, characters
    150              only, for example \"a\" for a template to be selected with a
    151              single key, or \"bt\" for selection with two keys.  When using
    152              several keys, keys using the same prefix key must be together
    153              in the list and preceded by a 2-element entry explaining the
    154              prefix key, for example
    155 
    156                      (\"b\" \"Templates for marking stuff to buy\")
    157 
    158              The \"C\" key is used by default for quick access to the
    159              customization of the template variable.  But if you want to use
    160              that key for a template, you can.
    161 
    162 description  A short string describing the template, will be shown during
    163              selection.
    164 
    165 type         The type of entry.  Valid types are:
    166                entry       an Org node, with a headline.  Will be filed
    167                            as the child of the target entry or as a
    168                            top-level entry.  Its default template is:
    169                              \"* %?\n %a\"
    170                item        a plain list item, will be placed in the
    171                            first plain list at the target location.
    172                            Its default template is:
    173                              \"- %?\"
    174                checkitem   a checkbox item.  This differs from the
    175                            plain list item only in so far as it uses a
    176                            different default template.  Its default
    177                            template is:
    178                              \"- [ ] %?\"
    179                table-line  a new line in the first table at target location.
    180                            Its default template is:
    181                              \"| %? |\"
    182                plain       text to be inserted as it is.
    183 
    184 target       Specification of where the captured item should be placed.
    185              In Org files, targets usually define a node.  Entries will
    186              become children of this node, other types will be added to the
    187              table or list in the body of this node.
    188 
    189              Most target specifications contain a file name.  If that file
    190              name is the empty string, it defaults to `org-default-notes-file'.
    191              A file can also be given as a variable or as a function called
    192              with no argument.  When an absolute path is not specified for a
    193              target, it is taken as relative to `org-directory'.
    194 
    195              Valid values are:
    196 
    197              (file \"path/to/file\")
    198                  Text will be placed at the beginning or end of that file
    199 
    200              (id \"id of existing Org entry\")
    201                  File as child of this entry, or in the body of the entry
    202 
    203              (file+headline \"path/to/file\" \"node headline\")
    204                  Fast configuration if the target heading is unique in the file
    205 
    206              (file+olp \"path/to/file\" \"Level 1 heading\" \"Level 2\" ...)
    207                  For non-unique headings, the full outline path is safer
    208 
    209              (file+regexp  \"path/to/file\" \"regexp to find location\")
    210                  File to the entry matching regexp
    211 
    212              (file+olp+datetree \"path/to/file\" \"Level 1 heading\" ...)
    213                  Will create a heading in a date tree for today's date.
    214                  If no heading is given, the tree will be on top level.
    215                  To prompt for date instead of using TODAY, use the
    216                  :time-prompt property.  To create a week-tree, use the
    217                  :tree-type property.
    218 
    219              (file+function \"path/to/file\" function-finding-location)
    220                  A function to find the right location in the file
    221 
    222              (clock)
    223                 File to the entry that is currently being clocked
    224 
    225              (here)
    226                 The position of point
    227 
    228              (function function-finding-location)
    229                 Most general way: write your own function which both visits
    230                 the file and moves point to the right location
    231 
    232 template     The template for creating the capture item.
    233              If it is an empty string or nil, a default template based on
    234              the entry type will be used (see the \"type\" section above).
    235              Instead of a string, this may also be one of:
    236 
    237                  (file \"/path/to/template-file\")
    238                  (function function-returning-the-template)
    239 
    240              in order to get a template from a file, or dynamically
    241              from a function.
    242 
    243 The rest of the entry is a property list of additional options.  Recognized
    244 properties are:
    245 
    246  :prepend            Normally newly captured information will be appended at
    247                      the target location (last child, last table line,
    248                      last list item...).  Setting this property will
    249                      change that.
    250 
    251  :immediate-finish   When set, do not offer to edit the information, just
    252                      file it away immediately.  This makes sense if the
    253                      template only needs information that can be added
    254                      automatically.
    255 
    256  :jump-to-captured   When set, jump to the captured entry when finished.
    257 
    258  :refile-targets     When exiting capture mode via `org-capture-refile', the
    259                      variable `org-refile-targets' will be temporarily bound
    260                      to the value of this property.
    261 
    262  :empty-lines        Set this to the number of lines that should be inserted
    263                      before and after the new item.  Default 0, only common
    264                      other value is 1.
    265 
    266  :empty-lines-before Set this to the number of lines that should be inserted
    267                      before the new item.  Overrides :empty-lines for the
    268                      number lines inserted before.
    269 
    270  :empty-lines-after  Set this to the number of lines that should be inserted
    271                      after the new item.  Overrides :empty-lines for the
    272                      number of lines inserted after.
    273 
    274  :clock-in           Start the clock in this item.
    275 
    276  :clock-keep         Keep the clock running when filing the captured entry.
    277 
    278  :clock-resume       Start the interrupted clock when finishing the capture.
    279                      Note that :clock-keep has precedence over :clock-resume.
    280                      When setting both to t, the current clock will run and
    281                      the previous one will not be resumed.
    282 
    283  :time-prompt        Prompt for a date/time to be used for date/week trees
    284                      and when filling the template.
    285 
    286  :tree-type          When `week', make a week tree instead of the month-day
    287                      tree.  When `month', make a month tree instead of the
    288                      month-day tree.
    289 
    290  :unnarrowed         Do not narrow the target buffer, simply show the
    291                      full buffer.  Default is to narrow it so that you
    292                      only see the new stuff.
    293 
    294  :table-line-pos     Specification of the location in the table where the
    295                      new line should be inserted.  It should be a string like
    296                      \"II-3\", meaning that the new line should become the
    297                      third line before the second horizontal separator line.
    298 
    299  :kill-buffer        If the target file was not yet visited by a buffer when
    300                      capture was invoked, kill the buffer again after capture
    301                      is finalized.
    302 
    303  :no-save            Do not save the target file after finishing the capture.
    304 
    305  :hook               A nullary function or list of nullary functions run before
    306                      `org-capture-mode-hook' when the template is selected.
    307 
    308  :prepare-finalize   A nullary function or list of nullary functions run before
    309                      `org-capture-prepare-finalize-hook'
    310                      when the template is selected.
    311 
    312  :before-finalize    A nullary function or list of nullary functions run before
    313                      `org-capture-before-finalize-hook'
    314                      when the template is selected.
    315 
    316  :after-finalize     A nullary function or list of nullary functions run before
    317                      `org-capture-after-finalize-hook'
    318                      when the template is selected.
    319 
    320 The template defines the text to be inserted.  Often this is an
    321 Org mode entry (so the first line should start with a star) that
    322 will be filed as a child of the target headline.  It can also be
    323 freely formatted text.  Furthermore, the following %-escapes will
    324 be replaced with content and expanded:
    325 
    326   %[pathname] Insert the contents of the file given by
    327               `pathname'.  These placeholders are expanded at the very
    328               beginning of the process so they can be used to extend the
    329               current template.
    330   %(sexp)     Evaluate elisp `(sexp)' and replace it with the results.
    331               Only placeholders pre-existing within the template, or
    332               introduced with %[pathname] are expanded this way.
    333               Since this happens after expanding non-interactive
    334               %-escapes, those can be used to fill the expression.
    335               The evaluation happens with Org mode set as major mode
    336               in a temporary buffer.
    337   %<...>      The result of `format-time-string' on the ... format
    338               specification.
    339   %t          Time stamp, date only.  The time stamp is the current
    340               time, except when called from agendas with
    341               `\\[org-agenda-capture]' or with
    342               `org-capture-use-agenda-date' set.
    343   %T          Time stamp as above, with date and time.
    344   %u, %U      Like the above, but inactive time stamps.
    345   %i          Initial content, copied from the active region.  If
    346               there is text before %i on the same line, such as
    347               indentation, and %i is not inside a %(sexp), that prefix
    348               will be added before every line in the inserted text.
    349   %a          Annotation, normally the link created with `org-store-link'.
    350   %A          Like %a, but prompt for the description part.
    351   %l          Like %a, but only insert the literal link.
    352   %L          Like %l, but without brackets (the link content itself).
    353   %c          Current kill ring head.
    354   %x          Content of the X clipboard.
    355   %k          Title of currently clocked task.
    356   %K          Link to currently clocked task.
    357   %n          User name (taken from the variable `user-full-name').
    358   %f          File visited by current buffer when `org-capture' was called.
    359   %F          Full path of the file or directory visited by current buffer.
    360   %:keyword   Specific information for certain link types, see below.
    361   %^g         Prompt for tags, with completion on tags in target file.
    362   %^G         Prompt for tags, with completion on all tags in all agenda files.
    363   %^t         Like %t, but prompt for date.  Similarly %^T, %^u, %^U.
    364               You may define a prompt like: %^{Please specify birthday}t.
    365               The default date is that of %t, see above.
    366   %^C         Interactive selection of which kill or clip to use.
    367   %^L         Like %^C, but insert as link.
    368   %^{prop}p   Prompt the user for a value for property `prop'.
    369               A default value can be specified like this:
    370               %^{prop|default}p.
    371   %^{prompt}  Prompt the user for a string and replace this sequence with it.
    372               A default value and a completion table can be specified like this:
    373               %^{prompt|default|completion2|completion3|...}.
    374   %^{prompt}X where X is one of g, G, t, T, u, U, C, or L.
    375               Same as %^X (see above), but also supply custom
    376               prompt/completions.  Default value and completions as in
    377               %^{prompt|default|...}X are allowed.
    378   %?          After completing the template, position cursor here.
    379   %\\1 ... %\\N Insert the text entered at the nth %^{prompt}, where N
    380               is a number, starting from 1.
    381 
    382 Apart from these general escapes, you can access information specific to
    383 the link type that is created.  For example, calling `org-capture' in emails
    384 or in Gnus will record the author and the subject of the message, which you
    385 can access with \"%:from\" and \"%:subject\", respectively.  Here is a
    386 complete list of what is recorded for each link type.
    387 
    388 Link type               |  Available information
    389 ------------------------+------------------------------------------------------
    390 bbdb                    |  %:type %:name %:company
    391 vm, wl, mh, mew, rmail, |  %:type %:subject %:message-id
    392 gnus                    |  %:from %:fromname %:fromaddress
    393                         |  %:to   %:toname   %:toaddress
    394                         |  %:fromto (either \"to NAME\" or \"from NAME\")
    395                         |  %:date %:date-timestamp (as active timestamp)
    396                         |  %:date-timestamp-inactive (as inactive timestamp)
    397 gnus                    |  %:group, for messages also all email fields
    398 eww, w3, w3m            |  %:type %:url
    399 info                    |  %:type %:file %:node
    400 calendar                |  %:type %:date
    401 
    402 When you need to insert a literal percent sign in the template,
    403 you can escape ambiguous cases with a backward slash, e.g., \\%i."
    404   :group 'org-capture
    405   :package-version '(Org . "9.7")
    406   :set (lambda (s v) (set-default-toplevel-value s (org-capture-upgrade-templates v)))
    407   :type
    408   (let ((file-variants '(choice :tag "Filename       "
    409 				(file :tag "Literal")
    410 				(function :tag "Function")
    411 				(variable :tag "Variable"))))
    412     `(repeat
    413       (choice :value ("" "" entry (file "~/org/notes.org") "")
    414 	      (list :tag "Multikey description"
    415 		    (string :tag "Keys       ")
    416 		    (string :tag "Description"))
    417 	      (list :tag "Template entry"
    418 		    (string :tag "Keys           ")
    419 		    (string :tag "Description    ")
    420 		    (choice :tag "Capture Type   " :value entry
    421 			    (const :tag "Org entry" entry)
    422 			    (const :tag "Plain list item" item)
    423 			    (const :tag "Checkbox item" checkitem)
    424 			    (const :tag "Plain text" plain)
    425 			    (const :tag "Table line" table-line))
    426 		    (choice :tag "Target location"
    427 			    (list :tag "File"
    428 				  (const :format "" file)
    429 				  ,file-variants)
    430 			    (list :tag "ID"
    431 				  (const :format "" id)
    432 				  (string :tag "  ID"))
    433 			    (list :tag "File & Headline"
    434 				  (const :format "" file+headline)
    435 				  ,file-variants
    436 				  (string :tag "  Headline"))
    437 			    (list :tag "File & Outline path"
    438 				  (const :format "" file+olp)
    439 				  ,file-variants
    440 				  (repeat :tag "Outline path" :inline t
    441 					  (string :tag "Headline")))
    442 			    (list :tag "File & Regexp"
    443 				  (const :format "" file+regexp)
    444 				  ,file-variants
    445 				  (regexp :tag "  Regexp"))
    446 			    (list :tag "File [ & Outline path ] & Date tree"
    447 				  (const :format "" file+olp+datetree)
    448 				  ,file-variants
    449 				  (option (repeat :tag "Outline path" :inline t
    450 						  (string :tag "Headline"))))
    451 			    (list :tag "File & function"
    452 				  (const :format "" file+function)
    453 				  ,file-variants
    454 				  (function :tag "  Function"))
    455 			    (list :tag "Current clocking task"
    456 				  (const :format "" clock))
    457 			    (list :tag "Function"
    458 				  (const :format "" function)
    459 				  (function :tag "  Function")))
    460 		    (choice :tag "Template       "
    461 			    (string)
    462 			    (list :tag "File"
    463 				  (const :format "" file)
    464 				  (file :tag "Template file"))
    465 			    (list :tag "Function"
    466 				  (const :format "" function)
    467 				  (function :tag "Template function")))
    468 		    (plist :inline t
    469 			   ;; Give the most common options as checkboxes
    470 			   :options (((const :format "%v " :prepend) (const t))
    471 				     ((const :format "%v " :immediate-finish) (const t))
    472 				     ((const :format "%v " :jump-to-captured) (const t))
    473 				     ((const :format "%v " :empty-lines) (const 1))
    474 				     ((const :format "%v " :empty-lines-before) (const 1))
    475 				     ((const :format "%v " :empty-lines-after) (const 1))
    476 				     ((const :format "%v " :clock-in) (const t))
    477 				     ((const :format "%v " :clock-keep) (const t))
    478 				     ((const :format "%v " :clock-resume) (const t))
    479 				     ((const :format "%v " :time-prompt) (const t))
    480 				     ((const :format "%v " :tree-type) (const week))
    481 				     ((const :format "%v " :unnarrowed) (const t))
    482 				     ((const :format "%v " :table-line-pos) (string))
    483 				     ((const :format "%v " :kill-buffer) (const t)))))))))
    484 
    485 (defcustom org-capture-before-finalize-hook nil
    486   "Hook that is run right before a capture process is finalized.
    487 The capture buffer is still current when this hook runs and it is
    488 widened to the entire buffer."
    489   :group 'org-capture
    490   :version "24.1"
    491   :type 'hook)
    492 
    493 (defcustom org-capture-after-finalize-hook nil
    494   "Hook that is run right after a capture process is finalized.
    495 Suitable for window cleanup."
    496   :group 'org-capture
    497   :version "24.1"
    498   :type 'hook)
    499 
    500 (defcustom org-capture-prepare-finalize-hook nil
    501   "Hook that is run before the finalization starts.
    502 The capture buffer is current and still narrowed."
    503   :group 'org-capture
    504   :version "24.1"
    505   :type 'hook)
    506 
    507 ;;; The property list for keeping information about the capture process
    508 
    509 (defvar org-capture-plist nil
    510   "Plist for the current capture process, global, to avoid having to pass it.")
    511 
    512 (defvar org-capture-current-plist nil
    513   "Local variable holding the plist in a capture buffer.
    514 This is used to store the plist for use when finishing a capture process
    515 because another such process might have changed the global variable by then.
    516 
    517 Each time a new capture buffer has been set up, the global `org-capture-plist'
    518 is copied to this variable, which is local in the indirect buffer.")
    519 
    520 (defvar org-capture-clock-keep nil
    521   "Local variable to store the value of the :clock-keep parameter.
    522 This is needed in case `org-capture-finalize' is called interactively.")
    523 
    524 (defun org-capture-put (&rest elements)
    525   "Add ELEMENTS to the capture property list `org-capture-plist'."
    526   (while elements
    527     (setq org-capture-plist (plist-put org-capture-plist
    528 				       (pop elements) (pop elements)))))
    529 (defun org-capture-get (property &optional local)
    530   "Get PROPERTY from the capture property list `org-capture-plist'.
    531 When LOCAL is set, use the local variable `org-capture-current-plist',
    532 this is necessary after initialization of the capture process,
    533 to avoid conflicts with other active capture processes."
    534   (plist-get (if local org-capture-current-plist org-capture-plist) property))
    535 
    536 ;;; The minor mode
    537 
    538 (defvar org-capture-mode-map
    539   (let ((map (make-sparse-keymap)))
    540     (define-key map "\C-c\C-c" #'org-capture-finalize)
    541     (define-key map "\C-c\C-k" #'org-capture-kill)
    542     (define-key map "\C-c\C-w" #'org-capture-refile)
    543     map)
    544   "Keymap for `org-capture-mode', a minor mode.
    545 Use this map to set additional keybindings for when Org mode is used
    546 for a capture buffer.")
    547 
    548 (defvar org-capture-mode-hook nil
    549   "Hook for the `org-capture-mode' minor mode.")
    550 
    551 (define-minor-mode org-capture-mode
    552   "Minor mode for special key bindings in a capture buffer.
    553 
    554 Turning on this mode runs the normal hook `org-capture-mode-hook'."
    555   :lighter " Cap"
    556   (setq-local
    557    header-line-format
    558    (substitute-command-keys
    559     "\\<org-capture-mode-map>Capture buffer.  Finish \
    560 `\\[org-capture-finalize]', refile `\\[org-capture-refile]', \
    561 abort `\\[org-capture-kill]'.")))
    562 
    563 ;;; The main commands
    564 
    565 (defvar org-capture-initial nil)
    566 (defvar org-capture-entry nil)
    567 
    568 ;;;###autoload
    569 (defun org-capture-string (string &optional keys)
    570   "Capture STRING with the template selected by KEYS."
    571   (interactive "sInitial text: \n")
    572   (let ((org-capture-initial string)
    573 	(org-capture-entry (org-capture-select-template keys)))
    574     (org-capture)))
    575 
    576 (defcustom org-capture-templates-contexts nil
    577   "Alist of capture templates and valid contexts.
    578 
    579 For example, if you have a capture template \"c\" and you want
    580 this template to be accessible only from `message-mode' buffers,
    581 use this:
    582 
    583   (setq org-capture-templates-contexts
    584         \\='((\"c\" ((in-mode . \"message-mode\")))
    585             (\"d\" (my-context-function
    586                     (in-mode . \"org-mode\")))))
    587 
    588 Here are the available contexts definitions:
    589 
    590       in-file: command displayed only in matching files
    591       in-mode: command displayed only in matching modes
    592   not-in-file: command not displayed in matching files
    593   not-in-mode: command not displayed in matching modes
    594     in-buffer: command displayed only in matching buffers
    595 not-in-buffer: command not displayed in matching buffers
    596    [function]: a custom function taking no argument
    597 
    598 If you define several checks, the agenda command will be
    599 accessible if there is at least one valid check.
    600 
    601 You can also bind a key to another capture template depending on
    602 contextual rules.
    603 
    604   (setq org-capture-templates-contexts
    605         \\='((\"c\" \"d\" ((in-mode . \"message-mode\")))))
    606 
    607 Here it means: in `message-mode buffers', use \"c\" as the
    608 key for the capture template otherwise associated with \"d\".
    609 \(The template originally associated with \"d\" is not displayed
    610 to avoid duplicates.)"
    611   :version "24.3"
    612   :group 'org-capture
    613   :type '(repeat (list :tag "Rule"
    614 		       (string :tag "        Capture key")
    615 		       (string :tag "Replace by template")
    616 		       (repeat :tag "Available when"
    617 			       (choice
    618 			        (cons :tag "Condition"
    619 				      (choice
    620 				       (const :tag "In file" in-file)
    621 				       (const :tag "Not in file" not-in-file)
    622 				       (const :tag "In buffer" in-buffer)
    623 				       (const :tag "Not in buffer" not-in-buffer)
    624 				       (const :tag "In mode" in-mode)
    625 				       (const :tag "Not in mode" not-in-mode))
    626 				      (regexp))
    627 			        (function :tag "Custom function"))))))
    628 
    629 (defcustom org-capture-use-agenda-date nil
    630   "Non-nil means use the date at point when capturing from agendas.
    631 When nil, you can still capture using the date at point with
    632 `\\[org-agenda-capture]'."
    633   :group 'org-capture
    634   :version "24.3"
    635   :type 'boolean)
    636 
    637 ;;;###autoload
    638 (defun org-capture (&optional goto keys)
    639   "Capture something.
    640 \\<org-capture-mode-map>
    641 This will let you select a template from `org-capture-templates', and
    642 then file the newly captured information.  The text is immediately
    643 inserted at the target location, and an indirect buffer is shown where
    644 you can edit it.  Pressing `\\[org-capture-finalize]' brings you back to the \
    645 previous
    646 state of Emacs, so that you can continue your work.
    647 
    648 When called interactively with a `\\[universal-argument]' prefix argument \
    649 GOTO, don't
    650 capture anything, just go to the file/headline where the selected
    651 template stores its notes.
    652 
    653 With a `\\[universal-argument] \\[universal-argument]' prefix argument, go to \
    654 the last note stored.
    655 
    656 When called with a `C-0' (zero) prefix, insert a template at point.
    657 
    658 When called with a `C-1' (one) prefix, force prompting for a date when
    659 a datetree entry is made.
    660 
    661 ELisp programs can set KEYS to a string associated with a template
    662 in `org-capture-templates'.  In this case, interactive selection
    663 will be bypassed.
    664 
    665 If `org-capture-use-agenda-date' is non-nil, capturing from the
    666 agenda will use the date at point as the default date.  Then, a
    667 `C-1' prefix will tell the capture process to use the HH:MM time
    668 of the day at point (if any) or the current HH:MM time."
    669   (interactive "P")
    670   (when (and org-capture-use-agenda-date
    671 	     (eq major-mode 'org-agenda-mode))
    672     (setq org-overriding-default-time
    673 	  (org-get-cursor-date (equal goto 1))))
    674   (cond
    675    ((equal goto '(4))  (org-capture-goto-target keys))
    676    ((equal goto '(16)) (org-capture-goto-last-stored))
    677    (t
    678     (let* ((orig-buf (current-buffer))
    679 	   (annotation (if (and (boundp 'org-capture-link-is-already-stored)
    680 				org-capture-link-is-already-stored)
    681 			   (plist-get org-store-link-plist :annotation)
    682 			 (ignore-errors (org-store-link nil))))
    683 	   (entry (or org-capture-entry (org-capture-select-template keys)))
    684 	   initial)
    685       (setq initial (or org-capture-initial
    686 			(and (org-region-active-p)
    687 			     (buffer-substring (point) (mark)))))
    688       (when (stringp initial)
    689 	(remove-text-properties 0 (length initial) '(read-only t) initial))
    690       (when (stringp annotation)
    691 	(remove-text-properties 0 (length annotation)
    692 				'(read-only t) annotation))
    693       (cond
    694        ((equal entry "C")
    695 	(customize-variable 'org-capture-templates))
    696        ((equal entry "q")
    697 	(user-error "Abort"))
    698        (t
    699 	(org-capture-set-plist entry)
    700 	(org-capture-get-template)
    701 	(org-capture-put :original-buffer orig-buf
    702 			 :original-file (or (buffer-file-name orig-buf)
    703 					    (and (featurep 'dired)
    704 						 (car (rassq orig-buf
    705 							     dired-buffers))))
    706 			 :original-file-nondirectory
    707 			 (and (buffer-file-name orig-buf)
    708 			      (file-name-nondirectory
    709 			       (buffer-file-name orig-buf)))
    710 			 :annotation annotation
    711 			 :initial initial
    712 			 :return-to-wconf (current-window-configuration)
    713 			 :default-time (or org-overriding-default-time
    714 					   (org-current-time)))
    715 	(org-capture-set-target-location (and (equal goto 0) 'here))
    716 	(condition-case error
    717 	    (org-capture-put :template (org-capture-fill-template))
    718 	  ((error quit)
    719 	   (if (get-buffer "*Capture*") (kill-buffer "*Capture*"))
    720 	   (error "Capture abort: %s" (error-message-string error))))
    721 
    722 	(setq org-capture-clock-keep (org-capture-get :clock-keep))
    723 	(condition-case error
    724 	    (org-capture-place-template
    725 	     (eq (car (org-capture-get :target)) 'function))
    726 	  ((error quit)
    727 	   (when (and (buffer-base-buffer (current-buffer))
    728 		      (string-prefix-p "CAPTURE-" (buffer-name)))
    729 	     (kill-buffer (current-buffer)))
    730 	   (set-window-configuration (org-capture-get :return-to-wconf))
    731 	   (error "Capture template `%s': %s"
    732 		  (org-capture-get :key)
    733 		  (error-message-string error))))
    734 	(when (and (derived-mode-p 'org-mode) (org-capture-get :clock-in))
    735 	  (condition-case nil
    736 	      (progn
    737 		(when (org-clock-is-active)
    738 		  (org-capture-put :interrupted-clock
    739 				   (copy-marker org-clock-marker)))
    740 		(org-clock-in)
    741 		(setq-local org-capture-clock-was-started
    742                             (copy-marker org-clock-marker)))
    743 	    (error "Could not start the clock in this capture buffer")))
    744 	(when (org-capture-get :immediate-finish)
    745 	  (org-capture-finalize))))))))
    746 
    747 (defun org-capture-get-template ()
    748   "Get the template from a file or a function if necessary."
    749   (org-capture-put
    750    :template
    751    (pcase (org-capture-get :template)
    752      (`nil "")
    753      ((and (pred stringp) template) template)
    754      (`(file ,file)
    755       (let ((filename (expand-file-name file org-directory)))
    756 	(if (file-exists-p filename) (org-file-contents filename)
    757 	  (format "* Template file %S not found" file))))
    758      (`(function ,f)
    759       (if (functionp f) (funcall f)
    760 	(format "* Template function %S not found" f)))
    761      (_ "* Invalid capture template"))))
    762 
    763 (defun org-capture--run-template-functions (keyword &optional local)
    764   "Run functions associated with KEYWORD on template's plist.
    765 For valid values of KEYWORD see `org-capture-templates'.
    766 If LOCAL is non-nil use the buffer-local value of `org-capture-plist'."
    767   ;; Used in place of `run-hooks' because these functions have no associated symbol.
    768   ;; They are stored directly on `org-capture-plist'.
    769   (let ((value (org-capture-get keyword local)))
    770     (if (functionp value)
    771         (funcall value)
    772       (mapc #'funcall value))))
    773 
    774 (defun org-capture-finalize (&optional stay-with-capture)
    775   "Finalize the capture process.
    776 With prefix argument STAY-WITH-CAPTURE, jump to the location of the
    777 captured item after finalizing."
    778   (interactive "P")
    779   (when (org-capture-get :jump-to-captured)
    780     (setq stay-with-capture t))
    781   (unless (and org-capture-mode
    782 	       (buffer-base-buffer (current-buffer)))
    783     (error "This does not seem to be a capture buffer for Org mode"))
    784 
    785   (org-capture--run-template-functions :prepare-finalize 'local)
    786   (run-hooks 'org-capture-prepare-finalize-hook)
    787 
    788   ;; Update `org-capture-plist' with the buffer-local value.  Since
    789   ;; captures can be run concurrently, this is to ensure that
    790   ;; `org-capture-after-finalize-hook' accesses the proper plist.
    791   (setq org-capture-plist org-capture-current-plist)
    792 
    793   ;; Did we start the clock in this capture buffer?
    794   (when (and org-capture-clock-was-started
    795 	     (equal org-clock-marker org-capture-clock-was-started))
    796     ;; Looks like the clock we started is still running.
    797     (if org-capture-clock-keep
    798 	;; User may have completed clocked heading from the template.
    799 	;; Refresh clock mode line.
    800 	(org-clock-update-mode-line t)
    801       ;; Clock out.  Possibly resume interrupted clock.
    802       (let (org-log-note-clock-out) (org-clock-out))
    803       (when (and (org-capture-get :clock-resume 'local)
    804 		 (markerp (org-capture-get :interrupted-clock 'local))
    805 		 (buffer-live-p (marker-buffer
    806 				 (org-capture-get :interrupted-clock 'local))))
    807 	(let ((clock-in-task (org-capture-get :interrupted-clock 'local)))
    808 	  (org-with-point-at clock-in-task (org-clock-in)))
    809 	(message "Interrupted clock has been resumed"))))
    810 
    811   (let ((abort-note nil))
    812     ;; Store the size of the capture buffer
    813     (org-capture-put :captured-entry-size (- (point-max) (point-min)))
    814     (widen)
    815     ;; Store the insertion point in the target buffer
    816     (org-capture-put :insertion-point (point))
    817 
    818     (if org-note-abort
    819 	(let ((beg (org-capture-get :begin-marker 'local))
    820 	      (end (org-capture-get :end-marker 'local)))
    821 	  (if (not (and beg end)) (setq abort-note 'dirty)
    822 	    (setq abort-note t)
    823 	    (org-with-wide-buffer (kill-region beg end))))
    824 
    825       ;; Postprocessing:  Update Statistics cookies, do the sorting
    826       (when (derived-mode-p 'org-mode)
    827 	(save-excursion
    828 	  (when (ignore-errors (org-back-to-heading))
    829 	    (org-update-parent-todo-statistics)
    830 	    (org-update-checkbox-count)))
    831 	;; FIXME Here we should do the sorting
    832 	;; If we have added a table line, maybe recompute?
    833 	(when (and (eq (org-capture-get :type 'local) 'table-line)
    834 		   (org-at-table-p))
    835 	  (if (not (org-table-get-stored-formulas)) (org-table-align)
    836 	    ;; Adjust formulas, if necessary.  We assume a non-nil
    837 	    ;; `:immediate-finish' means that no confirmation is
    838 	    ;; required.  Else, obey `org-table-fix-formulas-confirm'.
    839 	    ;;
    840 	    ;; The delta required to fix formulas depends on the
    841 	    ;; number of rows inserted by the template.
    842 	    (when (or (org-capture-get :immediate-finish)
    843 		      (not org-table-fix-formulas-confirm)
    844 		      (funcall org-table-fix-formulas-confirm "Fix formulas? "))
    845 	      (org-table-fix-formulas
    846 	       "@" nil (1- (org-table-current-dline))
    847 	       (count-lines (org-capture-get :begin-marker 'local)
    848 			    (org-capture-get :end-marker 'local))))
    849 	    (org-table-recalculate 'all)))) ;FIXME: should we iterate?
    850       ;; Store this place as the last one where we stored something
    851       ;; Do the marking in the base buffer, so that it makes sense after
    852       ;; the indirect buffer has been killed.
    853       (org-capture-store-last-position)
    854 
    855       (org-capture--run-template-functions :before-finalize 'local)
    856       ;; Run the hook
    857       (run-hooks 'org-capture-before-finalize-hook))
    858 
    859     (when (org-capture-get :decrypted)
    860       (save-excursion
    861 	(goto-char (org-capture-get :decrypted))
    862 	(org-encrypt-entry)))
    863 
    864     (unless (org-capture-get :no-save) (save-buffer))
    865 
    866     (let ((return-wconf (org-capture-get :return-to-wconf 'local))
    867 	  (new-buffer (org-capture-get :new-buffer 'local))
    868 	  (kill-buffer (org-capture-get :kill-buffer 'local))
    869 	  (base-buffer (buffer-base-buffer (current-buffer))))
    870 
    871       ;; Kill the indirect buffer
    872       (kill-buffer (current-buffer))
    873 
    874       ;; Narrow back the target buffer to its previous state
    875       (with-current-buffer (org-capture-get :buffer)
    876         (let ((reg (org-capture-get :initial-target-region))
    877 	      (pos (org-capture-get :initial-target-position))
    878 	      (ipt (org-capture-get :insertion-point))
    879 	      (size (org-capture-get :captured-entry-size)))
    880 	  (if (not reg)
    881 	      (widen)
    882 	    (cond ((< ipt (car reg))
    883 		   ;; insertion point is before the narrowed region
    884 		   (narrow-to-region (+ size (car reg)) (+ size (cdr reg))))
    885 		  ((> ipt (cdr reg))
    886 		   ;; insertion point is after the narrowed region
    887 		   (narrow-to-region (car reg) (cdr reg)))
    888 		  (t
    889 		   ;; insertion point is within the narrowed region
    890 		   (narrow-to-region (car reg) (+ size (cdr reg)))))
    891 	    ;; now place back the point at its original position
    892 	    (if (< ipt (car reg))
    893 		(goto-char (+ size pos))
    894 	      (goto-char (if (< ipt pos) (+ size pos) pos))))))
    895 
    896       (if (and base-buffer org-note-abort new-buffer)
    897           ;; Unconditionally kill the new buffer when capture is
    898           ;; aborted.
    899           (with-current-buffer base-buffer
    900             (set-buffer-modified-p nil)
    901             (kill-buffer))
    902         ;; Kill the target buffer if that is desired
    903         (when (and base-buffer new-buffer kill-buffer)
    904 	  (with-current-buffer base-buffer (save-buffer))
    905 	  (kill-buffer base-buffer)))
    906 
    907       ;; Restore the window configuration before capture
    908       (set-window-configuration return-wconf))
    909 
    910     ;; Do not use the local arg to `org-capture--run-template-functions' here.
    911     ;; The buffer-local value has been stored on `org-capture-plist'.
    912     (org-capture--run-template-functions :after-finalize)
    913     (run-hooks 'org-capture-after-finalize-hook)
    914     ;; Special cases
    915     (cond
    916      (abort-note
    917       (cl-case abort-note
    918 	(clean
    919 	 (message "Capture process aborted and target buffer cleaned up"))
    920 	(dirty
    921 	 (error "Capture process aborted, but target buffer could not be \
    922 cleaned up correctly"))))
    923      (stay-with-capture
    924       (org-capture-goto-last-stored)))
    925     ;; Return if we did store something
    926     (not abort-note)))
    927 
    928 (defun org-capture-refile ()
    929   "Finalize the current capture and then refile the entry.
    930 Refiling is done from the base buffer, because the indirect buffer is then
    931 already gone.  Any prefix argument will be passed to the refile command."
    932   (interactive)
    933   (unless (eq (org-capture-get :type 'local) 'entry)
    934     (user-error "Refiling from a capture buffer makes only sense \
    935 for `entry'-type templates"))
    936   (let* ((base (or (buffer-base-buffer) (current-buffer)))
    937 	 (pos (make-marker))
    938 	 (org-capture-is-refiling t)
    939 	 (kill-buffer (org-capture-get :kill-buffer 'local))
    940 	 (jump-to-captured (org-capture-get :jump-to-captured 'local))
    941 	 (refile-targets (org-capture-get :refile-targets 'local)))
    942     ;; Since `org-capture-finalize' may alter buffer contents (e.g.,
    943     ;; empty lines) around entry, use a marker to refer to the
    944     ;; headline to be refiled.  Place the marker in the base buffer,
    945     ;; as the current indirect one is going to be killed.
    946     (set-marker pos (save-excursion (org-back-to-heading t) (point)) base)
    947     ;; `org-capture-finalize' calls `org-capture-goto-last-stored' too
    948     ;; early.  We want to wait for the refiling to be over, so we
    949     ;; control when the latter function is called.
    950     (org-capture-put :kill-buffer nil :jump-to-captured nil)
    951     (let ((org-refile-targets (or refile-targets org-refile-targets)))
    952       (org-capture-finalize)
    953       (save-window-excursion
    954         (with-current-buffer base
    955 	  (org-with-point-at pos
    956 	    (call-interactively 'org-refile)))))
    957     (when kill-buffer
    958       (with-current-buffer base (save-buffer))
    959       (kill-buffer base))
    960     (when jump-to-captured (org-capture-goto-last-stored))))
    961 
    962 (defun org-capture-kill ()
    963   "Abort the current capture process."
    964   (interactive)
    965   ;; FIXME: This does not do the right thing, we need to remove the
    966   ;; new stuff by hand it is easy: undo, then kill the buffer
    967   (let ((org-note-abort t)
    968 	(org-capture-before-finalize-hook nil))
    969     (org-capture-finalize)))
    970 
    971 (defun org-capture-goto-last-stored ()
    972   "Go to the location where the last capture note was stored."
    973   (interactive)
    974   (org-goto-marker-or-bmk org-capture-last-stored-marker
    975 			  (plist-get org-bookmark-names-plist
    976 				     :last-capture))
    977   (message "This is the last note stored by a capture process"))
    978 
    979 ;;; Supporting functions for handling the process
    980 
    981 (defun org-capture-put-target-region-and-position ()
    982   "Store the initial region with `org-capture-put'."
    983   (org-capture-put
    984    :initial-target-region
    985    ;; Check if the buffer is currently narrowed
    986    (when (org-buffer-narrowed-p)
    987      (cons (point-min) (point-max))))
    988   ;; store the current point
    989   (org-capture-put :initial-target-position (point)))
    990 
    991 (defvar org-time-was-given) ; dynamically scoped parameter
    992 (defun org-capture-set-target-location (&optional target)
    993   "Find TARGET buffer and position.
    994 Store them in the capture property list."
    995   (let ((target-entry-p t))
    996     (save-excursion
    997       (pcase (or target (org-capture-get :target))
    998 	((or `here
    999              `(here))
   1000 	 (org-capture-put :exact-position (point) :insert-here t))
   1001 	(`(file ,path)
   1002 	 (set-buffer (org-capture-target-buffer path))
   1003 	 (org-capture-put-target-region-and-position)
   1004 	 (widen)
   1005 	 (setq target-entry-p nil))
   1006 	(`(id ,(and id (or (pred stringp) (pred symbolp))))
   1007 	 (pcase (org-id-find id)
   1008 	   (`(,path . ,position)
   1009 	    (set-buffer (org-capture-target-buffer path))
   1010 	    (widen)
   1011 	    (org-capture-put-target-region-and-position)
   1012 	    (goto-char position))
   1013 	   (_ (error "Cannot find target ID \"%s\"" id))))
   1014 	(`(file+headline ,path ,(and headline (pred stringp)))
   1015 	 (set-buffer (org-capture-target-buffer path))
   1016 	 ;; Org expects the target file to be in Org mode, otherwise
   1017 	 ;; it throws an error.  However, the default notes files
   1018 	 ;; should work out of the box.  In this case, we switch it to
   1019 	 ;; Org mode.
   1020 	 (unless (derived-mode-p 'org-mode)
   1021 	   (org-display-warning
   1022 	    (format "Capture requirement: switching buffer %S to Org mode"
   1023 		    (current-buffer)))
   1024 	   (org-mode))
   1025 	 (org-capture-put-target-region-and-position)
   1026 	 (widen)
   1027 	 (goto-char (point-min))
   1028 	 (if (re-search-forward (format org-complex-heading-regexp-format
   1029 					(regexp-quote headline))
   1030 				nil t)
   1031 	     (forward-line 0)
   1032 	   (goto-char (point-max))
   1033 	   (unless (bolp) (insert "\n"))
   1034 	   (insert "* " headline "\n")
   1035 	   (forward-line -1)))
   1036 	(`(file+olp ,path . ,(and outline-path (guard outline-path)))
   1037 	 (let ((m (org-find-olp (cons (org-capture-expand-file path)
   1038 				      outline-path))))
   1039 	   (set-buffer (marker-buffer m))
   1040 	   (org-capture-put-target-region-and-position)
   1041 	   (widen)
   1042 	   (goto-char m)
   1043 	   (set-marker m nil)))
   1044 	(`(file+regexp ,path ,(and regexp (pred stringp)))
   1045 	 (set-buffer (org-capture-target-buffer path))
   1046 	 (org-capture-put-target-region-and-position)
   1047 	 (widen)
   1048 	 (goto-char (point-min))
   1049 	 (if (not (re-search-forward regexp nil t))
   1050 	     (error "No match for target regexp in file %s" path)
   1051 	   (goto-char (if (org-capture-get :prepend)
   1052 			  (match-beginning 0)
   1053 			(match-end 0)))
   1054 	   (org-capture-put :exact-position (point))
   1055 	   (setq target-entry-p
   1056 		 (and (derived-mode-p 'org-mode) (org-at-heading-p)))))
   1057 	(`(file+olp+datetree ,path . ,outline-path)
   1058 	 (let ((m (if outline-path
   1059 		      (org-find-olp (cons (org-capture-expand-file path)
   1060 					  outline-path))
   1061 		    (set-buffer (org-capture-target-buffer path))
   1062 		    (point-marker))))
   1063 	   (set-buffer (marker-buffer m))
   1064 	   (org-capture-put-target-region-and-position)
   1065 	   (widen)
   1066 	   (goto-char m)
   1067 	   (set-marker m nil)
   1068 	   (require 'org-datetree)
   1069 	   (org-capture-put-target-region-and-position)
   1070 	   (widen)
   1071 	   ;; Make a date/week tree entry, with the current date (or
   1072 	   ;; yesterday, if we are extending dates for a couple of
   1073 	   ;; hours)
   1074 	   (funcall
   1075 	    (pcase (org-capture-get :tree-type)
   1076 	      (`week #'org-datetree-find-iso-week-create)
   1077 	      (`month #'org-datetree-find-month-create)
   1078 	      (_ #'org-datetree-find-date-create))
   1079 	    (calendar-gregorian-from-absolute
   1080 	     (cond
   1081 	      (org-overriding-default-time
   1082 	       ;; Use the overriding default time.
   1083 	       (time-to-days org-overriding-default-time))
   1084 	      ((or (org-capture-get :time-prompt)
   1085 		   (equal current-prefix-arg 1))
   1086                ;; Prompt for date.  Bind `org-end-time-was-given' so
   1087                ;; that `org-read-date-analyze' handles the time range
   1088                ;; case and returns `prompt-time' with the start value.
   1089                (let* ((org-time-was-given nil)
   1090                       (org-end-time-was-given nil)
   1091                       (prompt-time (org-read-date
   1092 				    nil t nil "Date for tree entry:")))
   1093 		 (org-capture-put
   1094 		  :default-time
   1095                   (if (or org-time-was-given
   1096                           (= (time-to-days prompt-time) (org-today)))
   1097                       prompt-time
   1098                     ;; Use 00:00 when no time is given for another
   1099                     ;; date than today?
   1100                     (org-encode-time
   1101                      (apply #'list
   1102                             0 0 org-extend-today-until
   1103                             (cl-cdddr (decode-time prompt-time))))))
   1104 		 (time-to-days prompt-time)))
   1105 	      (t
   1106 	       ;; Current date, possibly corrected for late night
   1107 	       ;; workers.
   1108 	       (org-today))))
   1109 	    ;; the following is the keep-restriction argument for
   1110 	    ;; org-datetree-find-date-create
   1111 	    (when outline-path 'subtree-at-point))))
   1112 	(`(file+function ,path ,(and function (pred functionp)))
   1113 	 (set-buffer (org-capture-target-buffer path))
   1114 	 (org-capture-put-target-region-and-position)
   1115 	 (widen)
   1116 	 (funcall function)
   1117 	 (org-capture-put :exact-position (point))
   1118 	 (setq target-entry-p
   1119 	       (and (derived-mode-p 'org-mode) (org-at-heading-p))))
   1120 	(`(function ,(and fun (pred functionp)))
   1121 	 (funcall fun)
   1122 	 (org-capture-put :exact-position (point))
   1123 	 (setq target-entry-p
   1124 	       (and (derived-mode-p 'org-mode) (org-at-heading-p))))
   1125 	(`(clock)
   1126 	 (if (and (markerp org-clock-hd-marker)
   1127 		  (marker-buffer org-clock-hd-marker))
   1128 	     (progn (set-buffer (marker-buffer org-clock-hd-marker))
   1129 		    (org-capture-put-target-region-and-position)
   1130 		    (widen)
   1131 		    (goto-char org-clock-hd-marker))
   1132 	   (user-error "No running clock that could be used as capture target")))
   1133 	(target (error "Invalid capture target specification: %S" target)))
   1134 
   1135       (org-capture-put :buffer (current-buffer)
   1136 		       :pos (point)
   1137 		       :target-entry-p target-entry-p
   1138 		       :decrypted
   1139 		       (and (featurep 'org-crypt)
   1140 			    (org-at-encrypted-entry-p)
   1141 			    (save-excursion
   1142 			      (org-decrypt-entry)
   1143 			      (and (org-back-to-heading t) (point))))))))
   1144 
   1145 (defun org-capture-expand-file (file)
   1146   "Expand functions, symbols and file names for FILE.
   1147 When FILE is a function, call it.  When it is a form, evaluate
   1148 it.  When it is a variable, return its value.  When it is
   1149 a string, treat it as a file name, possibly expanding it
   1150 according to `org-directory', and return it.  If it is the empty
   1151 string, however, return `org-default-notes-file'.  In any other
   1152 case, raise an error."
   1153   (let ((location (cond ((equal file "") org-default-notes-file)
   1154 			((stringp file) (expand-file-name file org-directory))
   1155 			((functionp file) (funcall file))
   1156 			((and (symbolp file) (boundp file)) (symbol-value file))
   1157 			(t nil))))
   1158     (or (org-string-nw-p location)
   1159 	(error "Invalid file location: %S" location))))
   1160 
   1161 (defun org-capture-target-buffer (file)
   1162   "Get a buffer for FILE.
   1163 FILE is a generalized file location, as handled by
   1164 `org-capture-expand-file'."
   1165   (let ((file (org-capture-expand-file file)))
   1166     (or (org-find-base-buffer-visiting file)
   1167 	(progn (org-capture-put :new-buffer t)
   1168 	       (find-file-noselect file)))))
   1169 
   1170 (defun org-capture-place-template (&optional inhibit-wconf-store)
   1171   "Insert the template at the target location, and display the buffer.
   1172 When INHIBIT-WCONF-STORE is non-nil, don't store the window configuration, as it
   1173 may have been stored before."
   1174   (unless inhibit-wconf-store
   1175     (org-capture-put :return-to-wconf (current-window-configuration)))
   1176   (pop-to-buffer
   1177    (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE")
   1178    '(org-display-buffer-split))
   1179   (widen)
   1180   (org-fold-show-all)
   1181   (goto-char (org-capture-get :pos))
   1182   (setq-local outline-level 'org-outline-level)
   1183   (pcase (org-capture-get :type)
   1184     ((or `nil `entry) (org-capture-place-entry))
   1185     (`table-line (org-capture-place-table-line))
   1186     (`plain (org-capture-place-plain-text))
   1187     (`item (org-capture-place-item))
   1188     (`checkitem (org-capture-place-item)))
   1189   (setq-local org-capture-current-plist org-capture-plist)
   1190   (org-capture--run-template-functions :hook 'local)
   1191   (org-capture-mode 1))
   1192 
   1193 (defun org-capture-place-entry ()
   1194   "Place the template as a new Org entry."
   1195   (let ((template (org-capture-get :template))
   1196 	(reversed? (org-capture-get :prepend))
   1197 	(exact-position (org-capture-get :exact-position))
   1198 	(insert-here? (org-capture-get :insert-here))
   1199 	(level 1))
   1200     (org-capture-verify-tree template)
   1201     (when exact-position (goto-char exact-position))
   1202     (cond
   1203      ;; Force insertion at point.
   1204      (insert-here?
   1205       ;; FIXME: level should probably set directly within (let ...).
   1206       (setq level (org-get-valid-level
   1207                    (if (or (org-at-heading-p)
   1208                            (ignore-errors
   1209 			     (save-excursion (org-back-to-heading t))))
   1210                        (org-outline-level)
   1211                      1))))
   1212      ;; Insert as a child of the current entry.
   1213      ((org-capture-get :target-entry-p)
   1214       (setq level (org-get-valid-level
   1215 		   (if (org-at-heading-p) (org-outline-level) 1)
   1216 		   1))
   1217       (if reversed? (outline-next-heading) (org-end-of-subtree t t)))
   1218      ;; Insert as a top-level entry at the beginning of the file.
   1219      (reversed?
   1220       (goto-char (point-min))
   1221       (unless (org-at-heading-p) (outline-next-heading)))
   1222      ;; Otherwise, insert as a top-level entry at the end of the file.
   1223      (t (goto-char (point-max))
   1224         ;; Make sure that last point is not folded.
   1225         (org-fold-core-cycle-over-indirect-buffers
   1226           (org-fold-region (max 1 (1- (point-max))) (point-max) nil))))
   1227     (let ((origin (point-marker)))
   1228       (unless (bolp) (insert "\n"))
   1229       (org-capture-empty-lines-before)
   1230       (let ((beg (point)))
   1231 	(save-restriction
   1232 	  (when insert-here? (narrow-to-region beg beg))
   1233 	  (org-paste-subtree level template 'for-yank))
   1234 	(org-capture-position-for-last-stored beg)
   1235 	(org-capture-empty-lines-after)
   1236 	(unless (org-at-heading-p) (outline-next-heading))
   1237 	(org-capture-mark-kill-region origin (point))
   1238 	(org-capture-narrow beg (if (eobp) (point) (1- (point))))
   1239 	(org-capture--position-cursor beg (point))))))
   1240 
   1241 (defun org-capture-place-item ()
   1242   "Place the template as a new plain list item."
   1243   (let ((prepend? (org-capture-get :prepend))
   1244 	(template (org-remove-indentation (org-capture-get :template)))
   1245 	item)
   1246     ;; Make template suitable for insertion.  In particular, add
   1247     ;; a main bullet if it is missing.
   1248     (unless (string-match-p (concat "\\`" (org-item-re)) template)
   1249       (setq template (concat "- " (mapconcat #'identity
   1250 					     (split-string template "\n")
   1251 					     "\n  "))))
   1252     ;; Delimit the area where we should look for a plain list.
   1253     (pcase-let ((`(,beg . ,end)
   1254 		 (cond ((org-capture-get :exact-position)
   1255 			;; User gave a specific position.  Start
   1256 			;; looking for lists from here.
   1257 			(org-with-point-at (org-capture-get :exact-position)
   1258 			  (cons (line-beginning-position)
   1259 				(if (org-capture-get :insert-here)
   1260 				    (line-beginning-position)
   1261 				  (org-entry-end-position)))))
   1262 		       ((org-capture-get :target-entry-p)
   1263 			;; At a heading, limit search to its body.
   1264 			(cons (line-beginning-position 2)
   1265 			      (org-entry-end-position)))
   1266 		       (t
   1267 			;; Table is not necessarily under a heading.
   1268 			;; Search whole buffer.
   1269 			(cons (point-min) (point-max))))))
   1270       ;; Find the first plain list in the delimited area.
   1271       (goto-char beg)
   1272       (let ((item-regexp (org-item-beginning-re)))
   1273 	(catch :found
   1274 	  (while (re-search-forward item-regexp end t)
   1275 	    (when (setq item (org-element-lineage
   1276 			      (org-element-at-point) 'plain-list t))
   1277 	      (goto-char (org-element-property (if prepend? :post-affiliated
   1278 						 :contents-end)
   1279 					       item))
   1280 	      (throw :found t)))
   1281 	  ;; No list found.  Move to the location when to insert
   1282 	  ;; template.  Skip planning info and properties drawers, if
   1283 	  ;; any.
   1284 	  (goto-char (cond ((org-capture-get :insert-here) beg)
   1285 			   ((not prepend?) end)
   1286 			   ((org-before-first-heading-p) beg)
   1287 			   (t (max (save-excursion
   1288 				     (org-end-of-meta-data)
   1289 				     (point))
   1290 				   beg)))))))
   1291     ;; Insert template.
   1292     (let ((origin (point-marker)))
   1293       (unless (bolp) (insert "\n"))
   1294       ;; When a new list is created, always obey to `:empty-lines' and
   1295       ;; friends.
   1296       ;;
   1297       ;; When capturing in an existing list, do not change blank lines
   1298       ;; above or below the list; consider it to be a stable
   1299       ;; structure.  However, we can control how many blank lines
   1300       ;; separate items.  So obey to `:empty-lines' between items as
   1301       ;; long as it does not insert more than one empty line.  In the
   1302       ;; specific case of empty lines above, it means we only obey the
   1303       ;; parameter when appending an item.
   1304       (unless (and item prepend?)
   1305 	(org-capture-empty-lines-before
   1306 	 (and item
   1307 	      (not prepend?)
   1308 	      (min 1 (or (org-capture-get :empty-lines-before)
   1309 			 (org-capture-get :empty-lines)
   1310 			 0)))))
   1311       (org-capture-position-for-last-stored (point))
   1312       (let ((beg (line-beginning-position))
   1313 	    (end (progn
   1314 		   (insert (org-trim template) "\n")
   1315 		   (point-marker))))
   1316 	(when item
   1317 	  (let ((i (save-excursion
   1318 		     (goto-char (org-element-post-affiliated item))
   1319 		     (org-current-text-indentation))))
   1320 	    (save-excursion
   1321 	      (goto-char beg)
   1322 	      (save-excursion
   1323 		(while (< (point) end)
   1324 		  (indent-to i)
   1325 		  (forward-line)))
   1326 	      ;; Prepending an item could change the type of the list
   1327 	      ;; if there is a mismatch.  In this situation,
   1328 	      ;; prioritize the existing list.
   1329 	      (when prepend?
   1330 		(let ((ordered? (eq 'ordered (org-element-property :type item))))
   1331 		  (when (org-xor ordered?
   1332 				 (string-match-p "\\`[A-Za-z0-9]\\([.)]\\)"
   1333 						 template))
   1334 		    (org-cycle-list-bullet (if ordered? "1." "-")))))
   1335 	      ;; Eventually repair the list for proper indentation and
   1336 	      ;; bullets.
   1337 	      (org-list-repair))))
   1338 	;; Limit number of empty lines.  See above for details.
   1339 	(unless (and item (not prepend?))
   1340 	  (org-capture-empty-lines-after
   1341 	   (and item
   1342 		prepend?
   1343 		(min 1 (or (org-capture-get :empty-lines-after)
   1344 			   (org-capture-get :empty-lines)
   1345 			   0)))))
   1346 	(org-capture-mark-kill-region origin (point))
   1347 	;; ITEM always end with a newline character.  Make sure we do
   1348 	;; not narrow at the beginning of the next line, possibly
   1349 	;; altering its structure (e.g., when it is a headline).
   1350 	(org-capture-narrow beg (1- end))
   1351 	(org-capture--position-cursor beg end)))))
   1352 
   1353 (defun org-capture-place-table-line ()
   1354   "Place the template as a table line."
   1355   (require 'org-table)
   1356   (let ((text
   1357 	 (pcase (org-trim (org-capture-get :template))
   1358 	   ((pred (string-match-p org-table-border-regexp))
   1359 	    "| %?Bad template |")
   1360 	   (text (concat text "\n"))))
   1361 	(table-line-pos (org-capture-get :table-line-pos))
   1362 	beg end)
   1363     (cond
   1364      ((org-capture-get :exact-position)
   1365       (org-with-point-at (org-capture-get :exact-position)
   1366 	(setq beg (line-beginning-position))
   1367 	(setq end (if (org-capture-get :insert-here) beg
   1368 		    (org-entry-end-position)))))
   1369      ((not (org-capture-get :target-entry-p))
   1370       ;; Table is not necessarily under a heading.  Find first table
   1371       ;; in the buffer.
   1372       (setq beg (point-min) end (point-max)))
   1373      (t
   1374       ;; We are at a heading, limit search to the body.
   1375       (setq beg (line-beginning-position 2))
   1376       (setq end (save-excursion (outline-next-heading) (point)))))
   1377     (goto-char beg)
   1378     ;; Narrow to the table, possibly creating one if necessary.
   1379     (catch :found
   1380       (while (re-search-forward org-table-dataline-regexp end t)
   1381 	(pcase (org-element-lineage (org-element-at-point) 'table t)
   1382 	  (`nil nil)
   1383 	  ((pred (lambda (e) (eq 'table.el (org-element-property :type e))))
   1384 	   nil)
   1385 	  (table
   1386 	   (goto-char (org-element-contents-end table))
   1387 	   (narrow-to-region (org-element-post-affiliated table)
   1388 			     (point))
   1389 	   (throw :found t))))
   1390       ;; No table found.  Create it with an empty header.
   1391       (goto-char end)
   1392       (unless (bolp) (insert "\n"))
   1393       (let ((origin (point-marker)))
   1394 	(insert "|   |\n|---|\n")
   1395 	(narrow-to-region origin (point))))
   1396     ;; In the current table, find the appropriate location for TEXT.
   1397     (cond
   1398      ((org-capture-get :insert-here) nil)
   1399      ((and table-line-pos
   1400 	   (string-match "\\(I+\\)\\([-+][0-9]+\\)" table-line-pos))
   1401       (goto-char (point-min))
   1402       (let ((line
   1403 	     (condition-case _
   1404 		 (progn
   1405 		   (save-match-data (org-table-analyze))
   1406 		   (aref org-table-hlines
   1407 			 (- (match-end 1) (match-beginning 1))))
   1408 	       (error
   1409 		(error "Invalid table line specification %S" table-line-pos))))
   1410 	    (delta (string-to-number (match-string 2 table-line-pos))))
   1411 	(forward-line (+ line delta (if (< delta 0) 0 -1)))
   1412 	(forward-line)))		;insert below
   1413      ((org-capture-get :prepend)
   1414       (goto-char (point-min))
   1415       (cond
   1416        ((not (re-search-forward org-table-hline-regexp nil t)))
   1417        ((re-search-forward org-table-dataline-regexp nil t) (forward-line 0))
   1418        (t (goto-char (org-table-end)))))
   1419      (t
   1420       (goto-char (org-table-end))))
   1421     ;; Insert text and position point according to template.
   1422     (let ((origin (point-marker)))
   1423       (unless (bolp) (insert "\n"))
   1424       (let ((beg (point))
   1425 	    (end (save-excursion
   1426 		   (insert text)
   1427 		   (point))))
   1428 	(org-capture-position-for-last-stored 'table-line)
   1429 	(org-capture-mark-kill-region origin end)
   1430 	;; TEXT is guaranteed to end with a newline character.  Ignore
   1431 	;; it when narrowing so as to not alter data on the next line.
   1432 	(org-capture-narrow beg (1- end))
   1433 	(org-capture--position-cursor beg (1- end))))))
   1434 
   1435 (defun org-capture-place-plain-text ()
   1436   "Place the template plainly.
   1437 If the target locator points at an Org node, place the template into
   1438 the text of the entry, before the first child.  If not, place the
   1439 template at the beginning or end of the file.
   1440 Of course, if exact position has been required, just put it there."
   1441   (cond
   1442    ((org-capture-get :exact-position)
   1443     (goto-char (org-capture-get :exact-position)))
   1444    ((org-capture-get :target-entry-p)
   1445     ;; Place the text into this entry.
   1446     (if (org-capture-get :prepend)
   1447 	;; Skip meta data and drawers.
   1448 	(org-end-of-meta-data t)
   1449       ;; Go to end of the entry text, before the next headline.
   1450       (outline-next-heading)))
   1451    (t
   1452     ;; Beginning or end of file.
   1453     (goto-char (if (org-capture-get :prepend) (point-min) (point-max)))))
   1454   (let ((origin (point-marker)))
   1455     (unless (bolp) (insert "\n"))
   1456     (org-capture-empty-lines-before)
   1457     (org-capture-position-for-last-stored (point))
   1458     (let ((beg (point)))
   1459       (insert (org-capture-get :template))
   1460       (unless (bolp) (insert "\n"))
   1461       ;; Ignore the final newline character so as to not alter data
   1462       ;; after inserted text.  Yet, if the template is empty, make
   1463       ;; sure END matches BEG instead of pointing before it.
   1464       (let ((end (max beg (1- (point)))))
   1465 	(org-capture-empty-lines-after)
   1466 	(org-capture-mark-kill-region origin (point))
   1467 	(org-capture-narrow beg end)
   1468 	(org-capture--position-cursor beg end)))))
   1469 
   1470 (defun org-capture-mark-kill-region (beg end)
   1471   "Mark region between BEG and END to be killed on aborted capture."
   1472   (let ((m1 (copy-marker beg))
   1473 	(m2 (copy-marker end t)))
   1474     (org-capture-put :begin-marker m1)
   1475     (org-capture-put :end-marker m2)))
   1476 
   1477 (defun org-capture-position-for-last-stored (position)
   1478   "Put POSITION on `org-capture-plist' for future use as `last capture`."
   1479   (cond
   1480    ((integerp position)
   1481     (org-capture-put :position-for-last-stored
   1482 		     (move-marker (make-marker) position
   1483 				  (or (buffer-base-buffer (current-buffer))
   1484 				      (current-buffer)))))
   1485    ((eq position 'table-line)
   1486     (org-capture-put :position-for-last-stored
   1487 		     (list 'table-line
   1488 			   (org-table-current-dline))))
   1489    (t (error "This should not happen"))))
   1490 
   1491 (defun org-capture-store-last-position ()
   1492   "Store the last-captured position."
   1493   (let* ((where (org-capture-get :position-for-last-stored 'local))
   1494 	 (pos (cond
   1495 	       ((markerp where)
   1496 		(prog1 (marker-position where)
   1497 		  (move-marker where nil)))
   1498 	       ((and (listp where) (eq (car where) 'table-line))
   1499 		(if (org-at-table-p)
   1500 		    (save-excursion
   1501 		      (org-table-goto-line (nth 1 where))
   1502                       (line-beginning-position))
   1503 		  (point))))))
   1504     (with-current-buffer (buffer-base-buffer (current-buffer))
   1505       (org-with-point-at pos
   1506         ;; FIXME: `org-capture-bookmark' is obsolete.  To be removed
   1507         ;; in future Org releases.
   1508 	(when (with-no-warnings org-capture-bookmark)
   1509 	  (let ((bookmark (plist-get org-bookmark-names-plist :last-capture)))
   1510 	    (when bookmark
   1511               (condition-case err
   1512 	          (bookmark-set bookmark)
   1513                 (error
   1514                  (message "Bookmark set error: %S" err))))))
   1515 	(move-marker org-capture-last-stored-marker (point))))))
   1516 
   1517 (defun org-capture-narrow (beg end)
   1518   "Possibly narrow to region between BEG and END.
   1519 If configuration contains non-nil :unnarrowed property, do not narrow."
   1520   (unless (org-capture-get :unnarrowed)
   1521     (narrow-to-region beg end)))
   1522 
   1523 (defun org-capture--position-cursor (beg end)
   1524   "Move point to first \"%?\" location or at start of template.
   1525 BEG and END are buffer positions at the beginning and end position
   1526 of the template."
   1527   (goto-char beg)
   1528   (when (search-forward "%?" end t)
   1529     (replace-match "")))
   1530 
   1531 (defun org-capture-empty-lines-before (&optional n)
   1532   "Insert N empty lines before the insertion point.
   1533 Point will be after the empty lines, so insertion can directly be done.
   1534 If N is nil, :empty-lines-before or :empty-lines are considered."
   1535   (setq n (or n (org-capture-get :empty-lines-before)
   1536 	      (org-capture-get :empty-lines) 0))
   1537   (let ((pos (point)))
   1538     (org-back-over-empty-lines)
   1539     (delete-region (point) pos)
   1540     (when (> n 0) (newline n))))
   1541 
   1542 (defun org-capture-empty-lines-after (&optional n)
   1543   "Set the correct number of empty lines after the inserted string.
   1544 Point will remain at the first line after the inserted text.
   1545 If N is nil, :empty-lines-after or :empty-lines are considered."
   1546   (setq n (or n (org-capture-get :empty-lines-after)
   1547 	      (org-capture-get :empty-lines) 0))
   1548   (org-back-over-empty-lines)
   1549   (while (looking-at "[ \t]*\n") (replace-match ""))
   1550   (let ((pos (point)))
   1551     (when (> n 0) (newline n))
   1552     (goto-char pos)))
   1553 
   1554 (defvar org-clock-marker) ; Defined in org.el
   1555 
   1556 (defun org-capture-set-plist (entry)
   1557   "Initialize the property list for ENTRY from the template definition."
   1558   (setq org-capture-plist (copy-sequence (nthcdr 5 entry)))
   1559   (org-capture-put :key (car entry) :description (nth 1 entry)
   1560 		   :target (nth 3 entry))
   1561   (let ((txt (nth 4 entry)) (type (or (nth 2 entry) 'entry)))
   1562     (when (or (not txt) (and (stringp txt) (not (string-match "\\S-" txt))))
   1563       ;; The template may be empty or omitted for special types.
   1564       ;; Here we insert the default templates for such cases.
   1565       (cond
   1566        ((eq type 'item) (setq txt "- %?"))
   1567        ((eq type 'checkitem) (setq txt "- [ ] %?"))
   1568        ((eq type 'table-line) (setq txt "| %? |"))
   1569        ((member type '(nil entry)) (setq txt "* %?\n  %a"))))
   1570     (org-capture-put :template txt :type type)))
   1571 
   1572 (defun org-capture-goto-target (&optional template-key)
   1573   "Go to the target location of a capture template.
   1574 If TEMPLATE-KEY is nil, the user is queried for the template."
   1575   (interactive)
   1576   (let ((entry (org-capture-select-template template-key)))
   1577     (unless entry (error "No capture template selected"))
   1578     (org-capture-set-plist entry)
   1579     (org-capture-set-target-location)
   1580     (pop-to-buffer-same-window (org-capture-get :buffer))
   1581     (goto-char (org-capture-get :pos))))
   1582 
   1583 (defun org-capture-get-indirect-buffer (&optional buffer prefix)
   1584   "Make an indirect BUFFER for a capture process.
   1585 Use PREFIX as a prefix for the name of the indirect buffer."
   1586   (setq buffer (or buffer (current-buffer)))
   1587   (let ((n 1) (base (buffer-name buffer)) bname)
   1588     (setq bname (concat prefix "-" base))
   1589     (while (buffer-live-p (get-buffer bname))
   1590       (setq bname (concat prefix "-" (number-to-string (cl-incf n)) "-" base)))
   1591     (condition-case nil
   1592         (make-indirect-buffer buffer bname 'clone)
   1593       (error
   1594        (let ((buf (make-indirect-buffer buffer bname)))
   1595 	 (with-current-buffer buf (org-mode))
   1596 	 buf)))))
   1597 
   1598 (defun org-capture-verify-tree (tree)
   1599   "Throw error if TREE is not a valid tree."
   1600   (unless (org-kill-is-subtree-p tree)
   1601     (error "Template is not a valid Org entry or tree")))
   1602 
   1603 ;;; The template code
   1604 (defun org-capture-select-template (&optional keys)
   1605   "Select a capture template.
   1606 Lisp programs can force the template by setting KEYS to a string."
   1607   (let ((org-capture-templates
   1608 	 (or (org-contextualize-keys
   1609 	      (org-capture-upgrade-templates org-capture-templates)
   1610 	      org-capture-templates-contexts)
   1611 	     '(("t" "Task" entry (file+headline "" "Tasks")
   1612 		"* TODO %?\n  %u\n  %a")))))
   1613     (if keys
   1614 	(or (assoc keys org-capture-templates)
   1615 	    (error "No capture template referred to by \"%s\" keys" keys))
   1616       (org-mks org-capture-templates
   1617 	       "Select a capture template\n========================="
   1618 	       "Template key: "
   1619 	       '(("C" "Customize org-capture-templates")
   1620 		 ("q" "Abort"))))))
   1621 
   1622 (defvar org-capture--clipboards nil
   1623   "List various clipboards values.")
   1624 
   1625 (defun org-capture-fill-template (&optional template initial annotation)
   1626   "Fill a TEMPLATE and return the filled template as a string.
   1627 The template may still contain \"%?\" for cursor positioning.
   1628 INITIAL content and/or ANNOTATION may be specified, but will be overridden
   1629 by their respective `org-store-link-plist' properties if present.
   1630 
   1631 Expansion occurs in a temporary Org mode buffer."
   1632   (let* ((template (or template (org-capture-get :template)))
   1633 	 (buffer (org-capture-get :buffer))
   1634 	 (file (buffer-file-name (or (buffer-base-buffer buffer) buffer)))
   1635 	 (time (let* ((c (or (org-capture-get :default-time) (current-time)))
   1636 		      (d (decode-time c)))
   1637 		 (if (< (nth 2 d) org-extend-today-until)
   1638 		     (org-encode-time 0 59 23 (1- (nth 3 d)) (nth 4 d) (nth 5 d))
   1639 		   c)))
   1640 	 (v-t (format-time-string (org-time-stamp-format nil) time))
   1641 	 (v-T (format-time-string (org-time-stamp-format t) time))
   1642 	 (v-u (format-time-string (org-time-stamp-format nil t) time))
   1643 	 (v-U (format-time-string (org-time-stamp-format t t) time))
   1644 	 (v-c (and kill-ring (current-kill 0)))
   1645 	 (v-x (or (org-get-x-clipboard 'PRIMARY)
   1646 		  (org-get-x-clipboard 'CLIPBOARD)
   1647 		  (org-get-x-clipboard 'SECONDARY)
   1648 		  ""))			;ensure it is a string
   1649 	 ;; `initial' and `annotation' might have been passed.  But if
   1650 	 ;; the property list has them, we prefer those values.
   1651 	 (v-i (or (plist-get org-store-link-plist :initial)
   1652 		  (and (stringp initial) (org-no-properties initial))
   1653 		  (org-capture-get :initial)
   1654 		  ""))
   1655 	 (v-a
   1656 	  (let ((a (or (plist-get org-store-link-plist :annotation)
   1657 		       annotation
   1658 		       (org-capture-get :annotation)
   1659 		       "")))
   1660 	    ;; Is the link empty?  Then we do not want it...
   1661 	    (if (equal a "[[]]") "" a)))
   1662 	 (l-re "\\[\\[\\(.*?\\)\\]\\(\\[.*?\\]\\)?\\]")
   1663 	 (v-A (if (and v-a (string-match l-re v-a))
   1664 		  (replace-match "[[\\1][%^{Link description}]]" nil nil v-a)
   1665 		v-a))
   1666 	 (v-l (if (and v-a (string-match l-re v-a))
   1667 		  (replace-match "[[\\1]]" nil nil v-a)
   1668 		v-a))
   1669 	 (v-L (if (and v-a (string-match l-re v-a))
   1670 		  (replace-match "\\1" nil nil v-a)
   1671 		v-a))
   1672 	 (v-n user-full-name)
   1673 	 (v-k (if (marker-buffer org-clock-marker)
   1674 		  (org-no-properties org-clock-heading)
   1675 		""))
   1676 	 (v-K (if (marker-buffer org-clock-marker)
   1677                   (let ((original-link-plist org-store-link-plist)
   1678                         (clocked-task-link (org-with-point-at org-clock-marker
   1679                                              (org-store-link nil nil))))
   1680                     (setq org-store-link-plist original-link-plist)
   1681                     clocked-task-link)
   1682 	        ""))
   1683 	 (v-f (or (org-capture-get :original-file-nondirectory) ""))
   1684 	 (v-F (or (org-capture-get :original-file) ""))
   1685 	 (org-capture--clipboards
   1686 	  (delq nil
   1687 		(list v-i
   1688 		      (org-get-x-clipboard 'PRIMARY)
   1689 		      (org-get-x-clipboard 'CLIPBOARD)
   1690 		      (org-get-x-clipboard 'SECONDARY)
   1691 		      v-c))))
   1692     (setq org-store-link-plist (plist-put org-store-link-plist :annotation v-a))
   1693     (setq org-store-link-plist (plist-put org-store-link-plist :initial v-i))
   1694     (unless template
   1695       (setq template "")
   1696       (message "no template") (ding)
   1697       (sit-for 1))
   1698     (save-window-excursion
   1699       (switch-to-buffer-other-window (get-buffer-create "*Capture*"))
   1700       (erase-buffer)
   1701       (setq buffer-file-name nil)
   1702       (setq mark-active nil)
   1703       (insert template)
   1704       (org-mode)
   1705       (goto-char (point-min))
   1706       ;; %[] insert contents of a file.
   1707       (save-excursion
   1708 	(while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
   1709 	  (let ((filename (expand-file-name (match-string 1)))
   1710 		(beg (copy-marker (match-beginning 0)))
   1711 		(end (copy-marker (match-end 0))))
   1712 	    (unless (org-capture-escaped-%)
   1713 	      (delete-region beg end)
   1714 	      (set-marker beg nil)
   1715 	      (set-marker end nil)
   1716 	      (condition-case error
   1717 		  (insert-file-contents filename)
   1718 		(error
   1719 		 (insert (format "%%![could not insert %s: %s]"
   1720 				 filename
   1721 				 error))))))))
   1722       ;; Mark %() embedded elisp for later evaluation.
   1723       (org-capture-expand-embedded-elisp 'mark)
   1724       ;; Expand non-interactive templates.
   1725       (let ((regexp "%\\(:[-A-Za-z]+\\|<\\([^>\n]+\\)>\\|[aAcfFikKlLntTuUx]\\)"))
   1726 	(save-excursion
   1727 	  (while (re-search-forward regexp nil t)
   1728 	    ;; `org-capture-escaped-%' may modify buffer and cripple
   1729 	    ;; match-data.  Use markers instead.  Ditto for other
   1730 	    ;; templates.
   1731 	    (let ((pos (copy-marker (match-beginning 0)))
   1732 		  (end (copy-marker (match-end 0)))
   1733 		  (value (match-string 1))
   1734 		  (time-string (match-string 2)))
   1735 	      (unless (org-capture-escaped-%)
   1736 		(delete-region pos end)
   1737 		(set-marker pos nil)
   1738 		(set-marker end nil)
   1739 		(let* ((inside-sexp? (org-capture-inside-embedded-elisp-p))
   1740 		       (replacement
   1741 			(pcase (string-to-char value)
   1742 			  (?< (format-time-string time-string time))
   1743 			  (?:
   1744 			   (or (plist-get org-store-link-plist (intern value))
   1745 			       ""))
   1746 			  (?i
   1747 			   (if inside-sexp? v-i
   1748 			     ;; Outside embedded Lisp, repeat leading
   1749 			     ;; characters before initial place holder
   1750 			     ;; every line.
   1751 			     (let ((lead (concat "\n"
   1752 						 (org-current-line-string t))))
   1753 			       (replace-regexp-in-string "\n" lead v-i nil t))))
   1754 			  (?a v-a)
   1755 			  (?A v-A)
   1756 			  (?c v-c)
   1757 			  (?f v-f)
   1758 			  (?F v-F)
   1759 			  (?k v-k)
   1760 			  (?K v-K)
   1761 			  (?l v-l)
   1762 			  (?L v-L)
   1763 			  (?n v-n)
   1764 			  (?t v-t)
   1765 			  (?T v-T)
   1766 			  (?u v-u)
   1767 			  (?U v-U)
   1768 			  (?x v-x))))
   1769 		  (insert
   1770 		   (if inside-sexp?
   1771 		       ;; Escape sensitive characters.
   1772 		       (replace-regexp-in-string "[\\\"]" "\\\\\\&" replacement)
   1773 		     replacement))))))))
   1774       ;; Expand %() embedded Elisp.  Limit to Sexp originally marked.
   1775       (org-capture-expand-embedded-elisp)
   1776       ;; Expand interactive templates.  This is the last step so that
   1777       ;; template is mostly expanded when prompting happens.  Turn on
   1778       ;; Org mode and set local variables.  This is to support
   1779       ;; completion in interactive prompts.
   1780       (let ((org-inhibit-startup t)) (org-mode))
   1781       (org-clone-local-variables buffer "\\`org-")
   1782       (let (strings)			; Stores interactive answers.
   1783 	(save-excursion
   1784 	  (let ((regexp "%\\^\\(?:{\\([^}]*\\)}\\)?\\([CgGLptTuU]\\)?"))
   1785 	    (while (re-search-forward regexp nil t)
   1786 	      (let* ((items (and (match-end 1)
   1787 				 (save-match-data
   1788 				   (split-string (match-string-no-properties 1)
   1789 						 "|"))))
   1790 		     (key (match-string 2))
   1791 		     (beg (copy-marker (match-beginning 0)))
   1792 		     (end (copy-marker (match-end 0)))
   1793 		     (prompt (nth 0 items))
   1794 		     (default (nth 1 items))
   1795 		     (completions (nthcdr 2 items)))
   1796 		(unless (org-capture-escaped-%)
   1797 		  (delete-region beg end)
   1798 		  (set-marker beg nil)
   1799 		  (set-marker end nil)
   1800 		  (pcase key
   1801 		    ((or "G" "g")
   1802 		     (let* ((org-last-tags-completion-table
   1803 			     (org-global-tags-completion-table
   1804 			      (cond ((equal key "G") (org-agenda-files))
   1805 				    (file (list file))
   1806 				    (t nil))))
   1807 			    (org-add-colon-after-tag-completion t)
   1808 			    (ins (mapconcat
   1809 				  #'identity
   1810 				  (let ((crm-separator "[ \t]*:[ \t]*"))
   1811                                     (completing-read-multiple
   1812 				     (if prompt (concat prompt ": ") "Tags: ")
   1813 				     org-last-tags-completion-table nil nil nil
   1814 				     'org-tags-history))
   1815 				  ":")))
   1816 		       (when (org-string-nw-p ins)
   1817 			 (unless (eq (char-before) ?:) (insert ":"))
   1818 			 (insert ins)
   1819 			 (unless (eq (char-after) ?:) (insert ":"))
   1820 			 (when (org-at-heading-p) (org-align-tags)))))
   1821 		    ((or "C" "L")
   1822 		     (let ((insert-fun (if (equal key "C") #'insert
   1823 					 (lambda (s) (org-insert-link 0 s)))))
   1824 		       (pcase org-capture--clipboards
   1825 			 (`nil nil)
   1826 			 (`(,value) (funcall insert-fun value))
   1827 			 (`(,first-value . ,_)
   1828 			  (funcall insert-fun
   1829 				   (read-string "Clipboard/kill value: "
   1830 						first-value
   1831 						'org-capture--clipboards
   1832 						first-value)))
   1833 			 (_ (error "Invalid `org-capture--clipboards' value: %S"
   1834 				   org-capture--clipboards)))))
   1835 		    ("p"
   1836 		     ;; We remove keyword properties inherited from
   1837 		     ;; target buffer so `org-read-property-value' has
   1838 		     ;; a chance to find allowed values in sub-trees
   1839 		     ;; from the target buffer.
   1840 		     (setq-local org-keyword-properties nil)
   1841 		     (let* ((origin (set-marker (make-marker)
   1842 						(org-capture-get :pos)
   1843 						(org-capture-get :buffer)))
   1844 			    ;; Find location from where to get allowed
   1845 			    ;; values.  If `:target-entry-p' is
   1846 			    ;; non-nil, the current headline in the
   1847 			    ;; target buffer is going to be a parent
   1848 			    ;; headline, so location is fine.
   1849 			    ;; Otherwise, find the parent headline in
   1850 			    ;; the target buffer.
   1851 			    (pom (if (org-capture-get :target-entry-p) origin
   1852 				   (let ((level (progn
   1853 						  (while (org-up-heading-safe))
   1854 						  (org-current-level))))
   1855 				     (org-with-point-at origin
   1856 				       (let ((l (if (org-at-heading-p)
   1857 						    (org-current-level)
   1858 						  most-positive-fixnum)))
   1859 					 (while (and l (>= l level))
   1860 					   (setq l (org-up-heading-safe)))
   1861 					 (if l (point-marker)
   1862 					   (point-min-marker)))))))
   1863 			    (value
   1864 			     (org-read-property-value prompt pom default)))
   1865 		       (org-set-property prompt value)))
   1866 		    ((or "t" "T" "u" "U")
   1867 		     ;; These are the date/time related ones.
   1868 		     (let* ((upcase? (equal (upcase key) key))
   1869 			    (org-end-time-was-given nil)
   1870 			    (time (org-read-date upcase? t nil prompt)))
   1871 		       (org-insert-timestamp
   1872 			time (or org-time-was-given upcase?)
   1873 			(member key '("u" "U"))
   1874 			nil nil (list org-end-time-was-given))))
   1875 		    (`nil
   1876 		     ;; Load history list for current prompt.
   1877 		     (setq org-capture--prompt-history
   1878 			   (gethash prompt org-capture--prompt-history-table))
   1879                      (push (org-completing-read
   1880                             (org-format-prompt (or prompt "Enter string") default)
   1881 			    completions
   1882 			    nil nil nil 'org-capture--prompt-history default)
   1883 			   strings)
   1884 		     (insert (car strings))
   1885 		     ;; Save updated history list for current prompt.
   1886 		     (puthash prompt org-capture--prompt-history
   1887 			      org-capture--prompt-history-table))
   1888 		    (_
   1889 		     (error "Unknown template placeholder: \"%%^%s\""
   1890 			    key))))))))
   1891 	;; Replace %n escapes with nth %^{...} string.
   1892 	(setq strings (nreverse strings))
   1893 	(save-excursion
   1894 	  (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t)
   1895 	    (unless (org-capture-escaped-%)
   1896 	      (replace-match
   1897 	       (nth (1- (string-to-number (match-string 1))) strings)
   1898 	       nil t)))))
   1899       ;; Make sure there are no empty lines before the text, and that
   1900       ;; it ends with a newline character or it is empty.
   1901       (skip-chars-forward " \t\n")
   1902       (delete-region (point-min) (line-beginning-position))
   1903       (goto-char (point-max))
   1904       (skip-chars-backward " \t\n")
   1905       (if (bobp) (delete-region (point) (line-end-position))
   1906 	(end-of-line)
   1907 	(delete-region (point) (point-max))
   1908 	(insert "\n"))
   1909       ;; Return the expanded template and kill the capture buffer.
   1910       (untabify (point-min) (point-max))
   1911       (set-buffer-modified-p nil)
   1912       (prog1 (buffer-substring-no-properties (point-min) (point-max))
   1913 	(kill-buffer (current-buffer))))))
   1914 
   1915 (defun org-capture-escaped-% ()
   1916   "Non-nil if % was escaped.
   1917 If yes, unescape it now.  Assume `match-data' contains the
   1918 placeholder to check."
   1919   (save-excursion
   1920     (goto-char (match-beginning 0))
   1921     (let ((n (abs (skip-chars-backward "\\\\"))))
   1922       (delete-char (/ (1+ n) 2))
   1923       (= (% n 2) 1))))
   1924 
   1925 (defun org-capture-expand-embedded-elisp (&optional mark)
   1926   "Evaluate embedded elisp %(sexp) and replace with the result.
   1927 When optional MARK argument is non-nil, mark Sexp with a text
   1928 property (`org-embedded-elisp') for later evaluation.  Only
   1929 marked Sexp are evaluated when this argument is nil."
   1930   (save-excursion
   1931     (goto-char (point-min))
   1932     (while (re-search-forward "%(" nil t)
   1933       (cond
   1934        ((get-text-property (match-beginning 0) 'org-embedded-elisp)
   1935 	(goto-char (match-beginning 0))
   1936 	(let ((template-start (point)))
   1937 	  (forward-char 1)
   1938 	  (let* ((sexp (read (current-buffer)))
   1939 		 (result (org-eval
   1940 			  (org-capture--expand-keyword-in-embedded-elisp
   1941 			   sexp))))
   1942 	    (delete-region template-start (point))
   1943 	    (cond
   1944 	     ((not result) nil)
   1945 	     ((stringp result) (insert result))
   1946 	     (t (error
   1947 		 "Capture template sexp `%s' must evaluate to string or nil"
   1948 		 sexp))))))
   1949        ((not mark) nil)
   1950        ;; Only mark valid and non-escaped sexp.
   1951        ((org-capture-escaped-%) nil)
   1952        (t
   1953 	(let ((end (with-syntax-table emacs-lisp-mode-syntax-table
   1954 		     (ignore-errors (scan-sexps (1- (point)) 1)))))
   1955 	  (when end
   1956 	    (put-text-property (- (point) 2) end 'org-embedded-elisp t))))))))
   1957 
   1958 (defun org-capture--expand-keyword-in-embedded-elisp (attr)
   1959   "Recursively replace capture link keywords in ATTR sexp.
   1960 Such keywords are prefixed with \"%:\".  See
   1961 `org-capture-template' for more information."
   1962   (cond ((consp attr)
   1963 	 (mapcar 'org-capture--expand-keyword-in-embedded-elisp attr))
   1964 	((symbolp attr)
   1965 	 (let* ((attr-symbol (symbol-name attr))
   1966 		(key (and (string-match "%\\(:.*\\)" attr-symbol)
   1967 			  (intern (match-string 1 attr-symbol)))))
   1968 	   (or (plist-get org-store-link-plist key)
   1969 	       attr)))
   1970 	(t attr)))
   1971 
   1972 (defun org-capture-inside-embedded-elisp-p ()
   1973   "Non-nil if point is inside of embedded elisp %(sexp).
   1974 Assume sexps have been marked with
   1975 `org-capture-expand-embedded-elisp' beforehand."
   1976   (get-text-property (point) 'org-embedded-elisp))
   1977 
   1978 ;;;###autoload
   1979 (defun org-capture-import-remember-templates ()
   1980   "Set `org-capture-templates' to be similar to `org-remember-templates'."
   1981   (interactive)
   1982   (when (and (yes-or-no-p
   1983 	      "Import old remember templates into org-capture-templates? ")
   1984 	     (yes-or-no-p
   1985 	      "Note that this will remove any templates currently defined in `org-capture-templates'.  Do you still want to go ahead? "))
   1986     (require 'org-remember)
   1987     (setq org-capture-templates
   1988 	  (mapcar
   1989 	   (lambda (entry)
   1990 	     (let ((desc (car entry))
   1991 		   (key (char-to-string (nth 1 entry)))
   1992 		   (template (nth 2 entry))
   1993 		   (file (or (nth 3 entry) org-default-notes-file))
   1994 		   (position (or (nth 4 entry) org-remember-default-headline))
   1995 		   (type 'entry)
   1996 		   (prepend org-reverse-note-order)
   1997 		   immediate target jump-to-captured)
   1998 	       (cond
   1999 		((member position '(top bottom))
   2000 		 (setq target (list 'file file)
   2001 		       prepend (eq position 'top)))
   2002 		((eq position 'date-tree)
   2003 		 (setq target (list 'file+datetree file)
   2004 		       prepend nil))
   2005 		(t (setq target (list 'file+headline file position))))
   2006 
   2007 	       (when (string-match "%!" template)
   2008 		 (setq template (replace-match "" t t template)
   2009 		       immediate t))
   2010 
   2011 	       (when (string-match "%&" template)
   2012 		 (setq jump-to-captured t))
   2013 
   2014 	       (append (list key desc type target template)
   2015 		       (and prepend '(:prepend t))
   2016 		       (and immediate '(:immediate-finish t))
   2017 		       (and jump-to-captured '(:jump-to-captured t)))))
   2018 
   2019 	   org-remember-templates))))
   2020 
   2021 
   2022 (provide 'org-capture)
   2023 
   2024 ;;; org-capture.el ends here