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