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