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