Merge branch 'maint'
[org-mode.git] / lisp / org-capture.el
blob03e5230ea088a4c173c12184df751a61c3c93276
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 ;; Make sure that the empty lines after are correct
756 (when (and (> (point-max) end) ; indeed, the buffer was still narrowed
757 (member (org-capture-get :type 'local)
758 '(entry item checkitem plain)))
759 (save-excursion
760 (goto-char end)
761 (or (bolp) (newline))
762 (org-capture-empty-lines-after
763 (or (org-capture-get :empty-lines-after 'local)
764 (org-capture-get :empty-lines 'local) 0))))
765 ;; Postprocessing: Update Statistics cookies, do the sorting
766 (when (derived-mode-p 'org-mode)
767 (save-excursion
768 (when (ignore-errors (org-back-to-heading))
769 (org-update-parent-todo-statistics)
770 (org-update-checkbox-count)))
771 ;; FIXME Here we should do the sorting
772 ;; If we have added a table line, maybe recompute?
773 (when (and (eq (org-capture-get :type 'local) 'table-line)
774 (org-at-table-p))
775 (if (org-table-get-stored-formulas)
776 (org-table-recalculate 'all) ;; FIXME: Should we iterate???
777 (org-table-align))))
778 ;; Store this place as the last one where we stored something
779 ;; Do the marking in the base buffer, so that it makes sense after
780 ;; the indirect buffer has been killed.
781 (org-capture-store-last-position)
783 ;; Run the hook
784 (run-hooks 'org-capture-before-finalize-hook))
786 (when (org-capture-get :decrypted)
787 (save-excursion
788 (goto-char (org-capture-get :decrypted))
789 (org-encrypt-entry)))
791 ;; Kill the indirect buffer
792 (save-buffer)
793 (let ((return-wconf (org-capture-get :return-to-wconf 'local))
794 (new-buffer (org-capture-get :new-buffer 'local))
795 (kill-buffer (org-capture-get :kill-buffer 'local))
796 (base-buffer (buffer-base-buffer (current-buffer))))
798 ;; Kill the indirect buffer
799 (kill-buffer (current-buffer))
801 ;; Narrow back the target buffer to its previous state
802 (with-current-buffer (org-capture-get :buffer)
803 (let ((reg (org-capture-get :initial-target-region))
804 (pos (org-capture-get :initial-target-position))
805 (ipt (org-capture-get :insertion-point))
806 (size (org-capture-get :captured-entry-size)))
807 (if (not reg)
808 (widen)
809 (cond ((< ipt (car reg))
810 ;; insertion point is before the narrowed region
811 (narrow-to-region (+ size (car reg)) (+ size (cdr reg))))
812 ((> ipt (cdr reg))
813 ;; insertion point is after the narrowed region
814 (narrow-to-region (car reg) (cdr reg)))
816 ;; insertion point is within the narrowed region
817 (narrow-to-region (car reg) (+ size (cdr reg)))))
818 ;; now place back the point at its original position
819 (if (< ipt (car reg))
820 (goto-char (+ size pos))
821 (goto-char (if (< ipt pos) (+ size pos) pos))))))
823 ;; Kill the target buffer if that is desired
824 (when (and base-buffer new-buffer kill-buffer)
825 (with-current-buffer base-buffer (save-buffer))
826 (kill-buffer base-buffer))
828 ;; Restore the window configuration before capture
829 (set-window-configuration return-wconf))
831 (run-hooks 'org-capture-after-finalize-hook)
832 ;; Special cases
833 (cond
834 (abort-note
835 (cl-case abort-note
836 (clean
837 (message "Capture process aborted and target buffer cleaned up"))
838 (dirty
839 (error "Capture process aborted, but target buffer could not be \
840 cleaned up correctly"))))
841 (stay-with-capture
842 (org-capture-goto-last-stored)))
843 ;; Return if we did store something
844 (not abort-note)))
846 (defun org-capture-refile ()
847 "Finalize the current capture and then refile the entry.
848 Refiling is done from the base buffer, because the indirect buffer is then
849 already gone. Any prefix argument will be passed to the refile command."
850 (interactive)
851 (unless (eq (org-capture-get :type 'local) 'entry)
852 (user-error "Refiling from a capture buffer makes only sense \
853 for `entry'-type templates"))
854 (let* ((base (or (buffer-base-buffer) (current-buffer)))
855 (pos (make-marker))
856 (org-capture-is-refiling t)
857 (kill-buffer (org-capture-get :kill-buffer 'local)))
858 ;; Since `org-capture-finalize' may alter buffer contents (e.g.,
859 ;; empty lines) around entry, use a marker to refer to the
860 ;; headline to be refiled. Place the marker in the base buffer,
861 ;; as the current indirect one is going to be killed.
862 (set-marker pos (save-excursion (org-back-to-heading t) (point)) base)
863 (org-capture-put :kill-buffer nil)
864 (unwind-protect
865 (progn
866 (org-capture-finalize)
867 (save-window-excursion
868 (with-current-buffer base
869 (org-with-wide-buffer
870 (goto-char pos)
871 (call-interactively 'org-refile))))
872 (when kill-buffer (kill-buffer base)))
873 (set-marker pos nil))))
875 (defun org-capture-kill ()
876 "Abort the current capture process."
877 (interactive)
878 ;; FIXME: This does not do the right thing, we need to remove the
879 ;; new stuff by hand it is easy: undo, then kill the buffer
880 (let ((org-note-abort t)
881 (org-capture-before-finalize-hook nil))
882 (org-capture-finalize)))
884 (defun org-capture-goto-last-stored ()
885 "Go to the location where the last capture note was stored."
886 (interactive)
887 (org-goto-marker-or-bmk org-capture-last-stored-marker
888 (plist-get org-bookmark-names-plist
889 :last-capture))
890 (message "This is the last note stored by a capture process"))
892 ;;; Supporting functions for handling the process
894 (defun org-capture-put-target-region-and-position ()
895 "Store the initial region with `org-capture-put'."
896 (org-capture-put
897 :initial-target-region
898 ;; Check if the buffer is currently narrowed
899 (when (org-buffer-narrowed-p)
900 (cons (point-min) (point-max))))
901 ;; store the current point
902 (org-capture-put :initial-target-position (point)))
904 (defvar org-time-was-given) ; dynamically scoped parameter
905 (defun org-capture-set-target-location (&optional target)
906 "Find TARGET buffer and position.
907 Store them in the capture property list."
908 (let ((target-entry-p t))
909 (save-excursion
910 (pcase (or target (org-capture-get :target))
911 (`(file ,path)
912 (set-buffer (org-capture-target-buffer path))
913 (org-capture-put-target-region-and-position)
914 (widen)
915 (setq target-entry-p nil))
916 (`(id ,id)
917 (pcase (org-id-find id)
918 (`(,path . ,position)
919 (set-buffer (org-capture-target-buffer path))
920 (widen)
921 (org-capture-put-target-region-and-position)
922 (goto-char position))
923 (_ (error "Cannot find target ID \"%s\"" id))))
924 (`(file+headline ,path ,headline)
925 (set-buffer (org-capture-target-buffer path))
926 (unless (derived-mode-p 'org-mode)
927 (error "Target buffer \"%s\" for file+headline not in Org mode"
928 (current-buffer)))
929 (org-capture-put-target-region-and-position)
930 (widen)
931 (goto-char (point-min))
932 (if (re-search-forward (format org-complex-heading-regexp-format
933 (regexp-quote headline))
934 nil t)
935 (goto-char (line-beginning-position))
936 (goto-char (point-max))
937 (or (bolp) (insert "\n"))
938 (insert "* " headline "\n")
939 (beginning-of-line 0)))
940 (`(file+olp ,path . ,outline-path)
941 (let ((m (org-find-olp (cons (org-capture-expand-file path)
942 outline-path))))
943 (set-buffer (marker-buffer m))
944 (org-capture-put-target-region-and-position)
945 (widen)
946 (goto-char m)
947 (set-marker m nil)))
948 (`(file+regexp ,path ,regexp)
949 (set-buffer (org-capture-target-buffer path))
950 (org-capture-put-target-region-and-position)
951 (widen)
952 (goto-char (point-min))
953 (if (not (re-search-forward regexp nil t))
954 (error "No match for target regexp in file %s" path)
955 (goto-char (if (org-capture-get :prepend)
956 (match-beginning 0)
957 (match-end 0)))
958 (org-capture-put :exact-position (point))
959 (setq target-entry-p
960 (and (derived-mode-p 'org-mode) (org-at-heading-p)))))
961 (`(file+olp+datetree ,path . ,outline-path)
962 (let ((m (if outline-path
963 (org-find-olp (cons (org-capture-expand-file path)
964 outline-path))
965 (set-buffer (org-capture-target-buffer path))
966 (point-marker))))
967 (set-buffer (marker-buffer m))
968 (org-capture-put-target-region-and-position)
969 (widen)
970 (goto-char m)
971 (set-marker m nil)
972 (require 'org-datetree)
973 (org-capture-put-target-region-and-position)
974 (widen)
975 ;; Make a date/week tree entry, with the current date (or
976 ;; yesterday, if we are extending dates for a couple of hours)
977 (funcall
978 (if (eq (org-capture-get :tree-type) 'week)
979 #'org-datetree-find-iso-week-create
980 #'org-datetree-find-date-create)
981 (calendar-gregorian-from-absolute
982 (cond
983 (org-overriding-default-time
984 ;; Use the overriding default time.
985 (time-to-days org-overriding-default-time))
986 ((or (org-capture-get :time-prompt)
987 (equal current-prefix-arg 1))
988 ;; Prompt for date.
989 (let ((prompt-time (org-read-date
990 nil t nil "Date for tree entry:"
991 (current-time))))
992 (org-capture-put
993 :default-time
994 (cond ((and (or (not (boundp 'org-time-was-given))
995 (not org-time-was-given))
996 (not (= (time-to-days prompt-time) (org-today))))
997 ;; Use 00:00 when no time is given for another
998 ;; date than today?
999 (apply #'encode-time
1000 (append '(0 0 0)
1001 (cl-cdddr (decode-time prompt-time)))))
1002 ((string-match "\\([^ ]+\\)--?[^ ]+[ ]+\\(.*\\)"
1003 org-read-date-final-answer)
1004 ;; Replace any time range by its start.
1005 (apply #'encode-time
1006 (org-read-date-analyze
1007 (replace-match "\\1 \\2" nil nil
1008 org-read-date-final-answer)
1009 prompt-time (decode-time prompt-time))))
1010 (t prompt-time)))
1011 (time-to-days prompt-time)))
1013 ;; Current date, possibly corrected for late night
1014 ;; workers.
1015 (org-today))))
1016 ;; the following is the keep-restriction argument for
1017 ;; org-datetree-find-date-create
1018 (if outline-path 'subtree-at-point))))
1019 (`(file+function ,path ,function)
1020 (set-buffer (org-capture-target-buffer path))
1021 (org-capture-put-target-region-and-position)
1022 (widen)
1023 (funcall function)
1024 (org-capture-put :exact-position (point))
1025 (setq target-entry-p
1026 (and (derived-mode-p 'org-mode) (org-at-heading-p))))
1027 (`(function ,fun)
1028 (funcall fun)
1029 (org-capture-put :exact-position (point))
1030 (setq target-entry-p
1031 (and (derived-mode-p 'org-mode) (org-at-heading-p))))
1032 (`(clock)
1033 (if (and (markerp org-clock-hd-marker)
1034 (marker-buffer org-clock-hd-marker))
1035 (progn (set-buffer (marker-buffer org-clock-hd-marker))
1036 (org-capture-put-target-region-and-position)
1037 (widen)
1038 (goto-char org-clock-hd-marker))
1039 (error "No running clock that could be used as capture target")))
1040 (target (error "Invalid capture target specification: %S" target)))
1042 (org-capture-put :buffer (current-buffer)
1043 :pos (point)
1044 :target-entry-p target-entry-p
1045 :decrypted
1046 (and (featurep 'org-crypt)
1047 (org-at-encrypted-entry-p)
1048 (save-excursion
1049 (org-decrypt-entry)
1050 (and (org-back-to-heading t) (point))))))))
1052 (defun org-capture-expand-file (file)
1053 "Expand functions, symbols and file names for FILE.
1054 When FILE is a function, call it. When it is a form, evaluate
1055 it. When it is a variable, return its value. When it is
1056 a string, treat it as a file name, possibly expanding it
1057 according to `org-directory', and return it. If it is the empty
1058 string, however, return `org-default-notes-file'. In any other
1059 case, raise an error."
1060 (let ((location (cond ((equal file "") org-default-notes-file)
1061 ((stringp file) (expand-file-name file org-directory))
1062 ((functionp file) (funcall file))
1063 ((and (symbolp file) (bound-and-true-p file)))
1064 (t nil))))
1065 (or (org-string-nw-p location)
1066 (error "Invalid file location: %S" location))))
1068 (defun org-capture-target-buffer (file)
1069 "Get a buffer for FILE.
1070 FILE is a generalized file location, as handled by
1071 `org-capture-expand-file'."
1072 (let ((file (org-capture-expand-file file)))
1073 (or (org-find-base-buffer-visiting file)
1074 (progn (org-capture-put :new-buffer t)
1075 (find-file-noselect file)))))
1077 (defun org-capture-place-template (&optional inhibit-wconf-store)
1078 "Insert the template at the target location, and display the buffer.
1079 When `inhibit-wconf-store', don't store the window configuration, as it
1080 may have been stored before."
1081 (unless inhibit-wconf-store
1082 (org-capture-put :return-to-wconf (current-window-configuration)))
1083 (delete-other-windows)
1084 (org-switch-to-buffer-other-window
1085 (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE"))
1086 (widen)
1087 (outline-show-all)
1088 (goto-char (org-capture-get :pos))
1089 (setq-local outline-level 'org-outline-level)
1090 (pcase (org-capture-get :type)
1091 ((or `nil `entry) (org-capture-place-entry))
1092 (`table-line (org-capture-place-table-line))
1093 (`plain (org-capture-place-plain-text))
1094 (`item (org-capture-place-item))
1095 (`checkitem (org-capture-place-item)))
1096 (org-capture-mode 1)
1097 (setq-local org-capture-current-plist org-capture-plist))
1099 (defun org-capture-place-entry ()
1100 "Place the template as a new Org entry."
1101 (let* ((txt (org-capture-get :template))
1102 (reversed (org-capture-get :prepend))
1103 (target-entry-p (org-capture-get :target-entry-p))
1104 level beg end)
1106 (and (org-capture-get :exact-position)
1107 (goto-char (org-capture-get :exact-position)))
1108 (cond
1109 ((not target-entry-p)
1110 ;; Insert as top-level entry, either at beginning or at end of
1111 ;; file.
1112 (setq level 1)
1113 (if reversed
1114 (progn (goto-char (point-min))
1115 (or (org-at-heading-p)
1116 (outline-next-heading)))
1117 (goto-char (point-max))
1118 (or (bolp) (insert "\n"))))
1120 ;; Insert as a child of the current entry
1121 (and (looking-at "\\*+")
1122 (setq level (- (match-end 0) (match-beginning 0))))
1123 (setq level (org-get-valid-level (or level 1) 1))
1124 (if reversed
1125 (progn
1126 (outline-next-heading)
1127 (or (bolp) (insert "\n")))
1128 (org-end-of-subtree t nil)
1129 (or (bolp) (insert "\n")))))
1130 (org-capture-empty-lines-before)
1131 (setq beg (point))
1132 (org-capture-verify-tree txt)
1133 (org-paste-subtree level txt 'for-yank)
1134 (org-capture-empty-lines-after 1)
1135 (org-capture-position-for-last-stored beg)
1136 (outline-next-heading)
1137 (setq end (point))
1138 (org-capture-mark-kill-region beg (1- end))
1139 (org-capture-narrow beg (1- end))
1140 (if (or (re-search-backward "%\\?" beg t)
1141 (re-search-forward "%\\?" end t))
1142 (replace-match ""))))
1144 (defun org-capture-place-item ()
1145 "Place the template as a new plain list item."
1146 (let* ((txt (org-capture-get :template))
1147 (target-entry-p (org-capture-get :target-entry-p))
1148 (ind 0)
1149 beg end)
1150 (if (org-capture-get :exact-position)
1151 (goto-char (org-capture-get :exact-position))
1152 (cond
1153 ((not target-entry-p)
1154 ;; Insert as top-level entry, either at beginning or at end of file
1155 (setq beg (point-min) end (point-max)))
1157 (setq beg (1+ (point-at-eol))
1158 end (save-excursion (outline-next-heading) (point)))))
1159 (setq ind nil)
1160 (if (org-capture-get :prepend)
1161 (progn
1162 (goto-char beg)
1163 (when (org-list-search-forward (org-item-beginning-re) end t)
1164 (goto-char (match-beginning 0))
1165 (setq ind (org-get-indentation))))
1166 (goto-char end)
1167 (when (org-list-search-backward (org-item-beginning-re) beg t)
1168 (setq ind (org-get-indentation))
1169 (org-end-of-item)))
1170 (unless ind (goto-char end)))
1171 ;; Remove common indentation
1172 (setq txt (org-remove-indentation txt))
1173 ;; Make sure this is indeed an item
1174 (unless (string-match (concat "\\`" (org-item-re)) txt)
1175 (setq txt (concat "- "
1176 (mapconcat 'identity (split-string txt "\n")
1177 "\n "))))
1178 ;; Prepare surrounding empty lines.
1179 (org-capture-empty-lines-before)
1180 (setq beg (point))
1181 (unless (eolp) (save-excursion (insert "\n")))
1182 (unless ind
1183 (org-indent-line)
1184 (setq ind (org-get-indentation))
1185 (delete-region beg (point)))
1186 ;; Set the correct indentation, depending on context
1187 (setq ind (make-string ind ?\ ))
1188 (setq txt (concat ind
1189 (mapconcat 'identity (split-string txt "\n")
1190 (concat "\n" ind))
1191 "\n"))
1192 ;; Insert item.
1193 (insert txt)
1194 (org-capture-empty-lines-after 1)
1195 (org-capture-position-for-last-stored beg)
1196 (forward-char 1)
1197 (setq end (point))
1198 (org-capture-mark-kill-region beg (1- end))
1199 (org-capture-narrow beg (1- end))
1200 (if (or (re-search-backward "%\\?" beg t)
1201 (re-search-forward "%\\?" end t))
1202 (replace-match ""))))
1204 (defun org-capture-place-table-line ()
1205 "Place the template as a table line."
1206 (require 'org-table)
1207 (let* ((txt (org-capture-get :template))
1208 (target-entry-p (org-capture-get :target-entry-p))
1209 (table-line-pos (org-capture-get :table-line-pos))
1210 beg end)
1211 (cond
1212 ((org-capture-get :exact-position)
1213 (goto-char (org-capture-get :exact-position)))
1214 ((not target-entry-p)
1215 ;; Table is not necessarily under a heading
1216 (setq beg (point-min) end (point-max)))
1218 ;; WE are at a heading, limit search to the body
1219 (setq beg (1+ (point-at-eol))
1220 end (save-excursion (outline-next-heading) (point)))))
1221 (if (re-search-forward org-table-dataline-regexp end t)
1222 (let ((b (org-table-begin)) (e (org-table-end)) (case-fold-search t))
1223 (goto-char e)
1224 (if (looking-at "[ \t]*#\\+tblfm:")
1225 (forward-line 1))
1226 (narrow-to-region b (point)))
1227 (goto-char end)
1228 (insert "\n| |\n|----|\n| |\n")
1229 (narrow-to-region (1+ end) (point)))
1230 ;; We are narrowed to the table, or to an empty line if there was no table
1232 ;; Check if the template is good
1233 (if (not (string-match org-table-dataline-regexp txt))
1234 (setq txt "| %?Bad template |\n"))
1235 (if (functionp table-line-pos)
1236 (setq table-line-pos (funcall table-line-pos))
1237 (setq table-line-pos (eval table-line-pos)))
1238 (cond
1239 ((and table-line-pos
1240 (string-match "\\(I+\\)\\([-+][0-9]\\)" table-line-pos))
1241 (goto-char (point-min))
1242 ;; we have a complex line specification
1243 (let ((ll (ignore-errors
1244 (save-match-data (org-table-analyze))
1245 (aref org-table-hlines
1246 (- (match-end 1) (match-beginning 1)))))
1247 (delta (string-to-number (match-string 2 table-line-pos))))
1248 ;; The user wants a special position in the table
1249 (unless ll
1250 (error "Invalid table line specification \"%s\"" table-line-pos))
1251 (goto-char org-table-current-begin-pos)
1252 (forward-line (+ ll delta (if (< delta 0) 0 -1)))
1253 (org-table-insert-row 'below)
1254 (beginning-of-line 1)
1255 (delete-region (point) (1+ (point-at-eol)))
1256 (setq beg (point))
1257 (insert txt)
1258 (setq end (point))))
1259 ((org-capture-get :prepend)
1260 (goto-char (point-min))
1261 (re-search-forward org-table-hline-regexp nil t)
1262 (beginning-of-line 1)
1263 (re-search-forward org-table-dataline-regexp nil t)
1264 (beginning-of-line 1)
1265 (setq beg (point))
1266 (org-table-insert-row)
1267 (beginning-of-line 1)
1268 (delete-region (point) (1+ (point-at-eol)))
1269 (insert txt)
1270 (setq end (point)))
1272 (goto-char (point-max))
1273 (re-search-backward org-table-dataline-regexp nil t)
1274 (beginning-of-line 1)
1275 (org-table-insert-row 'below)
1276 (beginning-of-line 1)
1277 (delete-region (point) (1+ (point-at-eol)))
1278 (setq beg (point))
1279 (insert txt)
1280 (setq end (point))))
1281 (goto-char beg)
1282 (org-capture-position-for-last-stored 'table-line)
1283 (if (or (re-search-backward "%\\?" beg t)
1284 (re-search-forward "%\\?" end t))
1285 (replace-match ""))
1286 (org-table-align)))
1288 (defun org-capture-place-plain-text ()
1289 "Place the template plainly.
1290 If the target locator points at an Org node, place the template into
1291 the text of the entry, before the first child. If not, place the
1292 template at the beginning or end of the file.
1293 Of course, if exact position has been required, just put it there."
1294 (let* ((txt (org-capture-get :template))
1295 beg end)
1296 (cond
1297 ((org-capture-get :exact-position)
1298 (goto-char (org-capture-get :exact-position)))
1299 ((and (org-capture-get :target-entry-p)
1300 (bolp)
1301 (looking-at org-outline-regexp))
1302 ;; we should place the text into this entry
1303 (if (org-capture-get :prepend)
1304 ;; Skip meta data and drawers
1305 (org-end-of-meta-data t)
1306 ;; go to ent of the entry text, before the next headline
1307 (outline-next-heading)))
1309 ;; beginning or end of file
1310 (goto-char (if (org-capture-get :prepend) (point-min) (point-max)))))
1311 (or (bolp) (newline))
1312 (org-capture-empty-lines-before)
1313 (setq beg (point))
1314 (insert txt)
1315 (org-capture-empty-lines-after 1)
1316 (org-capture-position-for-last-stored beg)
1317 (setq end (point))
1318 (org-capture-mark-kill-region beg (1- end))
1319 (org-capture-narrow beg (1- end))
1320 (if (or (re-search-backward "%\\?" beg t)
1321 (re-search-forward "%\\?" end t))
1322 (replace-match ""))))
1324 (defun org-capture-mark-kill-region (beg end)
1325 "Mark the region that will have to be killed when aborting capture."
1326 (let ((m1 (move-marker (make-marker) beg))
1327 (m2 (move-marker (make-marker) end)))
1328 (org-capture-put :begin-marker m1)
1329 (org-capture-put :end-marker m2)))
1331 (defun org-capture-position-for-last-stored (where)
1332 "Memorize the position that should later become the position of last capture."
1333 (cond
1334 ((integerp where)
1335 (org-capture-put :position-for-last-stored
1336 (move-marker (make-marker) where
1337 (or (buffer-base-buffer (current-buffer))
1338 (current-buffer)))))
1339 ((eq where 'table-line)
1340 (org-capture-put :position-for-last-stored
1341 (list 'table-line
1342 (org-table-current-dline))))
1343 (t (error "This should not happen"))))
1345 (defun org-capture-store-last-position ()
1346 "Store the last-captured position."
1347 (let* ((where (org-capture-get :position-for-last-stored 'local))
1348 (pos (cond
1349 ((markerp where)
1350 (prog1 (marker-position where)
1351 (move-marker where nil)))
1352 ((and (listp where) (eq (car where) 'table-line))
1353 (if (org-at-table-p)
1354 (save-excursion
1355 (org-table-goto-line (nth 1 where))
1356 (point-at-bol))
1357 (point))))))
1358 (with-current-buffer (buffer-base-buffer (current-buffer))
1359 (org-with-point-at pos
1360 (when org-capture-bookmark
1361 (let ((bookmark (plist-get org-bookmark-names-plist :last-capture)))
1362 (when bookmark (with-demoted-errors (bookmark-set bookmark)))))
1363 (move-marker org-capture-last-stored-marker (point))))))
1365 (defun org-capture-narrow (beg end)
1366 "Narrow, unless configuration says not to narrow."
1367 (unless (org-capture-get :unnarrowed)
1368 (narrow-to-region beg end)
1369 (goto-char beg)))
1371 (defun org-capture-empty-lines-before (&optional n)
1372 "Set the correct number of empty lines before the insertion point.
1373 Point will be after the empty lines, so insertion can directly be done."
1374 (setq n (or n (org-capture-get :empty-lines-before)
1375 (org-capture-get :empty-lines) 0))
1376 (let ((pos (point)))
1377 (org-back-over-empty-lines)
1378 (delete-region (point) pos)
1379 (if (> n 0) (newline n))))
1381 (defun org-capture-empty-lines-after (&optional n)
1382 "Set the correct number of empty lines after the inserted string.
1383 Point will remain at the first line after the inserted text."
1384 (setq n (or n (org-capture-get :empty-lines-after)
1385 (org-capture-get :empty-lines) 0))
1386 (org-back-over-empty-lines)
1387 (while (looking-at "[ \t]*\n") (replace-match ""))
1388 (let ((pos (point)))
1389 (if (> n 0) (newline n))
1390 (goto-char pos)))
1392 (defvar org-clock-marker) ; Defined in org.el
1394 (defun org-capture-insert-template-here ()
1395 "Insert the capture template at point."
1396 (let* ((template (org-capture-get :template))
1397 (type (org-capture-get :type))
1398 beg end pp)
1399 (or (bolp) (newline))
1400 (setq beg (point))
1401 (cond
1402 ((and (eq type 'entry) (derived-mode-p 'org-mode))
1403 (org-capture-verify-tree (org-capture-get :template))
1404 (org-paste-subtree nil template t))
1405 ((and (memq type '(item checkitem))
1406 (derived-mode-p 'org-mode)
1407 (save-excursion (skip-chars-backward " \t\n")
1408 (setq pp (point))
1409 (org-in-item-p)))
1410 (goto-char pp)
1411 (org-insert-item)
1412 (skip-chars-backward " ")
1413 (skip-chars-backward "-+*0123456789).")
1414 (delete-region (point) (point-at-eol))
1415 (setq beg (point))
1416 (org-remove-indentation template)
1417 (insert template)
1418 (org-capture-empty-lines-after)
1419 (goto-char beg)
1420 (org-list-repair)
1421 (org-end-of-item)
1422 (setq end (point)))
1423 (t (insert template)))
1424 (setq end (point))
1425 (goto-char beg)
1426 (if (re-search-forward "%\\?" end t)
1427 (replace-match ""))))
1429 (defun org-capture-set-plist (entry)
1430 "Initialize the property list from the template definition."
1431 (setq org-capture-plist (copy-sequence (nthcdr 5 entry)))
1432 (org-capture-put :key (car entry) :description (nth 1 entry)
1433 :target (nth 3 entry))
1434 (let ((txt (nth 4 entry)) (type (or (nth 2 entry) 'entry)))
1435 (when (or (not txt) (and (stringp txt) (not (string-match "\\S-" txt))))
1436 ;; The template may be empty or omitted for special types.
1437 ;; Here we insert the default templates for such cases.
1438 (cond
1439 ((eq type 'item) (setq txt "- %?"))
1440 ((eq type 'checkitem) (setq txt "- [ ] %?"))
1441 ((eq type 'table-line) (setq txt "| %? |"))
1442 ((member type '(nil entry)) (setq txt "* %?\n %a"))))
1443 (org-capture-put :template txt :type type)))
1445 (defun org-capture-goto-target (&optional template-key)
1446 "Go to the target location of a capture template.
1447 The user is queried for the template."
1448 (interactive)
1449 (let ((entry (org-capture-select-template template-key)))
1450 (unless entry (error "No capture template selected"))
1451 (org-capture-set-plist entry)
1452 (org-capture-set-target-location)
1453 (pop-to-buffer-same-window (org-capture-get :buffer))
1454 (goto-char (org-capture-get :pos))))
1456 (defun org-capture-get-indirect-buffer (&optional buffer prefix)
1457 "Make an indirect buffer for a capture process.
1458 Use PREFIX as a prefix for the name of the indirect buffer."
1459 (setq buffer (or buffer (current-buffer)))
1460 (let ((n 1) (base (buffer-name buffer)) bname)
1461 (setq bname (concat prefix "-" base))
1462 (while (buffer-live-p (get-buffer bname))
1463 (setq bname (concat prefix "-" (number-to-string (cl-incf n)) "-" base)))
1464 (condition-case nil
1465 (make-indirect-buffer buffer bname 'clone)
1466 (error
1467 (let ((buf (make-indirect-buffer buffer bname)))
1468 (with-current-buffer buf (org-mode))
1469 buf)))))
1471 (defun org-capture-verify-tree (tree)
1472 "Throw error if TREE is not a valid tree."
1473 (unless (org-kill-is-subtree-p tree)
1474 (error "Template is not a valid Org entry or tree")))
1476 (defun org-mks (table title &optional prompt specials)
1477 "Select a member of an alist with multiple keys.
1479 TABLE is the alist which should contain entries where the car is a string.
1480 There should be two types of entries.
1482 1. prefix descriptions like (\"a\" \"Description\")
1483 This indicates that `a' is a prefix key for multi-letter selection, and
1484 that there are entries following with keys like \"ab\", \"ax\"...
1486 2. Select-able members must have more than two elements, with the first
1487 being the string of keys that lead to selecting it, and the second a
1488 short description string of the item.
1490 The command will then make a temporary buffer listing all entries
1491 that can be selected with a single key, and all the single key
1492 prefixes. When you press the key for a single-letter entry, it is selected.
1493 When you press a prefix key, the commands (and maybe further prefixes)
1494 under this key will be shown and offered for selection.
1496 TITLE will be placed over the selection in the temporary buffer,
1497 PROMPT will be used when prompting for a key. SPECIAL is an
1498 alist with (\"key\" \"description\") entries. When one of these
1499 is selected, only the bare key is returned."
1500 (save-window-excursion
1501 (let ((inhibit-quit t)
1502 (buffer (org-switch-to-buffer-other-window "*Org Select*"))
1503 (prompt (or prompt "Select: "))
1504 current)
1505 (unwind-protect
1506 (catch 'exit
1507 (while t
1508 (erase-buffer)
1509 (insert title "\n\n")
1510 (let ((des-keys nil)
1511 (allowed-keys '("\C-g"))
1512 (cursor-type nil))
1513 ;; Populate allowed keys and descriptions keys
1514 ;; available with CURRENT selector.
1515 (let ((re (format "\\`%s\\(.\\)\\'"
1516 (if current (regexp-quote current) "")))
1517 (prefix (if current (concat current " ") "")))
1518 (dolist (entry table)
1519 (pcase entry
1520 ;; Description.
1521 (`(,(and key (pred (string-match re))) ,desc)
1522 (let ((k (match-string 1 key)))
1523 (push k des-keys)
1524 (push k allowed-keys)
1525 (insert prefix "[" k "]" "..." " " desc "..." "\n")))
1526 ;; Usable entry.
1527 (`(,(and key (pred (string-match re))) ,desc . ,_)
1528 (let ((k (match-string 1 key)))
1529 (insert prefix "[" k "]" " " desc "\n")
1530 (push k allowed-keys)))
1531 (_ nil))))
1532 ;; Insert special entries, if any.
1533 (when specials
1534 (insert "----------------------------------------------------\
1535 ---------------------------\n")
1536 (pcase-dolist (`(,key ,description) specials)
1537 (insert (format "[%s] %s\n" key description))
1538 (push key allowed-keys)))
1539 ;; Display UI and let user select an entry or
1540 ;; a sub-level prefix.
1541 (goto-char (point-min))
1542 (unless (pos-visible-in-window-p (point-max))
1543 (org-fit-window-to-buffer))
1544 (message prompt)
1545 (let ((pressed (char-to-string (read-char-exclusive))))
1546 (while (not (member pressed allowed-keys))
1547 (message "Invalid key `%s'" pressed) (sit-for 1)
1548 (message prompt)
1549 (setq pressed (char-to-string (read-char-exclusive))))
1550 (setq current (concat current pressed))
1551 (cond
1552 ((equal pressed "\C-g") (user-error "Abort"))
1553 ;; Selection is a prefix: open a new menu.
1554 ((member pressed des-keys))
1555 ;; Selection matches an association: return it.
1556 ((let ((entry (assoc current table)))
1557 (and entry (throw 'exit entry))))
1558 ;; Selection matches a special entry: return the
1559 ;; selection prefix.
1560 ((assoc current specials) (throw 'exit current))
1561 (t (error "No entry available")))))))
1562 (when buffer (kill-buffer buffer))))))
1564 ;;; The template code
1565 (defun org-capture-select-template (&optional keys)
1566 "Select a capture template.
1567 Lisp programs can force the template by setting KEYS to a string."
1568 (let ((org-capture-templates
1569 (or (org-contextualize-keys
1570 (org-capture-upgrade-templates org-capture-templates)
1571 org-capture-templates-contexts)
1572 '(("t" "Task" entry (file+headline "" "Tasks")
1573 "* TODO %?\n %u\n %a")))))
1574 (if keys
1575 (or (assoc keys org-capture-templates)
1576 (error "No capture template referred to by \"%s\" keys" keys))
1577 (org-mks org-capture-templates
1578 "Select a capture template\n========================="
1579 "Template key: "
1580 '(("C" "Customize org-capture-templates")
1581 ("q" "Abort"))))))
1583 (defun org-capture-fill-template (&optional template initial annotation)
1584 "Fill a template and return the filled template as a string.
1585 The template may still contain \"%?\" for cursor positioning."
1586 (let* ((template (or template (org-capture-get :template)))
1587 (buffer (org-capture-get :buffer))
1588 (file (buffer-file-name (or (buffer-base-buffer buffer) buffer)))
1589 (time (let* ((c (or (org-capture-get :default-time) (current-time)))
1590 (d (decode-time c)))
1591 (if (< (nth 2 d) org-extend-today-until)
1592 (encode-time 0 59 23 (1- (nth 3 d)) (nth 4 d) (nth 5 d))
1593 c)))
1594 (v-t (format-time-string (org-time-stamp-format nil) time))
1595 (v-T (format-time-string (org-time-stamp-format t) time))
1596 (v-u (format-time-string (org-time-stamp-format nil t) time))
1597 (v-U (format-time-string (org-time-stamp-format t t) time))
1598 (v-c (and kill-ring (current-kill 0)))
1599 (v-x (or (org-get-x-clipboard 'PRIMARY)
1600 (org-get-x-clipboard 'CLIPBOARD)
1601 (org-get-x-clipboard 'SECONDARY)))
1602 ;; `initial' and `annotation' might have been passed. But if
1603 ;; the property list has them, we prefer those values.
1604 (v-i (or (plist-get org-store-link-plist :initial)
1605 (and (stringp initial) (org-no-properties initial))
1606 (org-capture-get :initial)
1607 ""))
1608 (v-a
1609 (let ((a (or (plist-get org-store-link-plist :annotation)
1610 annotation
1611 (org-capture-get :annotation)
1612 "")))
1613 ;; Is the link empty? Then we do not want it...
1614 (if (equal a "[[]]") "" a)))
1615 (l-re "\\[\\[\\(.*?\\)\\]\\(\\[.*?\\]\\)?\\]")
1616 (v-A (if (and v-a (string-match l-re v-a))
1617 (replace-match "[[\\1][%^{Link description}]]" nil nil v-a)
1618 v-a))
1619 (v-l (if (and v-a (string-match l-re v-a))
1620 (replace-match "\\1" nil nil v-a)
1621 v-a))
1622 (v-n user-full-name)
1623 (v-k (and (marker-buffer org-clock-marker)
1624 (org-no-properties org-clock-heading)))
1625 (v-K (if (marker-buffer org-clock-marker)
1626 (org-make-link-string
1627 (buffer-file-name (marker-buffer org-clock-marker))
1628 org-clock-heading)))
1629 (v-f (or (org-capture-get :original-file-nondirectory) ""))
1630 (v-F (or (org-capture-get :original-file) ""))
1631 (clipboards (delq nil
1632 (list v-i
1633 (org-get-x-clipboard 'PRIMARY)
1634 (org-get-x-clipboard 'CLIPBOARD)
1635 (org-get-x-clipboard 'SECONDARY)
1636 v-c))))
1638 (setq org-store-link-plist (plist-put org-store-link-plist :annotation v-a))
1639 (setq org-store-link-plist (plist-put org-store-link-plist :initial v-i))
1641 (unless template
1642 (setq template "")
1643 (message "no template") (ding)
1644 (sit-for 1))
1645 (save-window-excursion
1646 (org-switch-to-buffer-other-window (get-buffer-create "*Capture*"))
1647 (erase-buffer)
1648 (setq buffer-file-name nil)
1649 (setq mark-active nil)
1650 (insert template)
1651 (goto-char (point-min))
1653 ;; %[] insert contents of a file.
1654 (save-excursion
1655 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
1656 (let ((filename (expand-file-name (match-string 1)))
1657 (beg (copy-marker (match-beginning 0)))
1658 (end (copy-marker (match-end 0))))
1659 (unless (org-capture-escaped-%)
1660 (delete-region beg end)
1661 (set-marker beg nil)
1662 (set-marker end nil)
1663 (condition-case error
1664 (insert-file-contents filename)
1665 (error
1666 (insert (format "%%![couldn not insert %s: %s]"
1667 filename
1668 error))))))))
1670 ;; Mark %() embedded elisp for later evaluation.
1671 (org-capture-expand-embedded-elisp 'mark)
1673 ;; Expand non-interactive templates.
1674 (let ((regexp "%\\(:[-a-za-z]+\\|<\\([^>\n]+\\)>\\|[aAcfFikKlntTuUx]\\)"))
1675 (save-excursion
1676 (while (re-search-forward regexp nil t)
1677 ;; `org-capture-escaped-%' may modify buffer and cripple
1678 ;; match-data. Use markers instead. Ditto for other
1679 ;; templates.
1680 (let ((pos (copy-marker (match-beginning 0)))
1681 (end (copy-marker (match-end 0)))
1682 (value (match-string 1))
1683 (time-string (match-string 2)))
1684 (unless (org-capture-escaped-%)
1685 (delete-region pos end)
1686 (set-marker pos nil)
1687 (set-marker end nil)
1688 (let* ((inside-sexp? (org-capture-inside-embedded-elisp-p))
1689 (replacement
1690 (pcase (string-to-char value)
1691 (?< (format-time-string time-string time))
1693 (or (plist-get org-store-link-plist (intern value))
1694 ""))
1696 (if inside-sexp? v-i
1697 ;; Outside embedded Lisp, repeat leading
1698 ;; characters before initial place holder
1699 ;; every line.
1700 (let ((lead (buffer-substring-no-properties
1701 (line-beginning-position) (point))))
1702 (replace-regexp-in-string "\n\\(.\\)"
1703 (concat lead "\\1")
1704 v-i nil nil 1))))
1705 (?a v-a)
1706 (?A v-A)
1707 (?c v-c)
1708 (?f v-f)
1709 (?F v-F)
1710 (?k v-k)
1711 (?K v-K)
1712 (?l v-l)
1713 (?n v-n)
1714 (?t v-t)
1715 (?T v-T)
1716 (?u v-u)
1717 (?U v-U)
1718 (?x v-x))))
1719 (insert
1720 (if inside-sexp?
1721 ;; Escape sensitive characters.
1722 (replace-regexp-in-string "[\\\"]" "\\\\\\&" replacement)
1723 replacement))))))))
1725 ;; Expand %() embedded Elisp. Limit to Sexp originally marked.
1726 (org-capture-expand-embedded-elisp)
1728 ;; Expand interactive templates. This is the last step so that
1729 ;; template is mostly expanded when prompting happens. Turn on
1730 ;; Org mode and set local variables. This is to support
1731 ;; completion in interactive prompts.
1732 (let ((org-inhibit-startup t)) (org-mode))
1733 (org-clone-local-variables buffer "\\`org-")
1734 (let (strings) ; Stores interactive answers.
1735 (save-excursion
1736 (let ((regexp "%\\^\\(?:{\\([^}]*\\)}\\)?\\([CgGLptTuU]\\)?"))
1737 (while (re-search-forward regexp nil t)
1738 (let* ((items (and (match-end 1)
1739 (save-match-data
1740 (split-string (match-string-no-properties 1)
1741 "|"))))
1742 (key (match-string 2))
1743 (beg (copy-marker (match-beginning 0)))
1744 (end (copy-marker (match-end 0)))
1745 (prompt (nth 0 items))
1746 (default (nth 1 items))
1747 (completions (nthcdr 2 items)))
1748 (unless (org-capture-escaped-%)
1749 (delete-region beg end)
1750 (set-marker beg nil)
1751 (set-marker end nil)
1752 (pcase key
1753 ((or "G" "g")
1754 (let* ((org-last-tags-completion-table
1755 (org-global-tags-completion-table
1756 (cond ((equal key "G") (org-agenda-files))
1757 (file (list file))
1758 (t nil))))
1759 (org-add-colon-after-tag-completion t)
1760 (ins (mapconcat
1761 #'identity
1762 (org-split-string
1763 (completing-read
1764 (if prompt (concat prompt ": ") "Tags: ")
1765 'org-tags-completion-function nil nil nil
1766 'org-tags-history)
1767 "[^[:alnum:]_@#%]+")
1768 ":")))
1769 (when (org-string-nw-p ins)
1770 (unless (eq (char-before) ?:) (insert ":"))
1771 (insert ins)
1772 (unless (eq (char-after) ?:) (insert ":"))
1773 (and (org-at-heading-p)
1774 (let ((org-ignore-region t))
1775 (org-set-tags nil 'align))))))
1776 ("C"
1777 (cond
1778 ((= (length clipboards) 1) (insert (car clipboards)))
1779 ((> (length clipboards) 1)
1780 (insert (read-string "Clipboard/kill value: "
1781 (car clipboards)
1782 '(clipboards . 1)
1783 (car clipboards))))))
1784 ("L"
1785 (cond ((= (length clipboards) 1)
1786 (org-insert-link 0 (car clipboards)))
1787 ((> (length clipboards) 1)
1788 (org-insert-link
1790 (read-string "Clipboard/kill value: "
1791 (car clipboards)
1792 '(clipboards . 1)
1793 (car clipboards))))))
1794 ("p" (org-set-property prompt nil))
1795 ((guard key)
1796 ;; These are the date/time related ones.
1797 (let* ((upcase? (equal (upcase key) key))
1798 (org-time-was-given upcase?)
1799 (org-end-time-was-given)
1800 (time (org-read-date upcase? t nil prompt)))
1801 (org-insert-time-stamp
1802 time org-time-was-given
1803 (member key '("u" "U"))
1804 nil nil (list org-end-time-was-given))))
1806 (push (org-completing-read
1807 (concat (or prompt "Enter string")
1808 (and default (format " [%s]" default))
1809 ": ")
1810 completions nil nil nil nil default)
1811 strings)
1812 (insert (car strings)))))))))
1814 ;; Replace %n escapes with nth %^{...} string.
1815 (setq strings (nreverse strings))
1816 (save-excursion
1817 (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t)
1818 (unless (org-capture-escaped-%)
1819 (replace-match
1820 (nth (1- (string-to-number (match-string 1))) strings)
1821 nil t)))))
1823 ;; Make sure there are no empty lines before the text, and that
1824 ;; it ends with a newline character.
1825 (skip-chars-forward " \t\n")
1826 (delete-region (point-min) (line-beginning-position))
1827 (goto-char (point-max))
1828 (skip-chars-backward " \t\n")
1829 (delete-region (point) (point-max))
1830 (insert "\n")
1832 ;; Return the expanded template and kill the capture buffer.
1833 (untabify (point-min) (point-max))
1834 (set-buffer-modified-p nil)
1835 (prog1 (buffer-substring-no-properties (point-min) (point-max))
1836 (kill-buffer (current-buffer))))))
1838 (defun org-capture-escaped-% ()
1839 "Non-nil if % was escaped.
1840 If yes, unescape it now. Assume match-data contains the
1841 placeholder to check."
1842 (save-excursion
1843 (goto-char (match-beginning 0))
1844 (let ((n (abs (skip-chars-backward "\\\\"))))
1845 (delete-char (/ (1+ n) 2))
1846 (= (% n 2) 1))))
1848 (defun org-capture-expand-embedded-elisp (&optional mark)
1849 "Evaluate embedded elisp %(sexp) and replace with the result.
1850 When optional MARK argument is non-nil, mark Sexp with a text
1851 property (`org-embedded-elisp') for later evaluation. Only
1852 marked Sexp are evaluated when this argument is nil."
1853 (save-excursion
1854 (goto-char (point-min))
1855 (while (re-search-forward "%(" nil t)
1856 (cond
1857 ((get-text-property (match-beginning 0) 'org-embedded-elisp)
1858 (goto-char (match-beginning 0))
1859 (let ((template-start (point)))
1860 (forward-char 1)
1861 (let* ((sexp (read (current-buffer)))
1862 (result (org-eval
1863 (org-capture--expand-keyword-in-embedded-elisp
1864 sexp))))
1865 (delete-region template-start (point))
1866 (cond
1867 ((not result) nil)
1868 ((stringp result) (insert result))
1869 (t (error
1870 "Capture template sexp `%s' must evaluate to string or nil"
1871 sexp))))))
1872 ((not mark) nil)
1873 ;; Only mark valid and non-escaped sexp.
1874 ((org-capture-escaped-%) nil)
1876 (let ((end (with-syntax-table emacs-lisp-mode-syntax-table
1877 (ignore-errors (scan-sexps (1- (point)) 1)))))
1878 (when end
1879 (put-text-property (- (point) 2) end 'org-embedded-elisp t))))))))
1881 (defun org-capture--expand-keyword-in-embedded-elisp (attr)
1882 "Recursively replace capture link keywords in ATTR sexp.
1883 Such keywords are prefixed with \"%:\". See
1884 `org-capture-template' for more information."
1885 (cond ((consp attr)
1886 (mapcar 'org-capture--expand-keyword-in-embedded-elisp attr))
1887 ((symbolp attr)
1888 (let* ((attr-symbol (symbol-name attr))
1889 (key (and (string-match "%\\(:.*\\)" attr-symbol)
1890 (intern (match-string 1 attr-symbol)))))
1891 (or (plist-get org-store-link-plist key)
1892 attr)))
1893 (t attr)))
1895 (defun org-capture-inside-embedded-elisp-p ()
1896 "Non-nil if point is inside of embedded elisp %(sexp).
1897 Assume sexps have been marked with
1898 `org-capture-expand-embedded-elisp' beforehand."
1899 (get-text-property (point) 'org-embedded-elisp))
1901 ;;;###autoload
1902 (defun org-capture-import-remember-templates ()
1903 "Set `org-capture-templates' to be similar to `org-remember-templates'."
1904 (interactive)
1905 (when (and (yes-or-no-p
1906 "Import old remember templates into org-capture-templates? ")
1907 (yes-or-no-p
1908 "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
1909 (require 'org-remember)
1910 (setq org-capture-templates
1911 (mapcar
1912 (lambda (entry)
1913 (let ((desc (car entry))
1914 (key (char-to-string (nth 1 entry)))
1915 (template (nth 2 entry))
1916 (file (or (nth 3 entry) org-default-notes-file))
1917 (position (or (nth 4 entry) org-remember-default-headline))
1918 (type 'entry)
1919 (prepend org-reverse-note-order)
1920 immediate target jump-to-captured)
1921 (cond
1922 ((member position '(top bottom))
1923 (setq target (list 'file file)
1924 prepend (eq position 'top)))
1925 ((eq position 'date-tree)
1926 (setq target (list 'file+datetree file)
1927 prepend nil))
1928 (t (setq target (list 'file+headline file position))))
1930 (when (string-match "%!" template)
1931 (setq template (replace-match "" t t template)
1932 immediate t))
1934 (when (string-match "%&" template)
1935 (setq jump-to-captured t))
1937 (append (list key desc type target template)
1938 (if prepend '(:prepend t))
1939 (if immediate '(:immediate-finish t))
1940 (if jump-to-captured '(:jump-to-captured t)))))
1942 org-remember-templates))))
1943 ;;; The function was made obsolete by commit 65399674d5 of
1944 ;;; 2013-02-22. This make-obsolete call was added 2016-09-01.
1945 (make-obsolete 'org-capture-import-remember-templates "use the `org-capture-templates' variable instead." "Org 9.0")
1947 (provide 'org-capture)
1949 ;;; org-capture.el ends here