1 ;;; org-capture.el --- Fast note taking in Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2010-2019 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: https://orgmode.org
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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.
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?
53 (declare-function org-at-encrypted-entry-p
"org-crypt" ())
54 (declare-function org-at-table-p
"org-table" (&optional table-type
))
55 (declare-function org-clock-update-mode-line
"org-clock" (&optional refresh
))
56 (declare-function org-datetree-find-date-create
"org-datetree" (date &optional keep-restriction
))
57 (declare-function org-decrypt-entry
"org-crypt" ())
58 (declare-function org-element-at-point
"org-element" ())
59 (declare-function org-element-lineage
"org-element" (datum &optional types with-self
))
60 (declare-function org-element-property
"org-element" (property element
))
61 (declare-function org-encrypt-entry
"org-crypt" ())
62 (declare-function org-insert-link
"ol" (&optional complete-file link-location default-description
))
63 (declare-function org-link-make-string
"ol" (link &optional description
))
64 (declare-function org-table-analyze
"org-table" ())
65 (declare-function org-table-current-dline
"org-table" ())
66 (declare-function org-table-fix-formulas
"org-table" (key replace
&optional limit delta remove
))
67 (declare-function org-table-goto-line
"org-table" (N))
69 (defvar dired-buffers
)
70 (defvar org-end-time-was-given
)
71 (defvar org-remember-default-headline
)
72 (defvar org-remember-templates
)
73 (defvar org-store-link-plist
)
74 (defvar org-table-border-regexp
)
75 (defvar org-table-current-begin-pos
)
76 (defvar org-table-dataline-regexp
)
77 (defvar org-table-fix-formulas-confirm
)
78 (defvar org-table-hline-regexp
)
79 (defvar org-table-hlines
)
81 (defvar org-capture-clock-was-started nil
82 "Internal flag, noting if the clock was started.")
84 (defvar org-capture-last-stored-marker
(make-marker)
85 "Marker pointing to the entry most recently stored with `org-capture'.")
87 ;; The following variable is scoped dynamically by org-protocol
88 ;; to indicate that the link properties have already been stored
89 (defvar org-capture-link-is-already-stored nil
)
91 (defvar org-capture-is-refiling nil
92 "Non-nil when capture process is refiling an entry.")
94 (defvar org-capture--prompt-history-table
(make-hash-table :test
#'equal
)
95 "Hash table for all history lists per prompt.")
97 (defvar org-capture--prompt-history nil
98 "History list for prompt placeholders.")
100 (defgroup org-capture nil
101 "Options concerning capturing new entries."
105 (defun org-capture-upgrade-templates (templates)
106 "Update the template list to the new format.
107 TEMPLATES is a template list, as in `org-capture-templates'. The
108 new format unifies all the date/week tree targets into one that
109 also allows for an optional outline path to specify a target."
110 (let ((modified-templates
114 ;; Match templates with an obsolete "tree" target type. Replace
115 ;; it with common `file+olp-datetree'. Add new properties
116 ;; (i.e., `:time-prompt' and `:tree-type') if needed.
117 (`(,key
,desc
,type
(file+datetree .
,path
) ,tpl .
,props
)
118 `(,key
,desc
,type
(file+olp
+datetree
,@path
) ,tpl
,@props
))
119 (`(,key
,desc
,type
(file+datetree
+prompt .
,path
) ,tpl .
,props
)
120 `(,key
,desc
,type
(file+olp
+datetree
,@path
) ,tpl
121 :time-prompt t
,@props
))
122 (`(,key
,desc
,type
(file+weektree .
,path
) ,tpl .
,props
)
123 `(,key
,desc
,type
(file+olp
+datetree
,@path
) ,tpl
124 :tree-type week
,@props
))
125 (`(,key
,desc
,type
(file+weektree
+prompt .
,path
) ,tpl .
,props
)
126 `(,key
,desc
,type
(file+olp
+datetree
,@path
) ,tpl
127 :tree-type week
:time-prompt t
,@props
))
128 ;; Other templates are left unchanged.
131 (unless (equal modified-templates templates
)
132 (message "Deprecated date/weektree capture templates changed to `file+olp+datetree'."))
135 (defcustom org-capture-templates nil
136 "Templates for the creation of new entries.
138 Each entry is a list with the following items:
140 keys The keys that will select the template, as a string, characters
141 only, for example \"a\" for a template to be selected with a
142 single key, or \"bt\" for selection with two keys. When using
143 several keys, keys using the same prefix key must be together
144 in the list and preceded by a 2-element entry explaining the
145 prefix key, for example
147 (\"b\" \"Templates for marking stuff to buy\")
149 The \"C\" key is used by default for quick access to the
150 customization of the template variable. But if you want to use
151 that key for a template, you can.
153 description A short string describing the template, will be shown during
156 type The type of entry. Valid types are:
157 entry an Org node, with a headline. Will be filed
158 as the child of the target entry or as a
160 item a plain list item, will be placed in the
161 first plain list at the target
163 checkitem a checkbox item. This differs from the
164 plain list item only is so far as it uses a
165 different default template.
166 table-line a new line in the first table at target location.
167 plain text to be inserted as it is.
169 target Specification of where the captured item should be placed.
170 In Org files, targets usually define a node. Entries will
171 become children of this node, other types will be added to the
172 table or list in the body of this node.
174 Most target specifications contain a file name. If that file
175 name is the empty string, it defaults to `org-default-notes-file'.
176 A file can also be given as a variable or as a function called
177 with no argument. When an absolute path is not specified for a
178 target, it is taken as relative to `org-directory'.
182 (file \"path/to/file\")
183 Text will be placed at the beginning or end of that file
185 (id \"id of existing Org entry\")
186 File as child of this entry, or in the body of the entry
188 (file+headline \"path/to/file\" \"node headline\")
189 Fast configuration if the target heading is unique in the file
191 (file+olp \"path/to/file\" \"Level 1 heading\" \"Level 2\" ...)
192 For non-unique headings, the full outline path is safer
194 (file+regexp \"path/to/file\" \"regexp to find location\")
195 File to the entry matching regexp
197 (file+olp+datetree \"path/to/file\" \"Level 1 heading\" ...)
198 Will create a heading in a date tree for today's date.
199 If no heading is given, the tree will be on top level.
200 To prompt for date instead of using TODAY, use the
201 :time-prompt property. To create a week-tree, use the
204 (file+function \"path/to/file\" function-finding-location)
205 A function to find the right location in the file
208 File to the entry that is currently being clocked
210 (function function-finding-location)
211 Most general way: write your own function which both visits
212 the file and moves point to the right location
214 template The template for creating the capture item. If you leave this
215 empty, an appropriate default template will be used. See below
216 for more details. Instead of a string, this may also be one of
218 (file \"/path/to/template-file\")
219 (function function-returning-the-template)
221 in order to get a template from a file, or dynamically
224 The rest of the entry is a property list of additional options. Recognized
227 :prepend Normally newly captured information will be appended at
228 the target location (last child, last table line,
229 last list item...). Setting this property will
232 :immediate-finish When set, do not offer to edit the information, just
233 file it away immediately. This makes sense if the
234 template only needs information that can be added
237 :jump-to-captured When set, jump to the captured entry when finished.
239 :empty-lines Set this to the number of lines the should be inserted
240 before and after the new item. Default 0, only common
243 :empty-lines-before Set this to the number of lines the should be inserted
244 before the new item. Overrides :empty-lines for the
245 number lines inserted before.
247 :empty-lines-after Set this to the number of lines the should be inserted
248 after the new item. Overrides :empty-lines for the
249 number of lines inserted after.
251 :clock-in Start the clock in this item.
253 :clock-keep Keep the clock running when filing the captured entry.
255 :clock-resume Start the interrupted clock when finishing the capture.
256 Note that :clock-keep has precedence over :clock-resume.
257 When setting both to t, the current clock will run and
258 the previous one will not be resumed.
260 :time-prompt Prompt for a date/time to be used for date/week trees
261 and when filling the template.
263 :tree-type When `week', make a week tree instead of the month tree.
265 :unnarrowed Do not narrow the target buffer, simply show the
266 full buffer. Default is to narrow it so that you
267 only see the new stuff.
269 :table-line-pos Specification of the location in the table where the
270 new line should be inserted. It should be a string like
271 \"II-3\", meaning that the new line should become the
272 third line before the second horizontal separator line.
274 :kill-buffer If the target file was not yet visited by a buffer when
275 capture was invoked, kill the buffer again after capture
278 :no-save Do not save the target file after finishing the capture.
280 The template defines the text to be inserted. Often this is an
281 Org mode entry (so the first line should start with a star) that
282 will be filed as a child of the target headline. It can also be
283 freely formatted text. Furthermore, the following %-escapes will
284 be replaced with content and expanded:
286 %[pathname] Insert the contents of the file given by
287 `pathname'. These placeholders are expanded at the very
288 beginning of the process so they can be used to extend the
290 %(sexp) Evaluate elisp `(sexp)' and replace it with the results.
291 Only placeholders pre-existing within the template, or
292 introduced with %[pathname] are expanded this way. Since this
293 happens after expanding non-interactive %-escapes, those can
294 be used to fill the expression.
295 %<...> The result of format-time-string on the ... format specification.
296 %t Time stamp, date only. The time stamp is the current time,
297 except when called from agendas with `\\[org-agenda-capture]' or
298 with `org-capture-use-agenda-date' set.
299 %T Time stamp as above, with date and time.
300 %u, %U Like the above, but inactive time stamps.
301 %i Initial content, copied from the active region. If
302 there is text before %i on the same line, such as
303 indentation, and %i is not inside a %(sexp), that prefix
304 will be added before every line in the inserted text.
305 %a Annotation, normally the link created with `org-store-link'.
306 %A Like %a, but prompt for the description part.
307 %l Like %a, but only insert the literal link.
308 %c Current kill ring head.
309 %x Content of the X clipboard.
310 %k Title of currently clocked task.
311 %K Link to currently clocked task.
312 %n User name (taken from the variable `user-full-name').
313 %f File visited by current buffer when org-capture was called.
314 %F Full path of the file or directory visited by current buffer.
315 %:keyword Specific information for certain link types, see below.
316 %^g Prompt for tags, with completion on tags in target file.
317 %^G Prompt for tags, with completion on all tags in all agenda files.
318 %^t Like %t, but prompt for date. Similarly %^T, %^u, %^U.
319 You may define a prompt like: %^{Please specify birthday}t.
320 The default date is that of %t, see above.
321 %^C Interactive selection of which kill or clip to use.
322 %^L Like %^C, but insert as link.
323 %^{prop}p Prompt the user for a value for property `prop'.
324 %^{prompt} Prompt the user for a string and replace this sequence with it.
325 A default value and a completion table ca be specified like this:
326 %^{prompt|default|completion2|completion3|...}.
327 %? After completing the template, position cursor here.
328 %\\1 ... %\\N Insert the text entered at the nth %^{prompt}, where N
329 is a number, starting from 1.
331 Apart from these general escapes, you can access information specific to
332 the link type that is created. For example, calling `org-capture' in emails
333 or in Gnus will record the author and the subject of the message, which you
334 can access with \"%:from\" and \"%:subject\", respectively. Here is a
335 complete list of what is recorded for each link type.
337 Link type | Available information
338 ------------------------+------------------------------------------------------
339 bbdb | %:type %:name %:company
340 vm, wl, mh, mew, rmail, | %:type %:subject %:message-id
341 gnus | %:from %:fromname %:fromaddress
342 | %:to %:toname %:toaddress
343 | %:fromto (either \"to NAME\" or \"from NAME\")
344 | %:date %:date-timestamp (as active timestamp)
345 | %:date-timestamp-inactive (as inactive timestamp)
346 gnus | %:group, for messages also all email fields
347 eww, w3, w3m | %:type %:url
348 info | %:type %:file %:node
349 calendar | %:type %:date
351 When you need to insert a literal percent sign in the template,
352 you can escape ambiguous cases with a backward slash, e.g., \\%i."
355 :set
(lambda (s v
) (set s
(org-capture-upgrade-templates v
)))
357 (let ((file-variants '(choice :tag
"Filename "
358 (file :tag
"Literal")
359 (function :tag
"Function")
360 (variable :tag
"Variable")
361 (sexp :tag
"Form"))))
363 (choice :value
("" "" entry
(file "~/org/notes.org") "")
364 (list :tag
"Multikey description"
365 (string :tag
"Keys ")
366 (string :tag
"Description"))
367 (list :tag
"Template entry"
368 (string :tag
"Keys ")
369 (string :tag
"Description ")
370 (choice :tag
"Capture Type " :value entry
371 (const :tag
"Org entry" entry
)
372 (const :tag
"Plain list item" item
)
373 (const :tag
"Checkbox item" checkitem
)
374 (const :tag
"Plain text" plain
)
375 (const :tag
"Table line" table-line
))
376 (choice :tag
"Target location"
378 (const :format
"" file
)
381 (const :format
"" id
)
383 (list :tag
"File & Headline"
384 (const :format
"" file
+headline
)
386 (string :tag
" Headline"))
387 (list :tag
"File & Outline path"
388 (const :format
"" file
+olp
)
390 (repeat :tag
"Outline path" :inline t
391 (string :tag
"Headline")))
392 (list :tag
"File & Regexp"
393 (const :format
"" file
+regexp
)
395 (regexp :tag
" Regexp"))
396 (list :tag
"File [ & Outline path ] & Date tree"
397 (const :format
"" file
+olp
+datetree
)
399 (option (repeat :tag
"Outline path" :inline t
400 (string :tag
"Headline"))))
401 (list :tag
"File & function"
402 (const :format
"" file
+function
)
404 (sexp :tag
" Function"))
405 (list :tag
"Current clocking task"
406 (const :format
"" clock
))
407 (list :tag
"Function"
408 (const :format
"" function
)
409 (sexp :tag
" Function")))
410 (choice :tag
"Template "
413 (const :format
"" file
)
414 (file :tag
"Template file"))
415 (list :tag
"Function"
416 (const :format
"" function
)
417 (function :tag
"Template function")))
419 ;; Give the most common options as checkboxes
420 :options
(((const :format
"%v " :prepend
) (const t
))
421 ((const :format
"%v " :immediate-finish
) (const t
))
422 ((const :format
"%v " :jump-to-captured
) (const t
))
423 ((const :format
"%v " :empty-lines
) (const 1))
424 ((const :format
"%v " :empty-lines-before
) (const 1))
425 ((const :format
"%v " :empty-lines-after
) (const 1))
426 ((const :format
"%v " :clock-in
) (const t
))
427 ((const :format
"%v " :clock-keep
) (const t
))
428 ((const :format
"%v " :clock-resume
) (const t
))
429 ((const :format
"%v " :time-prompt
) (const t
))
430 ((const :format
"%v " :tree-type
) (const week
))
431 ((const :format
"%v " :unnarrowed
) (const t
))
432 ((const :format
"%v " :table-line-pos
) (string))
433 ((const :format
"%v " :kill-buffer
) (const t
)))))))))
435 (defcustom org-capture-before-finalize-hook nil
436 "Hook that is run right before a capture process is finalized.
437 The capture buffer is still current when this hook runs and it is
438 widened to the entire buffer."
443 (defcustom org-capture-after-finalize-hook nil
444 "Hook that is run right after a capture process is finalized.
445 Suitable for window cleanup."
450 (defcustom org-capture-prepare-finalize-hook nil
451 "Hook that is run before the finalization starts.
452 The capture buffer is current and still narrowed."
457 (defcustom org-capture-bookmark t
458 "When non-nil, add a bookmark pointing at the last stored
459 position when capturing."
464 ;;; The property list for keeping information about the capture process
466 (defvar org-capture-plist nil
467 "Plist for the current capture process, global, to avoid having to pass it.")
469 (defvar org-capture-current-plist nil
470 "Local variable holding the plist in a capture buffer.
471 This is used to store the plist for use when finishing a capture process
472 because another such process might have changed the global variable by then.
474 Each time a new capture buffer has been set up, the global `org-capture-plist'
475 is copied to this variable, which is local in the indirect buffer.")
477 (defvar org-capture-clock-keep nil
478 "Local variable to store the value of the :clock-keep parameter.
479 This is needed in case org-capture-finalize is called interactively.")
481 (defun org-capture-put (&rest stuff
)
482 "Add properties to the capture property list `org-capture-plist'."
484 (setq org-capture-plist
(plist-put org-capture-plist
485 (pop stuff
) (pop stuff
)))))
486 (defun org-capture-get (prop &optional local
)
487 "Get properties from the capture property list `org-capture-plist'.
488 When LOCAL is set, use the local variable `org-capture-current-plist',
489 this is necessary after initialization of the capture process,
490 to avoid conflicts with other active capture processes."
491 (plist-get (if local org-capture-current-plist org-capture-plist
) prop
))
495 (defvar org-capture-mode-map
496 (let ((map (make-sparse-keymap)))
497 (define-key map
"\C-c\C-c" #'org-capture-finalize
)
498 (define-key map
"\C-c\C-k" #'org-capture-kill
)
499 (define-key map
"\C-c\C-w" #'org-capture-refile
)
501 "Keymap for `org-capture-mode', a minor mode.
502 Use this map to set additional keybindings for when Org mode is used
503 for a capture buffer.")
505 (defvar org-capture-mode-hook nil
506 "Hook for the `org-capture-mode' minor mode.")
508 (define-minor-mode org-capture-mode
509 "Minor mode for special key bindings in a capture buffer.
511 Turning on this mode runs the normal hook `org-capture-mode-hook'."
512 nil
" Cap" org-capture-mode-map
515 (substitute-command-keys
516 "\\<org-capture-mode-map>Capture buffer. Finish \
517 `\\[org-capture-finalize]', refile `\\[org-capture-refile]', \
518 abort `\\[org-capture-kill]'.")))
520 ;;; The main commands
522 (defvar org-capture-initial nil
)
523 (defvar org-capture-entry nil
)
526 (defun org-capture-string (string &optional keys
)
527 "Capture STRING with the template selected by KEYS."
528 (interactive "sInitial text: \n")
529 (let ((org-capture-initial string
)
530 (org-capture-entry (org-capture-select-template keys
)))
533 (defcustom org-capture-templates-contexts nil
534 "Alist of capture templates and valid contexts.
536 For example, if you have a capture template \"c\" and you want
537 this template to be accessible only from `message-mode' buffers,
540 \\='((\"c\" ((in-mode . \"message-mode\"))))
542 Here are the available contexts definitions:
544 in-file: command displayed only in matching files
545 in-mode: command displayed only in matching modes
546 not-in-file: command not displayed in matching files
547 not-in-mode: command not displayed in matching modes
548 in-buffer: command displayed only in matching buffers
549 not-in-buffer: command not displayed in matching buffers
550 [function]: a custom function taking no argument
552 If you define several checks, the agenda command will be
553 accessible if there is at least one valid check.
555 You can also bind a key to another capture template depending on
558 \\='((\"c\" \"d\" ((in-mode . \"message-mode\"))))
560 Here it means: in `message-mode buffers', use \"c\" as the
561 key for the capture template otherwise associated with \"d\".
562 \(The template originally associated with \"d\" is not displayed
563 to avoid duplicates.)"
566 :type
'(repeat (list :tag
"Rule"
567 (string :tag
" Capture key")
568 (string :tag
"Replace by template")
569 (repeat :tag
"Available when"
571 (cons :tag
"Condition"
573 (const :tag
"In file" in-file
)
574 (const :tag
"Not in file" not-in-file
)
575 (const :tag
"In buffer" in-buffer
)
576 (const :tag
"Not in buffer" not-in-buffer
)
577 (const :tag
"In mode" in-mode
)
578 (const :tag
"Not in mode" not-in-mode
))
580 (function :tag
"Custom function"))))))
582 (defcustom org-capture-use-agenda-date nil
583 "Non-nil means use the date at point when capturing from agendas.
584 When nil, you can still capture using the date at point with
585 `\\[org-agenda-capture]'."
591 (defun org-capture (&optional goto keys
)
593 \\<org-capture-mode-map>
594 This will let you select a template from `org-capture-templates', and
595 then file the newly captured information. The text is immediately
596 inserted at the target location, and an indirect buffer is shown where
597 you can edit it. Pressing `\\[org-capture-finalize]' brings you back to the \
599 state of Emacs, so that you can continue your work.
601 When called interactively with a `\\[universal-argument]' prefix argument \
603 capture anything, just go to the file/headline where the selected
604 template stores its notes.
606 With a `\\[universal-argument] \\[universal-argument]' prefix argument, go to \
607 the last note stored.
609 When called with a `C-0' (zero) prefix, insert a template at point.
611 When called with a `C-1' (one) prefix, force prompting for a date when
612 a datetree entry is made.
614 ELisp programs can set KEYS to a string associated with a template
615 in `org-capture-templates'. In this case, interactive selection
618 If `org-capture-use-agenda-date' is non-nil, capturing from the
619 agenda will use the date at point as the default date. Then, a
620 `C-1' prefix will tell the capture process to use the HH:MM time
621 of the day at point (if any) or the current HH:MM time."
623 (when (and org-capture-use-agenda-date
624 (eq major-mode
'org-agenda-mode
))
625 (setq org-overriding-default-time
626 (org-get-cursor-date (equal goto
1))))
628 ((equal goto
'(4)) (org-capture-goto-target))
629 ((equal goto
'(16)) (org-capture-goto-last-stored))
631 (let* ((orig-buf (current-buffer))
632 (annotation (if (and (boundp 'org-capture-link-is-already-stored
)
633 org-capture-link-is-already-stored
)
634 (plist-get org-store-link-plist
:annotation
)
635 (ignore-errors (org-store-link nil
))))
636 (entry (or org-capture-entry
(org-capture-select-template keys
)))
638 (setq initial
(or org-capture-initial
639 (and (org-region-active-p)
640 (buffer-substring (point) (mark)))))
641 (when (stringp initial
)
642 (remove-text-properties 0 (length initial
) '(read-only t
) initial
))
643 (when (stringp annotation
)
644 (remove-text-properties 0 (length annotation
)
645 '(read-only t
) annotation
))
648 (customize-variable 'org-capture-templates
))
650 (user-error "Abort"))
652 (org-capture-set-plist entry
)
653 (org-capture-get-template)
654 (org-capture-put :original-buffer orig-buf
655 :original-file
(or (buffer-file-name orig-buf
)
656 (and (featurep 'dired
)
659 :original-file-nondirectory
660 (and (buffer-file-name orig-buf
)
661 (file-name-nondirectory
662 (buffer-file-name orig-buf
)))
663 :annotation annotation
665 :return-to-wconf
(current-window-configuration)
667 (or org-overriding-default-time
669 (org-capture-set-target-location)
670 (condition-case error
671 (org-capture-put :template
(org-capture-fill-template))
673 (if (get-buffer "*Capture*") (kill-buffer "*Capture*"))
674 (error "Capture abort: %s" (error-message-string error
))))
676 (setq org-capture-clock-keep
(org-capture-get :clock-keep
))
679 (org-capture-insert-template-here)
680 (condition-case error
681 (org-capture-place-template
682 (eq (car (org-capture-get :target
)) 'function
))
684 (when (and (buffer-base-buffer (current-buffer))
685 (string-prefix-p "CAPTURE-" (buffer-name)))
686 (kill-buffer (current-buffer)))
687 (set-window-configuration (org-capture-get :return-to-wconf
))
688 (error "Capture template `%s': %s"
689 (org-capture-get :key
)
690 (error-message-string error
))))
691 (when (and (derived-mode-p 'org-mode
) (org-capture-get :clock-in
))
694 (when (org-clock-is-active)
695 (org-capture-put :interrupted-clock
696 (copy-marker org-clock-marker
)))
698 (setq-local org-capture-clock-was-started t
))
699 (error "Could not start the clock in this capture buffer")))
700 (when (org-capture-get :immediate-finish
)
701 (org-capture-finalize)))))))))
703 (defun org-capture-get-template ()
704 "Get the template from a file or a function if necessary."
705 (let ((txt (org-capture-get :template
)) file
)
707 ((and (listp txt
) (eq (car txt
) 'file
))
709 (setq file
(expand-file-name (nth 1 txt
) org-directory
)))
710 (setq txt
(org-file-contents file
))
711 (setq txt
(format "* Template file %s not found" (nth 1 txt
)))))
712 ((and (listp txt
) (eq (car txt
) 'function
))
713 (if (fboundp (nth 1 txt
))
714 (setq txt
(funcall (nth 1 txt
)))
715 (setq txt
(format "* Template function %s not found" (nth 1 txt
)))))
716 ((not txt
) (setq txt
""))
718 (t (setq txt
"* Invalid capture template")))
719 (org-capture-put :template txt
)))
721 (defun org-capture-finalize (&optional stay-with-capture
)
722 "Finalize the capture process.
723 With prefix argument STAY-WITH-CAPTURE, jump to the location of the
724 captured item after finalizing."
726 (when (org-capture-get :jump-to-captured
)
727 (setq stay-with-capture t
))
728 (unless (and org-capture-mode
729 (buffer-base-buffer (current-buffer)))
730 (error "This does not seem to be a capture buffer for Org mode"))
732 (run-hooks 'org-capture-prepare-finalize-hook
)
734 ;; Did we start the clock in this capture buffer?
735 (when (and org-capture-clock-was-started
737 (eq (marker-buffer org-clock-marker
) (buffer-base-buffer))
738 (>= org-clock-marker
(point-min))
739 (< org-clock-marker
(point-max)))
740 ;; Looks like the clock we started is still running.
741 (if org-capture-clock-keep
742 ;; User may have completed clocked heading from the template.
743 ;; Refresh clock mode line.
744 (org-clock-update-mode-line t
)
745 ;; Clock out. Possibly resume interrupted clock.
746 (let (org-log-note-clock-out) (org-clock-out))
747 (when (and (org-capture-get :clock-resume
'local
)
748 (markerp (org-capture-get :interrupted-clock
'local
))
749 (buffer-live-p (marker-buffer
750 (org-capture-get :interrupted-clock
'local
))))
751 (let ((clock-in-task (org-capture-get :interrupted-clock
'local
)))
752 (org-with-point-at clock-in-task
(org-clock-in)))
753 (message "Interrupted clock has been resumed"))))
755 (let ((abort-note nil
))
756 ;; Store the size of the capture buffer
757 (org-capture-put :captured-entry-size
(- (point-max) (point-min)))
759 ;; Store the insertion point in the target buffer
760 (org-capture-put :insertion-point
(point))
763 (let ((beg (org-capture-get :begin-marker
'local
))
764 (end (org-capture-get :end-marker
'local
)))
765 (if (not (and beg end
)) (setq abort-note
'dirty
)
767 (org-with-wide-buffer (kill-region beg end
))))
769 ;; Postprocessing: Update Statistics cookies, do the sorting
770 (when (derived-mode-p 'org-mode
)
772 (when (ignore-errors (org-back-to-heading))
773 (org-update-parent-todo-statistics)
774 (org-update-checkbox-count)))
775 ;; FIXME Here we should do the sorting
776 ;; If we have added a table line, maybe recompute?
777 (when (and (eq (org-capture-get :type
'local
) 'table-line
)
779 (if (not (org-table-get-stored-formulas)) (org-table-align)
780 ;; Adjust formulas, if necessary. We assume a non-nil
781 ;; `:immediate-finish' means that no confirmation is
782 ;; required. Else, obey `org-table-fix-formulas-confirm'.
784 ;; The delta required to fix formulas depends on the
785 ;; number of rows inserted by the template.
786 (when (or (org-capture-get :immediate-finish
)
787 (not org-table-fix-formulas-confirm
)
788 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
789 (org-table-fix-formulas
790 "@" nil
(1- (org-table-current-dline))
791 (count-lines (org-capture-get :begin-marker
'local
)
792 (org-capture-get :end-marker
'local
))))
793 (org-table-recalculate 'all
)))) ;FIXME: should we iterate?
794 ;; Store this place as the last one where we stored something
795 ;; Do the marking in the base buffer, so that it makes sense after
796 ;; the indirect buffer has been killed.
797 (org-capture-store-last-position)
800 (run-hooks 'org-capture-before-finalize-hook
))
802 (when (org-capture-get :decrypted
)
804 (goto-char (org-capture-get :decrypted
))
805 (org-encrypt-entry)))
807 (unless (org-capture-get :no-save
) (save-buffer))
809 (let ((return-wconf (org-capture-get :return-to-wconf
'local
))
810 (new-buffer (org-capture-get :new-buffer
'local
))
811 (kill-buffer (org-capture-get :kill-buffer
'local
))
812 (base-buffer (buffer-base-buffer (current-buffer))))
814 ;; Kill the indirect buffer
815 (kill-buffer (current-buffer))
817 ;; Narrow back the target buffer to its previous state
818 (with-current-buffer (org-capture-get :buffer
)
819 (let ((reg (org-capture-get :initial-target-region
))
820 (pos (org-capture-get :initial-target-position
))
821 (ipt (org-capture-get :insertion-point
))
822 (size (org-capture-get :captured-entry-size
)))
825 (cond ((< ipt
(car reg
))
826 ;; insertion point is before the narrowed region
827 (narrow-to-region (+ size
(car reg
)) (+ size
(cdr reg
))))
829 ;; insertion point is after the narrowed region
830 (narrow-to-region (car reg
) (cdr reg
)))
832 ;; insertion point is within the narrowed region
833 (narrow-to-region (car reg
) (+ size
(cdr reg
)))))
834 ;; now place back the point at its original position
835 (if (< ipt
(car reg
))
836 (goto-char (+ size pos
))
837 (goto-char (if (< ipt pos
) (+ size pos
) pos
))))))
839 ;; Kill the target buffer if that is desired
840 (when (and base-buffer new-buffer kill-buffer
)
841 (with-current-buffer base-buffer
(save-buffer))
842 (kill-buffer base-buffer
))
844 ;; Restore the window configuration before capture
845 (set-window-configuration return-wconf
))
847 (run-hooks 'org-capture-after-finalize-hook
)
853 (message "Capture process aborted and target buffer cleaned up"))
855 (error "Capture process aborted, but target buffer could not be \
856 cleaned up correctly"))))
858 (org-capture-goto-last-stored)))
859 ;; Return if we did store something
862 (defun org-capture-refile ()
863 "Finalize the current capture and then refile the entry.
864 Refiling is done from the base buffer, because the indirect buffer is then
865 already gone. Any prefix argument will be passed to the refile command."
867 (unless (eq (org-capture-get :type
'local
) 'entry
)
868 (user-error "Refiling from a capture buffer makes only sense \
869 for `entry'-type templates"))
870 (let* ((base (or (buffer-base-buffer) (current-buffer)))
872 (org-capture-is-refiling t
)
873 (kill-buffer (org-capture-get :kill-buffer
'local
))
874 (jump-to-captured (org-capture-get :jump-to-captured
'local
)))
875 ;; Since `org-capture-finalize' may alter buffer contents (e.g.,
876 ;; empty lines) around entry, use a marker to refer to the
877 ;; headline to be refiled. Place the marker in the base buffer,
878 ;; as the current indirect one is going to be killed.
879 (set-marker pos
(save-excursion (org-back-to-heading t
) (point)) base
)
880 ;; `org-capture-finalize' calls `org-capture-goto-last-stored' too
881 ;; early. We want to wait for the refiling to be over, so we
882 ;; control when the latter function is called.
883 (org-capture-put :kill-buffer nil
:jump-to-captured nil
)
884 (org-capture-finalize)
885 (save-window-excursion
886 (with-current-buffer base
887 (org-with-point-at pos
888 (call-interactively 'org-refile
))))
890 (with-current-buffer base
(save-buffer))
892 (when jump-to-captured
(org-capture-goto-last-stored))))
894 (defun org-capture-kill ()
895 "Abort the current capture process."
897 ;; FIXME: This does not do the right thing, we need to remove the
898 ;; new stuff by hand it is easy: undo, then kill the buffer
899 (let ((org-note-abort t
)
900 (org-capture-before-finalize-hook nil
))
901 (org-capture-finalize)))
903 (defun org-capture-goto-last-stored ()
904 "Go to the location where the last capture note was stored."
906 (org-goto-marker-or-bmk org-capture-last-stored-marker
907 (plist-get org-bookmark-names-plist
909 (message "This is the last note stored by a capture process"))
911 ;;; Supporting functions for handling the process
913 (defun org-capture-put-target-region-and-position ()
914 "Store the initial region with `org-capture-put'."
916 :initial-target-region
917 ;; Check if the buffer is currently narrowed
918 (when (org-buffer-narrowed-p)
919 (cons (point-min) (point-max))))
920 ;; store the current point
921 (org-capture-put :initial-target-position
(point)))
923 (defvar org-time-was-given
) ; dynamically scoped parameter
924 (defun org-capture-set-target-location (&optional target
)
925 "Find TARGET buffer and position.
926 Store them in the capture property list."
927 (let ((target-entry-p t
))
929 (pcase (or target
(org-capture-get :target
))
931 (set-buffer (org-capture-target-buffer path
))
932 (org-capture-put-target-region-and-position)
934 (setq target-entry-p nil
))
936 (pcase (org-id-find id
)
937 (`(,path .
,position
)
938 (set-buffer (org-capture-target-buffer path
))
940 (org-capture-put-target-region-and-position)
941 (goto-char position
))
942 (_ (error "Cannot find target ID \"%s\"" id
))))
943 (`(file+headline
,path
,headline
)
944 (set-buffer (org-capture-target-buffer path
))
945 ;; Org expects the target file to be in Org mode, otherwise
946 ;; it throws an error. However, the default notes files
947 ;; should work out of the box. In this case, we switch it to
949 (unless (derived-mode-p 'org-mode
)
951 (format "Capture requirement: switching buffer %S to Org mode"
954 (org-capture-put-target-region-and-position)
956 (goto-char (point-min))
957 (if (re-search-forward (format org-complex-heading-regexp-format
958 (regexp-quote headline
))
961 (goto-char (point-max))
962 (unless (bolp) (insert "\n"))
963 (insert "* " headline
"\n")
964 (beginning-of-line 0)))
965 (`(file+olp
,path .
,outline-path
)
966 (let ((m (org-find-olp (cons (org-capture-expand-file path
)
968 (set-buffer (marker-buffer m
))
969 (org-capture-put-target-region-and-position)
973 (`(file+regexp
,path
,regexp
)
974 (set-buffer (org-capture-target-buffer path
))
975 (org-capture-put-target-region-and-position)
977 (goto-char (point-min))
978 (if (not (re-search-forward regexp nil t
))
979 (error "No match for target regexp in file %s" path
)
980 (goto-char (if (org-capture-get :prepend
)
983 (org-capture-put :exact-position
(point))
985 (and (derived-mode-p 'org-mode
) (org-at-heading-p)))))
986 (`(file+olp
+datetree
,path .
,outline-path
)
987 (let ((m (if outline-path
988 (org-find-olp (cons (org-capture-expand-file path
)
990 (set-buffer (org-capture-target-buffer path
))
992 (set-buffer (marker-buffer m
))
993 (org-capture-put-target-region-and-position)
997 (require 'org-datetree
)
998 (org-capture-put-target-region-and-position)
1000 ;; Make a date/week tree entry, with the current date (or
1001 ;; yesterday, if we are extending dates for a couple of hours)
1003 (if (eq (org-capture-get :tree-type
) 'week
)
1004 #'org-datetree-find-iso-week-create
1005 #'org-datetree-find-date-create
)
1006 (calendar-gregorian-from-absolute
1008 (org-overriding-default-time
1009 ;; Use the overriding default time.
1010 (time-to-days org-overriding-default-time
))
1011 ((or (org-capture-get :time-prompt
)
1012 (equal current-prefix-arg
1))
1014 (let ((prompt-time (org-read-date
1015 nil t nil
"Date for tree entry:")))
1018 (cond ((and (or (not (boundp 'org-time-was-given
))
1019 (not org-time-was-given
))
1020 (not (= (time-to-days prompt-time
) (org-today))))
1021 ;; Use 00:00 when no time is given for another
1023 (apply #'encode-time
1024 (append `(0 0 ,org-extend-today-until
)
1025 (cl-cdddr (decode-time prompt-time
)))))
1026 ((string-match "\\([^ ]+\\)--?[^ ]+[ ]+\\(.*\\)"
1027 org-read-date-final-answer
)
1028 ;; Replace any time range by its start.
1029 (apply #'encode-time
1030 (org-read-date-analyze
1031 (replace-match "\\1 \\2" nil nil
1032 org-read-date-final-answer
)
1033 prompt-time
(decode-time prompt-time
))))
1035 (time-to-days prompt-time
)))
1037 ;; Current date, possibly corrected for late night
1040 ;; the following is the keep-restriction argument for
1041 ;; org-datetree-find-date-create
1042 (when outline-path
'subtree-at-point
))))
1043 (`(file+function
,path
,function
)
1044 (set-buffer (org-capture-target-buffer path
))
1045 (org-capture-put-target-region-and-position)
1048 (org-capture-put :exact-position
(point))
1049 (setq target-entry-p
1050 (and (derived-mode-p 'org-mode
) (org-at-heading-p))))
1053 (org-capture-put :exact-position
(point))
1054 (setq target-entry-p
1055 (and (derived-mode-p 'org-mode
) (org-at-heading-p))))
1057 (if (and (markerp org-clock-hd-marker
)
1058 (marker-buffer org-clock-hd-marker
))
1059 (progn (set-buffer (marker-buffer org-clock-hd-marker
))
1060 (org-capture-put-target-region-and-position)
1062 (goto-char org-clock-hd-marker
))
1063 (error "No running clock that could be used as capture target")))
1064 (target (error "Invalid capture target specification: %S" target
)))
1066 (org-capture-put :buffer
(current-buffer)
1068 :target-entry-p target-entry-p
1070 (and (featurep 'org-crypt
)
1071 (org-at-encrypted-entry-p)
1074 (and (org-back-to-heading t
) (point))))))))
1076 (defun org-capture-expand-file (file)
1077 "Expand functions, symbols and file names for FILE.
1078 When FILE is a function, call it. When it is a form, evaluate
1079 it. When it is a variable, return its value. When it is
1080 a string, treat it as a file name, possibly expanding it
1081 according to `org-directory', and return it. If it is the empty
1082 string, however, return `org-default-notes-file'. In any other
1083 case, raise an error."
1084 (let ((location (cond ((equal file
"") org-default-notes-file
)
1085 ((stringp file
) (expand-file-name file org-directory
))
1086 ((functionp file
) (funcall file
))
1087 ((and (symbolp file
) (boundp file
)) (symbol-value file
))
1089 (or (org-string-nw-p location
)
1090 (error "Invalid file location: %S" location
))))
1092 (defun org-capture-target-buffer (file)
1093 "Get a buffer for FILE.
1094 FILE is a generalized file location, as handled by
1095 `org-capture-expand-file'."
1096 (let ((file (org-capture-expand-file file
)))
1097 (or (org-find-base-buffer-visiting file
)
1098 (progn (org-capture-put :new-buffer t
)
1099 (find-file-noselect file
)))))
1101 (defun org-capture-place-template (&optional inhibit-wconf-store
)
1102 "Insert the template at the target location, and display the buffer.
1103 When `inhibit-wconf-store', don't store the window configuration, as it
1104 may have been stored before."
1105 (unless inhibit-wconf-store
1106 (org-capture-put :return-to-wconf
(current-window-configuration)))
1107 (delete-other-windows)
1108 (org-switch-to-buffer-other-window
1109 (org-capture-get-indirect-buffer (org-capture-get :buffer
) "CAPTURE"))
1112 (goto-char (org-capture-get :pos
))
1113 (setq-local outline-level
'org-outline-level
)
1114 (pcase (org-capture-get :type
)
1115 ((or `nil
`entry
) (org-capture-place-entry))
1116 (`table-line
(org-capture-place-table-line))
1117 (`plain
(org-capture-place-plain-text))
1118 (`item
(org-capture-place-item))
1119 (`checkitem
(org-capture-place-item)))
1120 (org-capture-mode 1)
1121 (setq-local org-capture-current-plist org-capture-plist
))
1123 (defun org-capture-place-entry ()
1124 "Place the template as a new Org entry."
1125 (let ((template (org-capture-get :template
))
1126 (reversed?
(org-capture-get :prepend
))
1128 (org-capture-verify-tree template
)
1129 (when (org-capture-get :exact-position
)
1130 (goto-char (org-capture-get :exact-position
)))
1132 ;; Insert as a child of the current entry.
1133 ((org-capture-get :target-entry-p
)
1134 (setq level
(org-get-valid-level
1135 (if (org-at-heading-p) (org-outline-level) 1)
1137 (if reversed?
(outline-next-heading) (org-end-of-subtree t t
)))
1138 ;; Insert as a top-level entry at the beginning of the file.
1140 (goto-char (point-min))
1141 (unless (org-at-heading-p) (outline-next-heading)))
1142 ;; Otherwise, insert as a top-level entry at the end of the file.
1143 (t (goto-char (point-max))))
1144 (let ((origin (point)))
1145 (unless (bolp) (insert "\n"))
1146 (org-capture-empty-lines-before)
1147 (let ((beg (point)))
1148 (org-paste-subtree level template
'for-yank
)
1149 (org-capture-position-for-last-stored beg
)
1150 (let ((end (if (org-at-heading-p) (line-end-position 0) (point))))
1151 (org-capture-empty-lines-after)
1152 (unless (org-at-heading-p) (outline-next-heading))
1153 (org-capture-mark-kill-region origin
(point))
1154 (org-capture-narrow beg end
)
1155 (when (or (search-backward "%?" beg t
)
1156 (search-forward "%?" end t
))
1157 (replace-match "")))))))
1159 (defun org-capture-place-item ()
1160 "Place the template as a new plain list item."
1161 (let ((prepend?
(org-capture-get :prepend
))
1162 (template (org-remove-indentation (org-capture-get :template
)))
1164 ;; Make template suitable for insertion. In particular, add
1165 ;; a main bullet if it is missing.
1166 (unless (string-match-p (concat "\\`" (org-item-re)) template
)
1167 (setq template
(concat "- " (mapconcat #'identity
1168 (split-string template
"\n")
1170 ;; Delimit the area where we should look for a plain list.
1171 (pcase-let ((`(,beg .
,end
)
1172 (cond ((org-capture-get :exact-position
)
1173 ;; User gave a specific position. Start
1174 ;; looking for lists from here.
1175 (cons (save-excursion
1176 (goto-char (org-capture-get :exact-position
))
1177 (line-beginning-position))
1178 (org-entry-end-position)))
1179 ((org-capture-get :target-entry-p
)
1180 ;; At a heading, limit search to its body.
1181 (cons (line-beginning-position 2)
1182 (org-entry-end-position)))
1184 ;; Table is not necessarily under a heading.
1185 ;; Search whole buffer.
1186 (cons (point-min) (point-max))))))
1187 ;; Find the first plain list in the delimited area.
1189 (let ((item-regexp (org-item-beginning-re)))
1191 (while (re-search-forward item-regexp end t
)
1192 (when (setq item
(org-element-lineage
1193 (org-element-at-point) '(plain-list) t
))
1194 (goto-char (org-element-property (if prepend?
:post-affiliated
1198 ;; No list found. Move to the location when to insert
1199 ;; template. Skip planning info and properties drawers, if
1201 (goto-char (cond ((not prepend?
) end
)
1202 ((org-before-first-heading-p) beg
)
1203 (t (max (save-excursion
1204 (org-end-of-meta-data)
1208 (let ((origin (point)))
1209 (unless (bolp) (insert "\n"))
1210 ;; When a new list is created, always obey to `:empty-lines' and
1213 ;; When capturing in an existing list, do not change blank lines
1214 ;; above or below the list; consider it to be a stable
1215 ;; structure. However, we can control how many blank lines
1216 ;; separate items. So obey to `:empty-lines' between items as
1217 ;; long as it does not insert more than one empty line. In the
1218 ;; specific case of empty lines above, it means we only obey the
1219 ;; parameter when appending an item.
1220 (unless (and item prepend?
)
1221 (org-capture-empty-lines-before
1224 (min 1 (or (org-capture-get :empty-lines-before
)
1225 (org-capture-get :empty-lines
)
1227 (org-capture-position-for-last-stored (point))
1228 (let ((beg (line-beginning-position))
1230 (insert (org-trim template
) "\n")
1233 (let ((i (save-excursion
1234 (goto-char (org-element-property :post-affiliated item
))
1235 (current-indentation))))
1239 (while (< (point) end
)
1242 ;; Pre-pending an item could change the type of the list
1243 ;; if there is a mismatch. In this situation,
1244 ;; prioritize the existing list.
1246 (let ((ordered?
(eq 'ordered
(org-element-property :type item
))))
1247 (when (org-xor ordered?
1248 (string-match-p "\\`[A-Za-z0-9]\\([.)]\\)"
1250 (org-cycle-list-bullet (if ordered?
"1." "-")))))
1251 ;; Eventually repair the list for proper indentation and
1253 (org-list-repair))))
1254 ;; Limit number of empty lines. See above for details.
1255 (unless (and item
(not prepend?
))
1256 (org-capture-empty-lines-after
1259 (min 1 (or (org-capture-get :empty-lines-after
)
1260 (org-capture-get :empty-lines
)
1262 (org-capture-mark-kill-region origin
(point))
1263 ;; ITEM always end with a newline character. Make sure we do
1264 ;; not narrow at the beginning of the next line, possibly
1265 ;; altering its structure (e.g., when it is a headline).
1266 (org-capture-narrow beg
(1- end
))
1267 (when (or (search-backward "%?" beg t
)
1268 (search-forward "%?" end t
))
1269 (replace-match ""))))))
1271 (defun org-capture-place-table-line ()
1272 "Place the template as a table line."
1273 (require 'org-table
)
1275 (pcase (org-trim (org-capture-get :template
))
1276 ((pred (string-match-p org-table-border-regexp
))
1277 "| %?Bad template |")
1278 (text (concat text
"\n"))))
1279 (table-line-pos (org-capture-get :table-line-pos
))
1282 ((org-capture-get :exact-position
)
1283 (setq beg
(org-capture-get :exact-position
))
1284 (setq end
(save-excursion (outline-next-heading) (point))))
1285 ((not (org-capture-get :target-entry-p
))
1286 ;; Table is not necessarily under a heading. Find first table
1288 (setq beg
(point-min) end
(point-max)))
1290 ;; We are at a heading, limit search to the body.
1291 (setq beg
(line-beginning-position 2))
1292 (setq end
(save-excursion (outline-next-heading) (point)))))
1294 ;; Narrow to the table, possibly creating one if necessary.
1296 (while (re-search-forward org-table-dataline-regexp end t
)
1297 (pcase (org-element-lineage (org-element-at-point) '(table) t
)
1299 ((pred (lambda (e) (eq 'table.el
(org-element-property :type e
))))
1302 (goto-char (org-element-property :contents-end table
))
1303 (narrow-to-region (org-element-property :post-affiliated table
)
1306 ;; No table found. Create it with an empty header.
1308 (unless (bolp) (insert "\n"))
1309 (let ((origin (point)))
1310 (insert "| |\n|----|\n")
1311 (narrow-to-region origin
(point))))
1312 ;; In the current table, find the appropriate location for TEXT.
1314 ((and table-line-pos
1315 (string-match "\\(I+\\)\\([-+][0-9]+\\)" table-line-pos
))
1316 (goto-char (point-min))
1320 (save-match-data (org-table-analyze))
1321 (aref org-table-hlines
1322 (- (match-end 1) (match-beginning 1))))
1324 (error "Invalid table line specification %S" table-line-pos
))))
1325 (delta (string-to-number (match-string 2 table-line-pos
))))
1326 (forward-line (+ line delta
(if (< delta
0) 0 -
1)))
1327 (forward-line))) ;insert below
1328 ((org-capture-get :prepend
)
1329 (goto-char (point-min))
1331 ((not (re-search-forward org-table-hline-regexp nil t
)))
1332 ((re-search-forward org-table-dataline-regexp nil t
) (beginning-of-line))
1333 (t (goto-char (org-table-end)))))
1335 (goto-char (org-table-end))))
1336 ;; Insert text and position point according to template.
1337 (let ((origin (point)))
1338 (unless (bolp) (insert "\n"))
1340 (end (save-excursion
1343 (org-capture-position-for-last-stored 'table-line
)
1344 (org-capture-mark-kill-region origin end
)
1345 ;; TEXT is guaranteed to end with a newline character. Ignore
1346 ;; it when narrowing so as to not alter data on the next line.
1347 (org-capture-narrow beg
(1- end
))
1348 (when (or (search-backward "%?" beg t
)
1349 (search-forward "%?" end t
))
1350 (replace-match ""))))))
1352 (defun org-capture-place-plain-text ()
1353 "Place the template plainly.
1354 If the target locator points at an Org node, place the template into
1355 the text of the entry, before the first child. If not, place the
1356 template at the beginning or end of the file.
1357 Of course, if exact position has been required, just put it there."
1359 ((org-capture-get :exact-position
)
1360 (goto-char (org-capture-get :exact-position
)))
1361 ((org-capture-get :target-entry-p
)
1362 ;; Place the text into this entry.
1363 (if (org-capture-get :prepend
)
1364 ;; Skip meta data and drawers.
1365 (org-end-of-meta-data t
)
1366 ;; Go to end of the entry text, before the next headline.
1367 (outline-next-heading)))
1369 ;; Beginning or end of file.
1370 (goto-char (if (org-capture-get :prepend
) (point-min) (point-max)))))
1371 (let ((origin (point)))
1372 (unless (bolp) (insert "\n"))
1373 (org-capture-empty-lines-before)
1374 (org-capture-position-for-last-stored (point))
1375 (let ((beg (point)))
1376 (insert (org-capture-get :template
))
1377 (unless (bolp) (insert "\n"))
1378 ;; Ignore the final newline character so as to not alter data
1379 ;; after inserted text. Yet, if the template is empty, make
1380 ;; sure END matches BEG instead of pointing before it.
1381 (let ((end (max beg
(1- (point)))))
1382 (org-capture-empty-lines-after)
1383 (org-capture-mark-kill-region origin
(point))
1384 (org-capture-narrow beg end
)
1385 (when (or (search-backward "%?" beg t
)
1386 (search-forward "%?" end t
))
1387 (replace-match ""))))))
1389 (defun org-capture-mark-kill-region (beg end
)
1390 "Mark the region that will have to be killed when aborting capture."
1391 (let ((m1 (copy-marker beg
))
1392 (m2 (copy-marker end t
)))
1393 (org-capture-put :begin-marker m1
)
1394 (org-capture-put :end-marker m2
)))
1396 (defun org-capture-position-for-last-stored (where)
1397 "Memorize the position that should later become the position of last capture."
1400 (org-capture-put :position-for-last-stored
1401 (move-marker (make-marker) where
1402 (or (buffer-base-buffer (current-buffer))
1403 (current-buffer)))))
1404 ((eq where
'table-line
)
1405 (org-capture-put :position-for-last-stored
1407 (org-table-current-dline))))
1408 (t (error "This should not happen"))))
1410 (defun org-capture-store-last-position ()
1411 "Store the last-captured position."
1412 (let* ((where (org-capture-get :position-for-last-stored
'local
))
1415 (prog1 (marker-position where
)
1416 (move-marker where nil
)))
1417 ((and (listp where
) (eq (car where
) 'table-line
))
1418 (if (org-at-table-p)
1420 (org-table-goto-line (nth 1 where
))
1423 (with-current-buffer (buffer-base-buffer (current-buffer))
1424 (org-with-point-at pos
1425 (when org-capture-bookmark
1426 (let ((bookmark (plist-get org-bookmark-names-plist
:last-capture
)))
1427 (when bookmark
(with-demoted-errors (bookmark-set bookmark
)))))
1428 (move-marker org-capture-last-stored-marker
(point))))))
1430 (defun org-capture-narrow (beg end
)
1431 "Narrow, unless configuration says not to narrow."
1432 (unless (org-capture-get :unnarrowed
)
1433 (narrow-to-region beg end
)
1436 (defun org-capture-empty-lines-before (&optional n
)
1437 "Set the correct number of empty lines before the insertion point.
1438 Point will be after the empty lines, so insertion can directly be done."
1439 (setq n
(or n
(org-capture-get :empty-lines-before
)
1440 (org-capture-get :empty-lines
) 0))
1441 (let ((pos (point)))
1442 (org-back-over-empty-lines)
1443 (delete-region (point) pos
)
1444 (when (> n
0) (newline n
))))
1446 (defun org-capture-empty-lines-after (&optional n
)
1447 "Set the correct number of empty lines after the inserted string.
1448 Point will remain at the first line after the inserted text."
1449 (setq n
(or n
(org-capture-get :empty-lines-after
)
1450 (org-capture-get :empty-lines
) 0))
1451 (org-back-over-empty-lines)
1452 (while (looking-at "[ \t]*\n") (replace-match ""))
1453 (let ((pos (point)))
1454 (when (> n
0) (newline n
))
1457 (defvar org-clock-marker
) ; Defined in org.el
1459 (defun org-capture-insert-template-here ()
1460 "Insert the capture template at point."
1461 (let* ((template (org-capture-get :template
))
1462 (type (org-capture-get :type
))
1464 (unless (bolp) (insert "\n"))
1467 ((and (eq type
'entry
) (derived-mode-p 'org-mode
))
1468 (org-capture-verify-tree (org-capture-get :template
))
1469 (org-paste-subtree nil template t
))
1470 ((and (memq type
'(item checkitem
))
1471 (derived-mode-p 'org-mode
)
1472 (save-excursion (skip-chars-backward " \t\n")
1477 (skip-chars-backward " ")
1478 (skip-chars-backward "-+*0123456789).")
1479 (delete-region (point) (point-at-eol))
1481 (org-remove-indentation template
)
1483 (org-capture-empty-lines-after)
1489 (org-capture-empty-lines-after)
1490 (skip-chars-forward " \t\n")
1491 (unless (eobp) (beginning-of-line))))
1494 (when (re-search-forward "%\\?" end t
)
1495 (replace-match ""))))
1497 (defun org-capture-set-plist (entry)
1498 "Initialize the property list from the template definition."
1499 (setq org-capture-plist
(copy-sequence (nthcdr 5 entry
)))
1500 (org-capture-put :key
(car entry
) :description
(nth 1 entry
)
1501 :target
(nth 3 entry
))
1502 (let ((txt (nth 4 entry
)) (type (or (nth 2 entry
) 'entry
)))
1503 (when (or (not txt
) (and (stringp txt
) (not (string-match "\\S-" txt
))))
1504 ;; The template may be empty or omitted for special types.
1505 ;; Here we insert the default templates for such cases.
1507 ((eq type
'item
) (setq txt
"- %?"))
1508 ((eq type
'checkitem
) (setq txt
"- [ ] %?"))
1509 ((eq type
'table-line
) (setq txt
"| %? |"))
1510 ((member type
'(nil entry
)) (setq txt
"* %?\n %a"))))
1511 (org-capture-put :template txt
:type type
)))
1513 (defun org-capture-goto-target (&optional template-key
)
1514 "Go to the target location of a capture template.
1515 The user is queried for the template."
1517 (let ((entry (org-capture-select-template template-key
)))
1518 (unless entry
(error "No capture template selected"))
1519 (org-capture-set-plist entry
)
1520 (org-capture-set-target-location)
1521 (pop-to-buffer-same-window (org-capture-get :buffer
))
1522 (goto-char (org-capture-get :pos
))))
1524 (defun org-capture-get-indirect-buffer (&optional buffer prefix
)
1525 "Make an indirect buffer for a capture process.
1526 Use PREFIX as a prefix for the name of the indirect buffer."
1527 (setq buffer
(or buffer
(current-buffer)))
1528 (let ((n 1) (base (buffer-name buffer
)) bname
)
1529 (setq bname
(concat prefix
"-" base
))
1530 (while (buffer-live-p (get-buffer bname
))
1531 (setq bname
(concat prefix
"-" (number-to-string (cl-incf n
)) "-" base
)))
1533 (make-indirect-buffer buffer bname
'clone
)
1535 (let ((buf (make-indirect-buffer buffer bname
)))
1536 (with-current-buffer buf
(org-mode))
1539 (defun org-capture-verify-tree (tree)
1540 "Throw error if TREE is not a valid tree."
1541 (unless (org-kill-is-subtree-p tree
)
1542 (error "Template is not a valid Org entry or tree")))
1544 ;;; The template code
1545 (defun org-capture-select-template (&optional keys
)
1546 "Select a capture template.
1547 Lisp programs can force the template by setting KEYS to a string."
1548 (let ((org-capture-templates
1549 (or (org-contextualize-keys
1550 (org-capture-upgrade-templates org-capture-templates
)
1551 org-capture-templates-contexts
)
1552 '(("t" "Task" entry
(file+headline
"" "Tasks")
1553 "* TODO %?\n %u\n %a")))))
1555 (or (assoc keys org-capture-templates
)
1556 (error "No capture template referred to by \"%s\" keys" keys
))
1557 (org-mks org-capture-templates
1558 "Select a capture template\n========================="
1560 '(("C" "Customize org-capture-templates")
1563 (defvar org-capture--clipboards nil
1564 "List various clipboards values.")
1566 (defun org-capture-fill-template (&optional template initial annotation
)
1567 "Fill a template and return the filled template as a string.
1568 The template may still contain \"%?\" for cursor positioning."
1569 (let* ((template (or template
(org-capture-get :template
)))
1570 (buffer (org-capture-get :buffer
))
1571 (file (buffer-file-name (or (buffer-base-buffer buffer
) buffer
)))
1572 (time (let* ((c (or (org-capture-get :default-time
) (current-time)))
1573 (d (decode-time c
)))
1574 (if (< (nth 2 d
) org-extend-today-until
)
1575 (encode-time 0 59 23 (1- (nth 3 d
)) (nth 4 d
) (nth 5 d
))
1577 (v-t (format-time-string (org-time-stamp-format nil
) time
))
1578 (v-T (format-time-string (org-time-stamp-format t
) time
))
1579 (v-u (format-time-string (org-time-stamp-format nil t
) time
))
1580 (v-U (format-time-string (org-time-stamp-format t t
) time
))
1581 (v-c (and kill-ring
(current-kill 0)))
1582 (v-x (or (org-get-x-clipboard 'PRIMARY
)
1583 (org-get-x-clipboard 'CLIPBOARD
)
1584 (org-get-x-clipboard 'SECONDARY
)
1585 "")) ;ensure it is a string
1586 ;; `initial' and `annotation' might have been passed. But if
1587 ;; the property list has them, we prefer those values.
1588 (v-i (or (plist-get org-store-link-plist
:initial
)
1589 (and (stringp initial
) (org-no-properties initial
))
1590 (org-capture-get :initial
)
1593 (let ((a (or (plist-get org-store-link-plist
:annotation
)
1595 (org-capture-get :annotation
)
1597 ;; Is the link empty? Then we do not want it...
1598 (if (equal a
"[[]]") "" a
)))
1599 (l-re "\\[\\[\\(.*?\\)\\]\\(\\[.*?\\]\\)?\\]")
1600 (v-A (if (and v-a
(string-match l-re v-a
))
1601 (replace-match "[[\\1][%^{Link description}]]" nil nil v-a
)
1603 (v-l (if (and v-a
(string-match l-re v-a
))
1604 (replace-match "\\1" nil nil v-a
)
1606 (v-n user-full-name
)
1607 (v-k (if (marker-buffer org-clock-marker
)
1608 (org-no-properties org-clock-heading
)
1610 (v-K (if (marker-buffer org-clock-marker
)
1611 (org-link-make-string
1613 (buffer-file-name (marker-buffer org-clock-marker
))
1617 (v-f (or (org-capture-get :original-file-nondirectory
) ""))
1618 (v-F (or (org-capture-get :original-file
) ""))
1619 (org-capture--clipboards
1622 (org-get-x-clipboard 'PRIMARY
)
1623 (org-get-x-clipboard 'CLIPBOARD
)
1624 (org-get-x-clipboard 'SECONDARY
)
1626 (setq org-store-link-plist
(plist-put org-store-link-plist
:annotation v-a
))
1627 (setq org-store-link-plist
(plist-put org-store-link-plist
:initial v-i
))
1630 (message "no template") (ding)
1632 (save-window-excursion
1633 (org-switch-to-buffer-other-window (get-buffer-create "*Capture*"))
1635 (setq buffer-file-name nil
)
1636 (setq mark-active nil
)
1638 (goto-char (point-min))
1639 ;; %[] insert contents of a file.
1641 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t
)
1642 (let ((filename (expand-file-name (match-string 1)))
1643 (beg (copy-marker (match-beginning 0)))
1644 (end (copy-marker (match-end 0))))
1645 (unless (org-capture-escaped-%
)
1646 (delete-region beg end
)
1647 (set-marker beg nil
)
1648 (set-marker end nil
)
1649 (condition-case error
1650 (insert-file-contents filename
)
1652 (insert (format "%%![couldn not insert %s: %s]"
1655 ;; Mark %() embedded elisp for later evaluation.
1656 (org-capture-expand-embedded-elisp 'mark
)
1657 ;; Expand non-interactive templates.
1658 (let ((regexp "%\\(:[-a-za-z]+\\|<\\([^>\n]+\\)>\\|[aAcfFikKlntTuUx]\\)"))
1660 (while (re-search-forward regexp nil t
)
1661 ;; `org-capture-escaped-%' may modify buffer and cripple
1662 ;; match-data. Use markers instead. Ditto for other
1664 (let ((pos (copy-marker (match-beginning 0)))
1665 (end (copy-marker (match-end 0)))
1666 (value (match-string 1))
1667 (time-string (match-string 2)))
1668 (unless (org-capture-escaped-%
)
1669 (delete-region pos end
)
1670 (set-marker pos nil
)
1671 (set-marker end nil
)
1672 (let* ((inside-sexp?
(org-capture-inside-embedded-elisp-p))
1674 (pcase (string-to-char value
)
1675 (?
< (format-time-string time-string time
))
1677 (or (plist-get org-store-link-plist
(intern value
))
1680 (if inside-sexp? v-i
1681 ;; Outside embedded Lisp, repeat leading
1682 ;; characters before initial place holder
1684 (let ((lead (concat "\n"
1685 (org-current-line-string t
))))
1686 (replace-regexp-in-string "\n" lead v-i nil t
))))
1703 ;; Escape sensitive characters.
1704 (replace-regexp-in-string "[\\\"]" "\\\\\\&" replacement
)
1706 ;; Expand %() embedded Elisp. Limit to Sexp originally marked.
1707 (org-capture-expand-embedded-elisp)
1708 ;; Expand interactive templates. This is the last step so that
1709 ;; template is mostly expanded when prompting happens. Turn on
1710 ;; Org mode and set local variables. This is to support
1711 ;; completion in interactive prompts.
1712 (let ((org-inhibit-startup t
)) (org-mode))
1713 (org-clone-local-variables buffer
"\\`org-")
1714 (let (strings) ; Stores interactive answers.
1716 (let ((regexp "%\\^\\(?:{\\([^}]*\\)}\\)?\\([CgGLptTuU]\\)?"))
1717 (while (re-search-forward regexp nil t
)
1718 (let* ((items (and (match-end 1)
1720 (split-string (match-string-no-properties 1)
1722 (key (match-string 2))
1723 (beg (copy-marker (match-beginning 0)))
1724 (end (copy-marker (match-end 0)))
1725 (prompt (nth 0 items
))
1726 (default (nth 1 items
))
1727 (completions (nthcdr 2 items
)))
1728 (unless (org-capture-escaped-%
)
1729 (delete-region beg end
)
1730 (set-marker beg nil
)
1731 (set-marker end nil
)
1734 (let* ((org-last-tags-completion-table
1735 (org-global-tags-completion-table
1736 (cond ((equal key
"G") (org-agenda-files))
1739 (org-add-colon-after-tag-completion t
)
1744 (if prompt
(concat prompt
": ") "Tags: ")
1745 'org-tags-completion-function nil nil nil
1747 "[^[:alnum:]_@#%]+")
1749 (when (org-string-nw-p ins
)
1750 (unless (eq (char-before) ?
:) (insert ":"))
1752 (unless (eq (char-after) ?
:) (insert ":"))
1753 (when (org-at-heading-p) (org-align-tags)))))
1755 (let ((insert-fun (if (equal key
"C") #'insert
1756 (lambda (s) (org-insert-link 0 s
)))))
1757 (pcase org-capture--clipboards
1759 (`(,value
) (funcall insert-fun value
))
1760 (`(,first-value .
,_
)
1762 (read-string "Clipboard/kill value: "
1764 'org-capture--clipboards
1766 (_ (error "Invalid `org-capture--clipboards' value: %S"
1767 org-capture--clipboards
)))))
1769 ;; We remove file properties inherited from
1770 ;; target buffer so `org-read-property-value' has
1771 ;; a chance to find allowed values in sub-trees
1772 ;; from the target buffer.
1773 (setq-local org-file-properties nil
)
1774 (let* ((origin (set-marker (make-marker)
1775 (org-capture-get :pos
)
1776 (org-capture-get :buffer
)))
1777 ;; Find location from where to get allowed
1778 ;; values. If `:target-entry-p' is
1779 ;; non-nil, the current headline in the
1780 ;; target buffer is going to be a parent
1781 ;; headline, so location is fine.
1782 ;; Otherwise, find the parent headline in
1783 ;; the target buffer.
1784 (pom (if (org-capture-get :target-entry-p
) origin
1786 (while (org-up-heading-safe))
1787 (org-current-level))))
1788 (org-with-point-at origin
1789 (let ((l (if (org-at-heading-p)
1791 most-positive-fixnum
)))
1792 (while (and l
(>= l level
))
1793 (setq l
(org-up-heading-safe)))
1794 (if l
(point-marker)
1795 (point-min-marker)))))))
1796 (value (org-read-property-value prompt pom
)))
1797 (org-set-property prompt value
)))
1798 ((or "t" "T" "u" "U")
1799 ;; These are the date/time related ones.
1800 (let* ((upcase?
(equal (upcase key
) key
))
1801 (org-end-time-was-given nil
)
1802 (time (org-read-date upcase? t nil prompt
)))
1803 (org-insert-time-stamp
1804 time
(or org-time-was-given upcase?
)
1805 (member key
'("u" "U"))
1806 nil nil
(list org-end-time-was-given
))))
1808 ;; Load history list for current prompt.
1809 (setq org-capture--prompt-history
1810 (gethash prompt org-capture--prompt-history-table
))
1811 (push (org-completing-read
1812 (concat (or prompt
"Enter string")
1813 (and default
(format " [%s]" default
))
1816 nil nil nil
'org-capture--prompt-history default
)
1818 (insert (car strings
))
1819 ;; Save updated history list for current prompt.
1820 (puthash prompt org-capture--prompt-history
1821 org-capture--prompt-history-table
))
1823 (error "Unknown template placeholder: \"%%^%s\""
1825 ;; Replace %n escapes with nth %^{...} string.
1826 (setq strings
(nreverse strings
))
1828 (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t
)
1829 (unless (org-capture-escaped-%
)
1831 (nth (1- (string-to-number (match-string 1))) strings
)
1833 ;; Make sure there are no empty lines before the text, and that
1834 ;; it ends with a newline character or it is empty.
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 (if (bobp) (delete-region (point) (line-end-position))
1841 (delete-region (point) (point-max))
1843 ;; Return the expanded template and kill the capture buffer.
1844 (untabify (point-min) (point-max))
1845 (set-buffer-modified-p nil
)
1846 (prog1 (buffer-substring-no-properties (point-min) (point-max))
1847 (kill-buffer (current-buffer))))))
1849 (defun org-capture-escaped-%
()
1850 "Non-nil if % was escaped.
1851 If yes, unescape it now. Assume match-data contains the
1852 placeholder to check."
1854 (goto-char (match-beginning 0))
1855 (let ((n (abs (skip-chars-backward "\\\\"))))
1856 (delete-char (/ (1+ n
) 2))
1859 (defun org-capture-expand-embedded-elisp (&optional mark
)
1860 "Evaluate embedded elisp %(sexp) and replace with the result.
1861 When optional MARK argument is non-nil, mark Sexp with a text
1862 property (`org-embedded-elisp') for later evaluation. Only
1863 marked Sexp are evaluated when this argument is nil."
1865 (goto-char (point-min))
1866 (while (re-search-forward "%(" nil t
)
1868 ((get-text-property (match-beginning 0) 'org-embedded-elisp
)
1869 (goto-char (match-beginning 0))
1870 (let ((template-start (point)))
1872 (let* ((sexp (read (current-buffer)))
1874 (org-capture--expand-keyword-in-embedded-elisp
1876 (delete-region template-start
(point))
1879 ((stringp result
) (insert result
))
1881 "Capture template sexp `%s' must evaluate to string or nil"
1884 ;; Only mark valid and non-escaped sexp.
1885 ((org-capture-escaped-%
) nil
)
1887 (let ((end (with-syntax-table emacs-lisp-mode-syntax-table
1888 (ignore-errors (scan-sexps (1- (point)) 1)))))
1890 (put-text-property (- (point) 2) end
'org-embedded-elisp t
))))))))
1892 (defun org-capture--expand-keyword-in-embedded-elisp (attr)
1893 "Recursively replace capture link keywords in ATTR sexp.
1894 Such keywords are prefixed with \"%:\". See
1895 `org-capture-template' for more information."
1897 (mapcar 'org-capture--expand-keyword-in-embedded-elisp attr
))
1899 (let* ((attr-symbol (symbol-name attr
))
1900 (key (and (string-match "%\\(:.*\\)" attr-symbol
)
1901 (intern (match-string 1 attr-symbol
)))))
1902 (or (plist-get org-store-link-plist key
)
1906 (defun org-capture-inside-embedded-elisp-p ()
1907 "Non-nil if point is inside of embedded elisp %(sexp).
1908 Assume sexps have been marked with
1909 `org-capture-expand-embedded-elisp' beforehand."
1910 (get-text-property (point) 'org-embedded-elisp
))
1913 (defun org-capture-import-remember-templates ()
1914 "Set `org-capture-templates' to be similar to `org-remember-templates'."
1916 (when (and (yes-or-no-p
1917 "Import old remember templates into org-capture-templates? ")
1919 "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
1920 (require 'org-remember
)
1921 (setq org-capture-templates
1924 (let ((desc (car entry
))
1925 (key (char-to-string (nth 1 entry
)))
1926 (template (nth 2 entry
))
1927 (file (or (nth 3 entry
) org-default-notes-file
))
1928 (position (or (nth 4 entry
) org-remember-default-headline
))
1930 (prepend org-reverse-note-order
)
1931 immediate target jump-to-captured
)
1933 ((member position
'(top bottom
))
1934 (setq target
(list 'file file
)
1935 prepend
(eq position
'top
)))
1936 ((eq position
'date-tree
)
1937 (setq target
(list 'file
+datetree file
)
1939 (t (setq target
(list 'file
+headline file position
))))
1941 (when (string-match "%!" template
)
1942 (setq template
(replace-match "" t t template
)
1945 (when (string-match "%&" template
)
1946 (setq jump-to-captured t
))
1948 (append (list key desc type target template
)
1949 (and prepend
'(:prepend t
))
1950 (and immediate
'(:immediate-finish t
))
1951 (and jump-to-captured
'(:jump-to-captured t
)))))
1953 org-remember-templates
))))
1956 (provide 'org-capture
)
1958 ;;; org-capture.el ends here