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