1 ;;; org-capture.el --- Fast note taking in Org -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2010-2018 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-clock-update-mode-line
"org-clock" (&optional refresh
))
55 (declare-function org-datetree-find-date-create
"org-datetree" (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-fix-formulas
"org-table" (key replace
&optional limit delta remove
))
61 (declare-function org-table-goto-line
"org-table" (N))
63 (defvar dired-buffers
)
64 (defvar org-end-time-was-given
)
65 (defvar org-remember-default-headline
)
66 (defvar org-remember-templates
)
67 (defvar org-table-border-regexp
)
68 (defvar org-table-current-begin-pos
)
69 (defvar org-table-fix-formulas-confirm
)
70 (defvar org-table-hlines
)
72 (defvar org-capture-clock-was-started nil
73 "Internal flag, noting if the clock was started.")
75 (defvar org-capture-last-stored-marker
(make-marker)
76 "Marker pointing to the entry most recently stored with `org-capture'.")
78 ;; The following variable is scoped dynamically by org-protocol
79 ;; to indicate that the link properties have already been stored
80 (defvar org-capture-link-is-already-stored nil
)
82 (defvar org-capture-is-refiling nil
83 "Non-nil when capture process is refiling an entry.")
85 (defvar org-capture--prompt-history-table
(make-hash-table :test
#'equal
)
86 "Hash table for all history lists per prompt.")
88 (defvar org-capture--prompt-history nil
89 "History list for prompt placeholders.")
91 (defgroup org-capture nil
92 "Options concerning capturing new entries."
96 (defun org-capture-upgrade-templates (templates)
97 "Update the template list to the new format.
98 TEMPLATES is a template list, as in `org-capture-templates'. The
99 new format unifies all the date/week tree targets into one that
100 also allows for an optional outline path to specify a target."
101 (let ((modified-templates
105 ;; Match templates with an obsolete "tree" target type. Replace
106 ;; it with common `file+olp-datetree'. Add new properties
107 ;; (i.e., `:time-prompt' and `:tree-type') if needed.
108 (`(,key
,desc
,type
(file+datetree .
,path
) ,tpl .
,props
)
109 `(,key
,desc
,type
(file+olp
+datetree
,@path
) ,tpl
,@props
))
110 (`(,key
,desc
,type
(file+datetree
+prompt .
,path
) ,tpl .
,props
)
111 `(,key
,desc
,type
(file+olp
+datetree
,@path
) ,tpl
112 :time-prompt t
,@props
))
113 (`(,key
,desc
,type
(file+weektree .
,path
) ,tpl .
,props
)
114 `(,key
,desc
,type
(file+olp
+datetree
,@path
) ,tpl
115 :tree-type week
,@props
))
116 (`(,key
,desc
,type
(file+weektree
+prompt .
,path
) ,tpl .
,props
)
117 `(,key
,desc
,type
(file+olp
+datetree
,@path
) ,tpl
118 :tree-type week
:time-prompt t
,@props
))
119 ;; Other templates are left unchanged.
122 (unless (equal modified-templates templates
)
123 (message "Deprecated date/weektree capture templates changed to `file+olp+datetree'."))
126 (defcustom org-capture-templates nil
127 "Templates for the creation of new entries.
129 Each entry is a list with the following items:
131 keys The keys that will select the template, as a string, characters
132 only, for example \"a\" for a template to be selected with a
133 single key, or \"bt\" for selection with two keys. When using
134 several keys, keys using the same prefix key must be together
135 in the list and preceded by a 2-element entry explaining the
136 prefix key, for example
138 (\"b\" \"Templates for marking stuff to buy\")
140 The \"C\" key is used by default for quick access to the
141 customization of the template variable. But if you want to use
142 that key for a template, you can.
144 description A short string describing the template, will be shown during
147 type The type of entry. Valid types are:
148 entry an Org node, with a headline. Will be filed
149 as the child of the target entry or as a
151 item a plain list item, will be placed in the
152 first plain list at the target
154 checkitem a checkbox item. This differs from the
155 plain list item only is so far as it uses a
156 different default template.
157 table-line a new line in the first table at target location.
158 plain text to be inserted as it is.
160 target Specification of where the captured item should be placed.
161 In Org files, targets usually define a node. Entries will
162 become children of this node, other types will be added to the
163 table or list in the body of this node.
165 Most target specifications contain a file name. If that file
166 name is the empty string, it defaults to `org-default-notes-file'.
167 A file can also be given as a variable or as a function called
168 with no argument. When an absolute path is not specified for a
169 target, it is taken as relative to `org-directory'.
173 (file \"path/to/file\")
174 Text will be placed at the beginning or end of that file
176 (id \"id of existing Org entry\")
177 File as child of this entry, or in the body of the entry
179 (file+headline \"path/to/file\" \"node headline\")
180 Fast configuration if the target heading is unique in the file
182 (file+olp \"path/to/file\" \"Level 1 heading\" \"Level 2\" ...)
183 For non-unique headings, the full outline path is safer
185 (file+regexp \"path/to/file\" \"regexp to find location\")
186 File to the entry matching regexp
188 (file+olp+datetree \"path/to/file\" \"Level 1 heading\" ...)
189 Will create a heading in a date tree for today's date.
190 If no heading is given, the tree will be on top level.
191 To prompt for date instead of using TODAY, use the
192 :time-prompt property. To create a week-tree, use the
195 (file+function \"path/to/file\" function-finding-location)
196 A function to find the right location in the file
199 File to the entry that is currently being clocked
201 (function function-finding-location)
202 Most general way: write your own function which both visits
203 the file and moves point to the right location
205 template The template for creating the capture item. If you leave this
206 empty, an appropriate default template will be used. See below
207 for more details. Instead of a string, this may also be one of
209 (file \"/path/to/template-file\")
210 (function function-returning-the-template)
212 in order to get a template from a file, or dynamically
215 The rest of the entry is a property list of additional options. Recognized
218 :prepend Normally newly captured information will be appended at
219 the target location (last child, last table line,
220 last list item...). Setting this property will
223 :immediate-finish When set, do not offer to edit the information, just
224 file it away immediately. This makes sense if the
225 template only needs information that can be added
228 :jump-to-captured When set, jump to the captured entry when finished.
230 :empty-lines Set this to the number of lines the should be inserted
231 before and after the new item. Default 0, only common
234 :empty-lines-before Set this to the number of lines the should be inserted
235 before the new item. Overrides :empty-lines for the
236 number lines inserted before.
238 :empty-lines-after Set this to the number of lines the should be inserted
239 after the new item. Overrides :empty-lines for the
240 number of lines inserted after.
242 :clock-in Start the clock in this item.
244 :clock-keep Keep the clock running when filing the captured entry.
246 :clock-resume Start the interrupted clock when finishing the capture.
247 Note that :clock-keep has precedence over :clock-resume.
248 When setting both to t, the current clock will run and
249 the previous one will not be resumed.
251 :time-prompt Prompt for a date/time to be used for date/week trees
252 and when filling the template.
254 :tree-type When `week', make a week tree instead of the month tree.
256 :unnarrowed Do not narrow the target buffer, simply show the
257 full buffer. Default is to narrow it so that you
258 only see the new stuff.
260 :table-line-pos Specification of the location in the table where the
261 new line should be inserted. It should be a string like
262 \"II-3\", meaning that the new line should become the
263 third line before the second horizontal separator line.
265 :kill-buffer If the target file was not yet visited by a buffer when
266 capture was invoked, kill the buffer again after capture
269 The template defines the text to be inserted. Often this is an
270 Org mode entry (so the first line should start with a star) that
271 will be filed as a child of the target headline. It can also be
272 freely formatted text. Furthermore, the following %-escapes will
273 be replaced with content and expanded:
275 %[pathname] Insert the contents of the file given by
276 `pathname'. These placeholders are expanded at the very
277 beginning of the process so they can be used to extend the
279 %(sexp) Evaluate elisp `(sexp)' and replace it with the results.
280 Only placeholders pre-existing within the template, or
281 introduced with %[pathname] are expanded this way. Since this
282 happens after expanding non-interactive %-escapes, those can
283 be used to fill the expression.
284 %<...> The result of format-time-string on the ... format specification.
285 %t Time stamp, date only. The time stamp is the current time,
286 except when called from agendas with `\\[org-agenda-capture]' or
287 with `org-capture-use-agenda-date' set.
288 %T Time stamp as above, with date and time.
289 %u, %U Like the above, but inactive time stamps.
290 %i Initial content, copied from the active region. If %i is
291 indented, the entire inserted text will be indented as well.
292 %a Annotation, normally the link created with `org-store-link'.
293 %A Like %a, but prompt for the description part.
294 %l Like %a, but only insert the literal link.
295 %c Current kill ring head.
296 %x Content of the X clipboard.
297 %k Title of currently clocked task.
298 %K Link to currently clocked task.
299 %n User name (taken from the variable `user-full-name').
300 %f File visited by current buffer when org-capture was called.
301 %F Full path of the file or directory visited by current buffer.
302 %:keyword Specific information for certain link types, see below.
303 %^g Prompt for tags, with completion on tags in target file.
304 %^G Prompt for tags, with completion on all tags in all agenda files.
305 %^t Like %t, but prompt for date. Similarly %^T, %^u, %^U.
306 You may define a prompt like: %^{Please specify birthday}t.
307 The default date is that of %t, see above.
308 %^C Interactive selection of which kill or clip to use.
309 %^L Like %^C, but insert as link.
310 %^{prop}p Prompt the user for a value for property `prop'.
311 %^{prompt} Prompt the user for a string and replace this sequence with it.
312 A default value and a completion table ca be specified like this:
313 %^{prompt|default|completion2|completion3|...}.
314 %? After completing the template, position cursor here.
315 %\\1 ... %\\N Insert the text entered at the nth %^{prompt}, where N
316 is a number, starting from 1.
318 Apart from these general escapes, you can access information specific to
319 the link type that is created. For example, calling `org-capture' in emails
320 or in Gnus will record the author and the subject of the message, which you
321 can access with \"%:from\" and \"%:subject\", respectively. Here is a
322 complete list of what is recorded for each link type.
324 Link type | Available information
325 ------------------------+------------------------------------------------------
326 bbdb | %:type %:name %:company
327 vm, wl, mh, mew, rmail, | %:type %:subject %:message-id
328 gnus | %:from %:fromname %:fromaddress
329 | %:to %:toname %:toaddress
330 | %:fromto (either \"to NAME\" or \"from NAME\")
331 | %:date %:date-timestamp (as active timestamp)
332 | %:date-timestamp-inactive (as inactive timestamp)
333 gnus | %:group, for messages also all email fields
334 eww, w3, w3m | %:type %:url
335 info | %:type %:file %:node
336 calendar | %:type %:date
338 When you need to insert a literal percent sign in the template,
339 you can escape ambiguous cases with a backward slash, e.g., \\%i."
342 :set
(lambda (s v
) (set s
(org-capture-upgrade-templates v
)))
344 (let ((file-variants '(choice :tag
"Filename "
345 (file :tag
"Literal")
346 (function :tag
"Function")
347 (variable :tag
"Variable")
348 (sexp :tag
"Form"))))
350 (choice :value
("" "" entry
(file "~/org/notes.org") "")
351 (list :tag
"Multikey description"
352 (string :tag
"Keys ")
353 (string :tag
"Description"))
354 (list :tag
"Template entry"
355 (string :tag
"Keys ")
356 (string :tag
"Description ")
357 (choice :tag
"Capture Type " :value entry
358 (const :tag
"Org entry" entry
)
359 (const :tag
"Plain list item" item
)
360 (const :tag
"Checkbox item" checkitem
)
361 (const :tag
"Plain text" plain
)
362 (const :tag
"Table line" table-line
))
363 (choice :tag
"Target location"
365 (const :format
"" file
)
368 (const :format
"" id
)
370 (list :tag
"File & Headline"
371 (const :format
"" file
+headline
)
373 (string :tag
" Headline"))
374 (list :tag
"File & Outline path"
375 (const :format
"" file
+olp
)
377 (repeat :tag
"Outline path" :inline t
378 (string :tag
"Headline")))
379 (list :tag
"File & Regexp"
380 (const :format
"" file
+regexp
)
382 (regexp :tag
" Regexp"))
383 (list :tag
"File [ & Outline path ] & Date tree"
384 (const :format
"" file
+olp
+datetree
)
386 (option (repeat :tag
"Outline path" :inline t
387 (string :tag
"Headline"))))
388 (list :tag
"File & function"
389 (const :format
"" file
+function
)
391 (sexp :tag
" Function"))
392 (list :tag
"Current clocking task"
393 (const :format
"" clock
))
394 (list :tag
"Function"
395 (const :format
"" function
)
396 (sexp :tag
" Function")))
397 (choice :tag
"Template "
400 (const :format
"" file
)
401 (file :tag
"Template file"))
402 (list :tag
"Function"
403 (const :format
"" function
)
404 (function :tag
"Template function")))
406 ;; Give the most common options as checkboxes
407 :options
(((const :format
"%v " :prepend
) (const t
))
408 ((const :format
"%v " :immediate-finish
) (const t
))
409 ((const :format
"%v " :jump-to-captured
) (const t
))
410 ((const :format
"%v " :empty-lines
) (const 1))
411 ((const :format
"%v " :empty-lines-before
) (const 1))
412 ((const :format
"%v " :empty-lines-after
) (const 1))
413 ((const :format
"%v " :clock-in
) (const t
))
414 ((const :format
"%v " :clock-keep
) (const t
))
415 ((const :format
"%v " :clock-resume
) (const t
))
416 ((const :format
"%v " :time-prompt
) (const t
))
417 ((const :format
"%v " :tree-type
) (const week
))
418 ((const :format
"%v " :unnarrowed
) (const t
))
419 ((const :format
"%v " :table-line-pos
) (string))
420 ((const :format
"%v " :kill-buffer
) (const t
)))))))))
422 (defcustom org-capture-before-finalize-hook nil
423 "Hook that is run right before a capture process is finalized.
424 The capture buffer is still current when this hook runs and it is
425 widened to the entire buffer."
430 (defcustom org-capture-after-finalize-hook nil
431 "Hook that is run right after a capture process is finalized.
432 Suitable for window cleanup."
437 (defcustom org-capture-prepare-finalize-hook nil
438 "Hook that is run before the finalization starts.
439 The capture buffer is current and still narrowed."
444 (defcustom org-capture-bookmark t
445 "When non-nil, add a bookmark pointing at the last stored
446 position when capturing."
451 ;;; The property list for keeping information about the capture process
453 (defvar org-capture-plist nil
454 "Plist for the current capture process, global, to avoid having to pass it.")
456 (defvar org-capture-current-plist nil
457 "Local variable holding the plist in a capture buffer.
458 This is used to store the plist for use when finishing a capture process
459 because another such process might have changed the global variable by then.
461 Each time a new capture buffer has been set up, the global `org-capture-plist'
462 is copied to this variable, which is local in the indirect buffer.")
464 (defvar org-capture-clock-keep nil
465 "Local variable to store the value of the :clock-keep parameter.
466 This is needed in case org-capture-finalize is called interactively.")
468 (defun org-capture-put (&rest stuff
)
469 "Add properties to the capture property list `org-capture-plist'."
471 (setq org-capture-plist
(plist-put org-capture-plist
472 (pop stuff
) (pop stuff
)))))
473 (defun org-capture-get (prop &optional local
)
474 "Get properties from the capture property list `org-capture-plist'.
475 When LOCAL is set, use the local variable `org-capture-current-plist',
476 this is necessary after initialization of the capture process,
477 to avoid conflicts with other active capture processes."
478 (plist-get (if local org-capture-current-plist org-capture-plist
) prop
))
482 (defvar org-capture-mode-map
483 (let ((map (make-sparse-keymap)))
484 (define-key map
"\C-c\C-c" #'org-capture-finalize
)
485 (define-key map
"\C-c\C-k" #'org-capture-kill
)
486 (define-key map
"\C-c\C-w" #'org-capture-refile
)
488 "Keymap for `org-capture-mode', a minor mode.
489 Use this map to set additional keybindings for when Org mode is used
490 for a capture buffer.")
492 (defvar org-capture-mode-hook nil
493 "Hook for the `org-capture-mode' minor mode.")
495 (define-minor-mode org-capture-mode
496 "Minor mode for special key bindings in a capture buffer.
498 Turning on this mode runs the normal hook `org-capture-mode-hook'."
499 nil
" Cap" org-capture-mode-map
502 (substitute-command-keys
503 "\\<org-capture-mode-map>Capture buffer. Finish \
504 `\\[org-capture-finalize]', refile `\\[org-capture-refile]', \
505 abort `\\[org-capture-kill]'.")))
507 ;;; The main commands
509 (defvar org-capture-initial nil
)
510 (defvar org-capture-entry nil
)
513 (defun org-capture-string (string &optional keys
)
514 "Capture STRING with the template selected by KEYS."
515 (interactive "sInitial text: \n")
516 (let ((org-capture-initial string
)
517 (org-capture-entry (org-capture-select-template keys
)))
520 (defcustom org-capture-templates-contexts nil
521 "Alist of capture templates and valid contexts.
523 For example, if you have a capture template \"c\" and you want
524 this template to be accessible only from `message-mode' buffers,
527 \\='((\"c\" ((in-mode . \"message-mode\"))))
529 Here are the available contexts definitions:
531 in-file: command displayed only in matching files
532 in-mode: command displayed only in matching modes
533 not-in-file: command not displayed in matching files
534 not-in-mode: command not displayed in matching modes
535 in-buffer: command displayed only in matching buffers
536 not-in-buffer: command not displayed in matching buffers
537 [function]: a custom function taking no argument
539 If you define several checks, the agenda command will be
540 accessible if there is at least one valid check.
542 You can also bind a key to another capture template depending on
545 \\='((\"c\" \"d\" ((in-mode . \"message-mode\"))))
547 Here it means: in `message-mode buffers', use \"c\" as the
548 key for the capture template otherwise associated with \"d\".
549 \(The template originally associated with \"d\" is not displayed
550 to avoid duplicates.)"
553 :type
'(repeat (list :tag
"Rule"
554 (string :tag
" Capture key")
555 (string :tag
"Replace by template")
556 (repeat :tag
"Available when"
558 (cons :tag
"Condition"
560 (const :tag
"In file" in-file
)
561 (const :tag
"Not in file" not-in-file
)
562 (const :tag
"In buffer" in-buffer
)
563 (const :tag
"Not in buffer" not-in-buffer
)
564 (const :tag
"In mode" in-mode
)
565 (const :tag
"Not in mode" not-in-mode
))
567 (function :tag
"Custom function"))))))
569 (defcustom org-capture-use-agenda-date nil
570 "Non-nil means use the date at point when capturing from agendas.
571 When nil, you can still capture using the date at point with
572 `\\[org-agenda-capture]'."
578 (defun org-capture (&optional goto keys
)
580 \\<org-capture-mode-map>
581 This will let you select a template from `org-capture-templates', and
582 then file the newly captured information. The text is immediately
583 inserted at the target location, and an indirect buffer is shown where
584 you can edit it. Pressing `\\[org-capture-finalize]' brings you back to the \
586 state of Emacs, so that you can continue your work.
588 When called interactively with a `\\[universal-argument]' prefix argument \
590 capture anything, just go to the file/headline where the selected
591 template stores its notes.
593 With a `\\[universal-argument] \\[universal-argument]' prefix argument, go to \
594 the last note stored.
596 When called with a `C-0' (zero) prefix, insert a template at point.
598 When called with a `C-1' (one) prefix, force prompting for a date when
599 a datetree entry is made.
601 ELisp programs can set KEYS to a string associated with a template
602 in `org-capture-templates'. In this case, interactive selection
605 If `org-capture-use-agenda-date' is non-nil, capturing from the
606 agenda will use the date at point as the default date. Then, a
607 `C-1' prefix will tell the capture process to use the HH:MM time
608 of the day at point (if any) or the current HH:MM time."
610 (when (and org-capture-use-agenda-date
611 (eq major-mode
'org-agenda-mode
))
612 (setq org-overriding-default-time
613 (org-get-cursor-date (equal goto
1))))
615 ((equal goto
'(4)) (org-capture-goto-target))
616 ((equal goto
'(16)) (org-capture-goto-last-stored))
618 (let* ((orig-buf (current-buffer))
619 (annotation (if (and (boundp 'org-capture-link-is-already-stored
)
620 org-capture-link-is-already-stored
)
621 (plist-get org-store-link-plist
:annotation
)
622 (ignore-errors (org-store-link nil
))))
623 (entry (or org-capture-entry
(org-capture-select-template keys
)))
625 (setq initial
(or org-capture-initial
626 (and (org-region-active-p)
627 (buffer-substring (point) (mark)))))
628 (when (stringp initial
)
629 (remove-text-properties 0 (length initial
) '(read-only t
) initial
))
630 (when (stringp annotation
)
631 (remove-text-properties 0 (length annotation
)
632 '(read-only t
) annotation
))
635 (customize-variable 'org-capture-templates
))
637 (user-error "Abort"))
639 (org-capture-set-plist entry
)
640 (org-capture-get-template)
641 (org-capture-put :original-buffer orig-buf
642 :original-file
(or (buffer-file-name orig-buf
)
643 (and (featurep 'dired
)
646 :original-file-nondirectory
647 (and (buffer-file-name orig-buf
)
648 (file-name-nondirectory
649 (buffer-file-name orig-buf
)))
650 :annotation annotation
652 :return-to-wconf
(current-window-configuration)
654 (or org-overriding-default-time
656 (org-capture-set-target-location)
657 (condition-case error
658 (org-capture-put :template
(org-capture-fill-template))
660 (if (get-buffer "*Capture*") (kill-buffer "*Capture*"))
661 (error "Capture abort: %s" error
)))
663 (setq org-capture-clock-keep
(org-capture-get :clock-keep
))
666 (org-capture-insert-template-here)
667 (condition-case error
668 (org-capture-place-template
669 (eq (car (org-capture-get :target
)) 'function
))
671 (if (and (buffer-base-buffer (current-buffer))
672 (string-prefix-p "CAPTURE-" (buffer-name)))
673 (kill-buffer (current-buffer)))
674 (set-window-configuration (org-capture-get :return-to-wconf
))
675 (error "Capture template `%s': %s"
676 (org-capture-get :key
)
678 (if (and (derived-mode-p 'org-mode
)
679 (org-capture-get :clock-in
))
682 (if (org-clock-is-active)
683 (org-capture-put :interrupted-clock
684 (copy-marker org-clock-marker
)))
686 (setq-local org-capture-clock-was-started t
))
688 "Could not start the clock in this capture buffer")))
689 (if (org-capture-get :immediate-finish
)
690 (org-capture-finalize)))))))))
692 (defun org-capture-get-template ()
693 "Get the template from a file or a function if necessary."
694 (let ((txt (org-capture-get :template
)) file
)
696 ((and (listp txt
) (eq (car txt
) 'file
))
698 (setq file
(expand-file-name (nth 1 txt
) org-directory
)))
699 (setq txt
(org-file-contents file
))
700 (setq txt
(format "* Template file %s not found" (nth 1 txt
)))))
701 ((and (listp txt
) (eq (car txt
) 'function
))
702 (if (fboundp (nth 1 txt
))
703 (setq txt
(funcall (nth 1 txt
)))
704 (setq txt
(format "* Template function %s not found" (nth 1 txt
)))))
705 ((not txt
) (setq txt
""))
707 (t (setq txt
"* Invalid capture template")))
708 (org-capture-put :template txt
)))
710 (defun org-capture-finalize (&optional stay-with-capture
)
711 "Finalize the capture process.
712 With prefix argument STAY-WITH-CAPTURE, jump to the location of the
713 captured item after finalizing."
715 (when (org-capture-get :jump-to-captured
)
716 (setq stay-with-capture t
))
717 (unless (and org-capture-mode
718 (buffer-base-buffer (current-buffer)))
719 (error "This does not seem to be a capture buffer for Org mode"))
721 (run-hooks 'org-capture-prepare-finalize-hook
)
723 ;; Did we start the clock in this capture buffer?
724 (when (and org-capture-clock-was-started
726 (eq (marker-buffer org-clock-marker
) (buffer-base-buffer))
727 (>= org-clock-marker
(point-min))
728 (< org-clock-marker
(point-max)))
729 ;; Looks like the clock we started is still running.
730 (if org-capture-clock-keep
731 ;; User may have completed clocked heading from the template.
732 ;; Refresh clock mode line.
733 (org-clock-update-mode-line t
)
734 ;; Clock out. Possibly resume interrupted clock.
735 (let (org-log-note-clock-out) (org-clock-out))
736 (when (and (org-capture-get :clock-resume
'local
)
737 (markerp (org-capture-get :interrupted-clock
'local
))
738 (buffer-live-p (marker-buffer
739 (org-capture-get :interrupted-clock
'local
))))
740 (let ((clock-in-task (org-capture-get :interrupted-clock
'local
)))
741 (org-with-point-at clock-in-task
(org-clock-in)))
742 (message "Interrupted clock has been resumed"))))
744 (let ((abort-note nil
))
745 ;; Store the size of the capture buffer
746 (org-capture-put :captured-entry-size
(- (point-max) (point-min)))
748 ;; Store the insertion point in the target buffer
749 (org-capture-put :insertion-point
(point))
752 (let ((beg (org-capture-get :begin-marker
'local
))
753 (end (org-capture-get :end-marker
'local
)))
754 (if (not (and beg end
)) (setq abort-note
'dirty
)
756 (org-with-wide-buffer (kill-region beg end
))))
758 ;; Postprocessing: Update Statistics cookies, do the sorting
759 (when (derived-mode-p 'org-mode
)
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
)
768 (if (not (org-table-get-stored-formulas)) (org-table-align)
769 ;; Adjust formulas, if necessary. We assume a non-nil
770 ;; `:immediate-finish' means that no confirmation is
771 ;; required. Else, obey `org-table-fix-formulas-confirm'.
773 ;; The delta required to fix formulas depends on the
774 ;; number of rows inserted by the template.
775 (when (or (org-capture-get :immediate-finish
)
776 (not org-table-fix-formulas-confirm
)
777 (funcall org-table-fix-formulas-confirm
"Fix formulas? "))
778 (org-table-fix-formulas
779 "@" nil
(1- (org-table-current-dline))
780 (count-lines (org-capture-get :begin-marker
'local
)
781 (org-capture-get :end-marker
'local
))))
782 (org-table-recalculate 'all
)))) ;FIXME: should we iterate?
783 ;; Store this place as the last one where we stored something
784 ;; Do the marking in the base buffer, so that it makes sense after
785 ;; the indirect buffer has been killed.
786 (org-capture-store-last-position)
789 (run-hooks 'org-capture-before-finalize-hook
))
791 (when (org-capture-get :decrypted
)
793 (goto-char (org-capture-get :decrypted
))
794 (org-encrypt-entry)))
796 ;; Kill the indirect buffer
797 (let ((return-wconf (org-capture-get :return-to-wconf
'local
))
798 (new-buffer (org-capture-get :new-buffer
'local
))
799 (kill-buffer (org-capture-get :kill-buffer
'local
))
800 (base-buffer (buffer-base-buffer (current-buffer))))
802 ;; Kill the indirect buffer
803 (kill-buffer (current-buffer))
805 ;; Narrow back the target buffer to its previous state
806 (with-current-buffer (org-capture-get :buffer
)
807 (let ((reg (org-capture-get :initial-target-region
))
808 (pos (org-capture-get :initial-target-position
))
809 (ipt (org-capture-get :insertion-point
))
810 (size (org-capture-get :captured-entry-size
)))
813 (cond ((< ipt
(car reg
))
814 ;; insertion point is before the narrowed region
815 (narrow-to-region (+ size
(car reg
)) (+ size
(cdr reg
))))
817 ;; insertion point is after the narrowed region
818 (narrow-to-region (car reg
) (cdr reg
)))
820 ;; insertion point is within the narrowed region
821 (narrow-to-region (car reg
) (+ size
(cdr reg
)))))
822 ;; now place back the point at its original position
823 (if (< ipt
(car reg
))
824 (goto-char (+ size pos
))
825 (goto-char (if (< ipt pos
) (+ size pos
) pos
))))))
827 ;; Kill the target buffer if that is desired
828 (when (and base-buffer new-buffer kill-buffer
)
829 (with-current-buffer base-buffer
(save-buffer))
830 (kill-buffer base-buffer
))
832 ;; Restore the window configuration before capture
833 (set-window-configuration return-wconf
))
835 (run-hooks 'org-capture-after-finalize-hook
)
841 (message "Capture process aborted and target buffer cleaned up"))
843 (error "Capture process aborted, but target buffer could not be \
844 cleaned up correctly"))))
846 (org-capture-goto-last-stored)))
847 ;; Return if we did store something
850 (defun org-capture-refile ()
851 "Finalize the current capture and then refile the entry.
852 Refiling is done from the base buffer, because the indirect buffer is then
853 already gone. Any prefix argument will be passed to the refile command."
855 (unless (eq (org-capture-get :type
'local
) 'entry
)
856 (user-error "Refiling from a capture buffer makes only sense \
857 for `entry'-type templates"))
858 (let* ((base (or (buffer-base-buffer) (current-buffer)))
860 (org-capture-is-refiling t
)
861 (kill-buffer (org-capture-get :kill-buffer
'local
))
862 (jump-to-captured (org-capture-get :jump-to-captured
'local
)))
863 ;; Since `org-capture-finalize' may alter buffer contents (e.g.,
864 ;; empty lines) around entry, use a marker to refer to the
865 ;; headline to be refiled. Place the marker in the base buffer,
866 ;; as the current indirect one is going to be killed.
867 (set-marker pos
(save-excursion (org-back-to-heading t
) (point)) base
)
868 ;; `org-capture-finalize' calls `org-capture-goto-last-stored' too
869 ;; early. We want to wait for the refiling to be over, so we
870 ;; control when the latter function is called.
871 (org-capture-put :kill-buffer nil
:jump-to-captured nil
)
872 (org-capture-finalize)
873 (save-window-excursion
874 (with-current-buffer base
875 (org-with-point-at pos
876 (call-interactively 'org-refile
))))
878 (with-current-buffer base
(save-buffer))
880 (when jump-to-captured
(org-capture-goto-last-stored))))
882 (defun org-capture-kill ()
883 "Abort the current capture process."
885 ;; FIXME: This does not do the right thing, we need to remove the
886 ;; new stuff by hand it is easy: undo, then kill the buffer
887 (let ((org-note-abort t
)
888 (org-capture-before-finalize-hook nil
))
889 (org-capture-finalize)))
891 (defun org-capture-goto-last-stored ()
892 "Go to the location where the last capture note was stored."
894 (org-goto-marker-or-bmk org-capture-last-stored-marker
895 (plist-get org-bookmark-names-plist
897 (message "This is the last note stored by a capture process"))
899 ;;; Supporting functions for handling the process
901 (defun org-capture-put-target-region-and-position ()
902 "Store the initial region with `org-capture-put'."
904 :initial-target-region
905 ;; Check if the buffer is currently narrowed
906 (when (org-buffer-narrowed-p)
907 (cons (point-min) (point-max))))
908 ;; store the current point
909 (org-capture-put :initial-target-position
(point)))
911 (defvar org-time-was-given
) ; dynamically scoped parameter
912 (defun org-capture-set-target-location (&optional target
)
913 "Find TARGET buffer and position.
914 Store them in the capture property list."
915 (let ((target-entry-p t
))
917 (pcase (or target
(org-capture-get :target
))
919 (set-buffer (org-capture-target-buffer path
))
920 (org-capture-put-target-region-and-position)
922 (setq target-entry-p nil
))
924 (pcase (org-id-find id
)
925 (`(,path .
,position
)
926 (set-buffer (org-capture-target-buffer path
))
928 (org-capture-put-target-region-and-position)
929 (goto-char position
))
930 (_ (error "Cannot find target ID \"%s\"" id
))))
931 (`(file+headline
,path
,headline
)
932 (set-buffer (org-capture-target-buffer path
))
933 ;; Org expects the target file to be in Org mode, otherwise
934 ;; it throws an error. However, the default notes files
935 ;; should work out of the box. In this case, we switch it to
937 (unless (derived-mode-p 'org-mode
)
939 (format "Capture requirement: switching buffer %S to Org mode"
942 (org-capture-put-target-region-and-position)
944 (goto-char (point-min))
945 (if (re-search-forward (format org-complex-heading-regexp-format
946 (regexp-quote headline
))
949 (goto-char (point-max))
950 (unless (bolp) (insert "\n"))
951 (insert "* " headline
"\n")
952 (beginning-of-line 0)))
953 (`(file+olp
,path .
,outline-path
)
954 (let ((m (org-find-olp (cons (org-capture-expand-file path
)
956 (set-buffer (marker-buffer m
))
957 (org-capture-put-target-region-and-position)
961 (`(file+regexp
,path
,regexp
)
962 (set-buffer (org-capture-target-buffer path
))
963 (org-capture-put-target-region-and-position)
965 (goto-char (point-min))
966 (if (not (re-search-forward regexp nil t
))
967 (error "No match for target regexp in file %s" path
)
968 (goto-char (if (org-capture-get :prepend
)
971 (org-capture-put :exact-position
(point))
973 (and (derived-mode-p 'org-mode
) (org-at-heading-p)))))
974 (`(file+olp
+datetree
,path .
,outline-path
)
975 (let ((m (if outline-path
976 (org-find-olp (cons (org-capture-expand-file path
)
978 (set-buffer (org-capture-target-buffer path
))
980 (set-buffer (marker-buffer m
))
981 (org-capture-put-target-region-and-position)
985 (require 'org-datetree
)
986 (org-capture-put-target-region-and-position)
988 ;; Make a date/week tree entry, with the current date (or
989 ;; yesterday, if we are extending dates for a couple of hours)
991 (if (eq (org-capture-get :tree-type
) 'week
)
992 #'org-datetree-find-iso-week-create
993 #'org-datetree-find-date-create
)
994 (calendar-gregorian-from-absolute
996 (org-overriding-default-time
997 ;; Use the overriding default time.
998 (time-to-days org-overriding-default-time
))
999 ((or (org-capture-get :time-prompt
)
1000 (equal current-prefix-arg
1))
1002 (let ((prompt-time (org-read-date
1003 nil t nil
"Date for tree entry:"
1007 (cond ((and (or (not (boundp 'org-time-was-given
))
1008 (not org-time-was-given
))
1009 (not (= (time-to-days prompt-time
) (org-today))))
1010 ;; Use 00:00 when no time is given for another
1012 (apply #'encode-time
1013 (append `(0 0 ,org-extend-today-until
)
1014 (cl-cdddr (decode-time prompt-time
)))))
1015 ((string-match "\\([^ ]+\\)--?[^ ]+[ ]+\\(.*\\)"
1016 org-read-date-final-answer
)
1017 ;; Replace any time range by its start.
1018 (apply #'encode-time
1019 (org-read-date-analyze
1020 (replace-match "\\1 \\2" nil nil
1021 org-read-date-final-answer
)
1022 prompt-time
(decode-time prompt-time
))))
1024 (time-to-days prompt-time
)))
1026 ;; Current date, possibly corrected for late night
1029 ;; the following is the keep-restriction argument for
1030 ;; org-datetree-find-date-create
1031 (when outline-path
'subtree-at-point
))))
1032 (`(file+function
,path
,function
)
1033 (set-buffer (org-capture-target-buffer path
))
1034 (org-capture-put-target-region-and-position)
1037 (org-capture-put :exact-position
(point))
1038 (setq target-entry-p
1039 (and (derived-mode-p 'org-mode
) (org-at-heading-p))))
1042 (org-capture-put :exact-position
(point))
1043 (setq target-entry-p
1044 (and (derived-mode-p 'org-mode
) (org-at-heading-p))))
1046 (if (and (markerp org-clock-hd-marker
)
1047 (marker-buffer org-clock-hd-marker
))
1048 (progn (set-buffer (marker-buffer org-clock-hd-marker
))
1049 (org-capture-put-target-region-and-position)
1051 (goto-char org-clock-hd-marker
))
1052 (error "No running clock that could be used as capture target")))
1053 (target (error "Invalid capture target specification: %S" target
)))
1055 (org-capture-put :buffer
(current-buffer)
1057 :target-entry-p target-entry-p
1059 (and (featurep 'org-crypt
)
1060 (org-at-encrypted-entry-p)
1063 (and (org-back-to-heading t
) (point))))))))
1065 (defun org-capture-expand-file (file)
1066 "Expand functions, symbols and file names for FILE.
1067 When FILE is a function, call it. When it is a form, evaluate
1068 it. When it is a variable, return its value. When it is
1069 a string, treat it as a file name, possibly expanding it
1070 according to `org-directory', and return it. If it is the empty
1071 string, however, return `org-default-notes-file'. In any other
1072 case, raise an error."
1073 (let ((location (cond ((equal file
"") org-default-notes-file
)
1074 ((stringp file
) (expand-file-name file org-directory
))
1075 ((functionp file
) (funcall file
))
1076 ((and (symbolp file
) (boundp file
)) (symbol-value file
))
1078 (or (org-string-nw-p location
)
1079 (error "Invalid file location: %S" location
))))
1081 (defun org-capture-target-buffer (file)
1082 "Get a buffer for FILE.
1083 FILE is a generalized file location, as handled by
1084 `org-capture-expand-file'."
1085 (let ((file (org-capture-expand-file file
)))
1086 (or (org-find-base-buffer-visiting file
)
1087 (progn (org-capture-put :new-buffer t
)
1088 (find-file-noselect file
)))))
1090 (defun org-capture-place-template (&optional inhibit-wconf-store
)
1091 "Insert the template at the target location, and display the buffer.
1092 When `inhibit-wconf-store', don't store the window configuration, as it
1093 may have been stored before."
1094 (unless inhibit-wconf-store
1095 (org-capture-put :return-to-wconf
(current-window-configuration)))
1096 (delete-other-windows)
1097 (org-switch-to-buffer-other-window
1098 (org-capture-get-indirect-buffer (org-capture-get :buffer
) "CAPTURE"))
1101 (goto-char (org-capture-get :pos
))
1102 (setq-local outline-level
'org-outline-level
)
1103 (pcase (org-capture-get :type
)
1104 ((or `nil
`entry
) (org-capture-place-entry))
1105 (`table-line
(org-capture-place-table-line))
1106 (`plain
(org-capture-place-plain-text))
1107 (`item
(org-capture-place-item))
1108 (`checkitem
(org-capture-place-item)))
1109 (org-capture-mode 1)
1110 (setq-local org-capture-current-plist org-capture-plist
))
1112 (defun org-capture-place-entry ()
1113 "Place the template as a new Org entry."
1114 (let ((reversed?
(org-capture-get :prepend
))
1116 (when (org-capture-get :exact-position
)
1117 (goto-char (org-capture-get :exact-position
)))
1119 ;; Insert as a child of the current entry.
1120 ((org-capture-get :target-entry-p
)
1121 (setq level
(org-get-valid-level
1122 (if (org-at-heading-p) (org-outline-level) 1)
1124 (if reversed?
(outline-next-heading) (org-end-of-subtree t t
)))
1125 ;; Insert as a top-level entry at the beginning of the file.
1127 (goto-char (point-min))
1128 (unless (org-at-heading-p) (outline-next-heading)))
1129 ;; Otherwise, insert as a top-level entry at the end of the file.
1130 (t (goto-char (point-max))))
1131 (let ((origin (point)))
1132 (unless (bolp) (insert "\n"))
1133 (org-capture-empty-lines-before)
1134 (let ((beg (point)))
1135 (org-capture-position-for-last-stored beg
)
1136 (let ((template (org-capture-get :template
)))
1137 (org-capture-verify-tree template
)
1138 (org-paste-subtree level template
'for-yank
))
1139 (let ((end (if (org-at-heading-p) (line-end-position 0) (point))))
1140 (org-capture-empty-lines-after)
1141 (unless (org-at-heading-p) (outline-next-heading))
1142 (org-capture-mark-kill-region origin
(point))
1143 (org-capture-narrow beg end
)
1144 (when (or (search-backward "%?" beg t
)
1145 (search-forward "%?" end t
))
1146 (replace-match "")))))))
1148 (defun org-capture-place-item ()
1149 "Place the template as a new plain list item."
1150 (let* ((txt (org-capture-get :template
))
1151 (target-entry-p (org-capture-get :target-entry-p
))
1154 (if (org-capture-get :exact-position
)
1155 (goto-char (org-capture-get :exact-position
))
1157 ((not target-entry-p
)
1158 ;; Insert as top-level entry, either at beginning or at end of file
1159 (setq beg
(point-min) end
(point-max)))
1161 (setq beg
(1+ (point-at-eol))
1162 end
(save-excursion (outline-next-heading) (point)))))
1164 (if (org-capture-get :prepend
)
1167 (when (org-list-search-forward (org-item-beginning-re) end t
)
1168 (goto-char (match-beginning 0))
1169 (setq ind
(current-indentation))))
1171 (when (org-list-search-backward (org-item-beginning-re) beg t
)
1172 (setq ind
(current-indentation))
1174 (unless ind
(goto-char end
)))
1175 ;; Remove common indentation
1176 (setq txt
(org-remove-indentation txt
))
1177 ;; Make sure this is indeed an item
1178 (unless (string-match (concat "\\`" (org-item-re)) txt
)
1179 (setq txt
(concat "- "
1180 (mapconcat 'identity
(split-string txt
"\n")
1182 ;; Prepare surrounding empty lines.
1183 (unless (bolp) (insert "\n"))
1184 (org-capture-empty-lines-before)
1186 (unless (eolp) (save-excursion (insert "\n")))
1189 (setq ind
(current-indentation))
1190 (delete-region beg
(point)))
1191 ;; Set the correct indentation, depending on context
1192 (setq ind
(make-string ind ?\
))
1193 (setq txt
(concat ind
1194 (mapconcat 'identity
(split-string txt
"\n")
1199 (org-capture-empty-lines-after)
1200 (org-capture-position-for-last-stored beg
)
1202 (org-capture-mark-kill-region beg end
)
1203 (org-capture-narrow beg end
)
1204 (when (or (re-search-backward "%\\?" beg t
)
1205 (re-search-forward "%\\?" end t
))
1206 (replace-match ""))))
1208 (defun org-capture-place-table-line ()
1209 "Place the template as a table line."
1210 (require 'org-table
)
1212 (pcase (org-trim (org-capture-get :template
))
1213 ((pred (string-match-p org-table-border-regexp
))
1214 "| %?Bad template |")
1215 (text (concat text
"\n"))))
1216 (table-line-pos (org-capture-get :table-line-pos
))
1219 ((org-capture-get :exact-position
)
1220 (setq beg
(org-capture-get :exact-position
))
1221 (setq end
(save-excursion (outline-next-heading) (point))))
1222 ((not (org-capture-get :target-entry-p
))
1223 ;; Table is not necessarily under a heading. Find first table
1225 (setq beg
(point-min) end
(point-max)))
1227 ;; We are at a heading, limit search to the body.
1228 (setq beg
(line-beginning-position 2))
1229 (setq end
(save-excursion (outline-next-heading) (point)))))
1231 ;; Narrow to the table, possibly creating one if necessary.
1233 (while (re-search-forward org-table-dataline-regexp end t
)
1234 (pcase (org-element-lineage (org-element-at-point) '(table) t
)
1236 ((pred (lambda (e) (eq 'table.el
(org-element-property :type e
))))
1239 (goto-char (org-element-property :contents-end table
))
1240 (narrow-to-region (org-element-property :post-affiliated table
)
1243 ;; No table found. Create it with an empty header.
1245 (unless (bolp) (insert "\n"))
1246 (let ((origin (point)))
1247 (insert "| |\n|----|\n")
1248 (narrow-to-region origin
(point))))
1249 ;; In the current table, find the appropriate location for TEXT.
1251 ((and table-line-pos
1252 (string-match "\\(I+\\)\\([-+][0-9]+\\)" table-line-pos
))
1253 (goto-char (point-min))
1257 (save-match-data (org-table-analyze))
1258 (aref org-table-hlines
1259 (- (match-end 1) (match-beginning 1))))
1261 (error "Invalid table line specification %S" table-line-pos
))))
1262 (delta (string-to-number (match-string 2 table-line-pos
))))
1263 (forward-line (+ line delta
(if (< delta
0) 0 -
1)))
1264 (forward-line))) ;insert below
1265 ((org-capture-get :prepend
)
1266 (goto-char (point-min))
1268 ((not (re-search-forward org-table-hline-regexp nil t
)))
1269 ((re-search-forward org-table-dataline-regexp nil t
) (beginning-of-line))
1270 (t (goto-char (org-table-end)))))
1272 (goto-char (org-table-end))))
1273 ;; Insert text and position point according to template.
1274 (unless (bolp) (insert "\n"))
1276 (end (save-excursion
1279 (org-capture-position-for-last-stored 'table-line
)
1280 (org-capture-mark-kill-region beg end
)
1281 (org-capture-narrow beg end
)
1282 (when (or (re-search-backward "%\\?" beg t
)
1283 (re-search-forward "%\\?" end t
))
1284 (replace-match "")))
1287 (defun org-capture-place-plain-text ()
1288 "Place the template plainly.
1289 If the target locator points at an Org node, place the template into
1290 the text of the entry, before the first child. If not, place the
1291 template at the beginning or end of the file.
1292 Of course, if exact position has been required, just put it there."
1293 (let* ((txt (org-capture-get :template
))
1296 ((org-capture-get :exact-position
)
1297 (goto-char (org-capture-get :exact-position
)))
1298 ((and (org-capture-get :target-entry-p
)
1300 (looking-at org-outline-regexp
))
1301 ;; we should place the text into this entry
1302 (if (org-capture-get :prepend
)
1303 ;; Skip meta data and drawers
1304 (org-end-of-meta-data t
)
1305 ;; go to ent of the entry text, before the next headline
1306 (outline-next-heading)))
1308 ;; beginning or end of file
1309 (goto-char (if (org-capture-get :prepend
) (point-min) (point-max)))))
1310 (or (bolp) (newline))
1311 (org-capture-empty-lines-before)
1314 (org-capture-empty-lines-after)
1315 (org-capture-position-for-last-stored beg
)
1317 (org-capture-mark-kill-region beg
(1- end
))
1318 (org-capture-narrow beg
(1- end
))
1319 (when (or (re-search-backward "%\\?" beg t
)
1320 (re-search-forward "%\\?" end t
))
1321 (replace-match ""))))
1323 (defun org-capture-mark-kill-region (beg end
)
1324 "Mark the region that will have to be killed when aborting capture."
1325 (let ((m1 (copy-marker beg
))
1326 (m2 (copy-marker end t
)))
1327 (org-capture-put :begin-marker m1
)
1328 (org-capture-put :end-marker m2
)))
1330 (defun org-capture-position-for-last-stored (where)
1331 "Memorize the position that should later become the position of last capture."
1334 (org-capture-put :position-for-last-stored
1335 (move-marker (make-marker) where
1336 (or (buffer-base-buffer (current-buffer))
1337 (current-buffer)))))
1338 ((eq where
'table-line
)
1339 (org-capture-put :position-for-last-stored
1341 (org-table-current-dline))))
1342 (t (error "This should not happen"))))
1344 (defun org-capture-store-last-position ()
1345 "Store the last-captured position."
1346 (let* ((where (org-capture-get :position-for-last-stored
'local
))
1349 (prog1 (marker-position where
)
1350 (move-marker where nil
)))
1351 ((and (listp where
) (eq (car where
) 'table-line
))
1352 (if (org-at-table-p)
1354 (org-table-goto-line (nth 1 where
))
1357 (with-current-buffer (buffer-base-buffer (current-buffer))
1358 (org-with-point-at pos
1359 (when org-capture-bookmark
1360 (let ((bookmark (plist-get org-bookmark-names-plist
:last-capture
)))
1361 (when bookmark
(with-demoted-errors (bookmark-set bookmark
)))))
1362 (move-marker org-capture-last-stored-marker
(point))))))
1364 (defun org-capture-narrow (beg end
)
1365 "Narrow, unless configuration says not to narrow."
1366 (unless (org-capture-get :unnarrowed
)
1367 (narrow-to-region beg end
)
1370 (defun org-capture-empty-lines-before (&optional n
)
1371 "Set the correct number of empty lines before the insertion point.
1372 Point will be after the empty lines, so insertion can directly be done."
1373 (setq n
(or n
(org-capture-get :empty-lines-before
)
1374 (org-capture-get :empty-lines
) 0))
1375 (let ((pos (point)))
1376 (org-back-over-empty-lines)
1377 (delete-region (point) pos
)
1378 (when (> n
0) (newline n
))))
1380 (defun org-capture-empty-lines-after (&optional n
)
1381 "Set the correct number of empty lines after the inserted string.
1382 Point will remain at the first line after the inserted text."
1383 (setq n
(or n
(org-capture-get :empty-lines-after
)
1384 (org-capture-get :empty-lines
) 0))
1385 (org-back-over-empty-lines)
1386 (while (looking-at "[ \t]*\n") (replace-match ""))
1387 (let ((pos (point)))
1388 (when (> n
0) (newline n
))
1391 (defvar org-clock-marker
) ; Defined in org.el
1393 (defun org-capture-insert-template-here ()
1394 "Insert the capture template at point."
1395 (let* ((template (org-capture-get :template
))
1396 (type (org-capture-get :type
))
1398 (unless (bolp) (insert "\n"))
1401 ((and (eq type
'entry
) (derived-mode-p 'org-mode
))
1402 (org-capture-verify-tree (org-capture-get :template
))
1403 (org-paste-subtree nil template t
))
1404 ((and (memq type
'(item checkitem
))
1405 (derived-mode-p 'org-mode
)
1406 (save-excursion (skip-chars-backward " \t\n")
1411 (skip-chars-backward " ")
1412 (skip-chars-backward "-+*0123456789).")
1413 (delete-region (point) (point-at-eol))
1415 (org-remove-indentation template
)
1417 (org-capture-empty-lines-after)
1423 (org-capture-empty-lines-after)
1424 (skip-chars-forward " \t\n")
1425 (unless (eobp) (beginning-of-line))))
1428 (when (re-search-forward "%\\?" end t
)
1429 (replace-match ""))))
1431 (defun org-capture-set-plist (entry)
1432 "Initialize the property list from the template definition."
1433 (setq org-capture-plist
(copy-sequence (nthcdr 5 entry
)))
1434 (org-capture-put :key
(car entry
) :description
(nth 1 entry
)
1435 :target
(nth 3 entry
))
1436 (let ((txt (nth 4 entry
)) (type (or (nth 2 entry
) 'entry
)))
1437 (when (or (not txt
) (and (stringp txt
) (not (string-match "\\S-" txt
))))
1438 ;; The template may be empty or omitted for special types.
1439 ;; Here we insert the default templates for such cases.
1441 ((eq type
'item
) (setq txt
"- %?"))
1442 ((eq type
'checkitem
) (setq txt
"- [ ] %?"))
1443 ((eq type
'table-line
) (setq txt
"| %? |"))
1444 ((member type
'(nil entry
)) (setq txt
"* %?\n %a"))))
1445 (org-capture-put :template txt
:type type
)))
1447 (defun org-capture-goto-target (&optional template-key
)
1448 "Go to the target location of a capture template.
1449 The user is queried for the template."
1451 (let ((entry (org-capture-select-template template-key
)))
1452 (unless entry
(error "No capture template selected"))
1453 (org-capture-set-plist entry
)
1454 (org-capture-set-target-location)
1455 (pop-to-buffer-same-window (org-capture-get :buffer
))
1456 (goto-char (org-capture-get :pos
))))
1458 (defun org-capture-get-indirect-buffer (&optional buffer prefix
)
1459 "Make an indirect buffer for a capture process.
1460 Use PREFIX as a prefix for the name of the indirect buffer."
1461 (setq buffer
(or buffer
(current-buffer)))
1462 (let ((n 1) (base (buffer-name buffer
)) bname
)
1463 (setq bname
(concat prefix
"-" base
))
1464 (while (buffer-live-p (get-buffer bname
))
1465 (setq bname
(concat prefix
"-" (number-to-string (cl-incf n
)) "-" base
)))
1467 (make-indirect-buffer buffer bname
'clone
)
1469 (let ((buf (make-indirect-buffer buffer bname
)))
1470 (with-current-buffer buf
(org-mode))
1473 (defun org-capture-verify-tree (tree)
1474 "Throw error if TREE is not a valid tree."
1475 (unless (org-kill-is-subtree-p tree
)
1476 (error "Template is not a valid Org entry or tree")))
1478 ;;; The template code
1479 (defun org-capture-select-template (&optional keys
)
1480 "Select a capture template.
1481 Lisp programs can force the template by setting KEYS to a string."
1482 (let ((org-capture-templates
1483 (or (org-contextualize-keys
1484 (org-capture-upgrade-templates org-capture-templates
)
1485 org-capture-templates-contexts
)
1486 '(("t" "Task" entry
(file+headline
"" "Tasks")
1487 "* TODO %?\n %u\n %a")))))
1489 (or (assoc keys org-capture-templates
)
1490 (error "No capture template referred to by \"%s\" keys" keys
))
1491 (org-mks org-capture-templates
1492 "Select a capture template\n========================="
1494 '(("C" "Customize org-capture-templates")
1497 (defvar org-capture--clipboards nil
1498 "List various clipboards values.")
1500 (defun org-capture-fill-template (&optional template initial annotation
)
1501 "Fill a template and return the filled template as a string.
1502 The template may still contain \"%?\" for cursor positioning."
1503 (let* ((template (or template
(org-capture-get :template
)))
1504 (buffer (org-capture-get :buffer
))
1505 (file (buffer-file-name (or (buffer-base-buffer buffer
) buffer
)))
1506 (time (let* ((c (or (org-capture-get :default-time
) (current-time)))
1507 (d (decode-time c
)))
1508 (if (< (nth 2 d
) org-extend-today-until
)
1509 (encode-time 0 59 23 (1- (nth 3 d
)) (nth 4 d
) (nth 5 d
))
1511 (v-t (format-time-string (org-time-stamp-format nil
) time
))
1512 (v-T (format-time-string (org-time-stamp-format t
) time
))
1513 (v-u (format-time-string (org-time-stamp-format nil t
) time
))
1514 (v-U (format-time-string (org-time-stamp-format t t
) time
))
1515 (v-c (and kill-ring
(current-kill 0)))
1516 (v-x (or (org-get-x-clipboard 'PRIMARY
)
1517 (org-get-x-clipboard 'CLIPBOARD
)
1518 (org-get-x-clipboard 'SECONDARY
)
1519 "")) ;ensure it is a string
1520 ;; `initial' and `annotation' might have been passed. But if
1521 ;; the property list has them, we prefer those values.
1522 (v-i (or (plist-get org-store-link-plist
:initial
)
1523 (and (stringp initial
) (org-no-properties initial
))
1524 (org-capture-get :initial
)
1527 (let ((a (or (plist-get org-store-link-plist
:annotation
)
1529 (org-capture-get :annotation
)
1531 ;; Is the link empty? Then we do not want it...
1532 (if (equal a
"[[]]") "" a
)))
1533 (l-re "\\[\\[\\(.*?\\)\\]\\(\\[.*?\\]\\)?\\]")
1534 (v-A (if (and v-a
(string-match l-re v-a
))
1535 (replace-match "[[\\1][%^{Link description}]]" nil nil v-a
)
1537 (v-l (if (and v-a
(string-match l-re v-a
))
1538 (replace-match "\\1" nil nil v-a
)
1540 (v-n user-full-name
)
1541 (v-k (if (marker-buffer org-clock-marker
)
1542 (org-no-properties org-clock-heading
)
1544 (v-K (if (marker-buffer org-clock-marker
)
1545 (org-make-link-string
1547 (buffer-file-name (marker-buffer org-clock-marker
))
1551 (v-f (or (org-capture-get :original-file-nondirectory
) ""))
1552 (v-F (or (org-capture-get :original-file
) ""))
1553 (org-capture--clipboards
1556 (org-get-x-clipboard 'PRIMARY
)
1557 (org-get-x-clipboard 'CLIPBOARD
)
1558 (org-get-x-clipboard 'SECONDARY
)
1561 (setq org-store-link-plist
(plist-put org-store-link-plist
:annotation v-a
))
1562 (setq org-store-link-plist
(plist-put org-store-link-plist
:initial v-i
))
1566 (message "no template") (ding)
1568 (save-window-excursion
1569 (org-switch-to-buffer-other-window (get-buffer-create "*Capture*"))
1571 (setq buffer-file-name nil
)
1572 (setq mark-active nil
)
1574 (goto-char (point-min))
1576 ;; %[] insert contents of a file.
1578 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t
)
1579 (let ((filename (expand-file-name (match-string 1)))
1580 (beg (copy-marker (match-beginning 0)))
1581 (end (copy-marker (match-end 0))))
1582 (unless (org-capture-escaped-%
)
1583 (delete-region beg end
)
1584 (set-marker beg nil
)
1585 (set-marker end nil
)
1586 (condition-case error
1587 (insert-file-contents filename
)
1589 (insert (format "%%![couldn not insert %s: %s]"
1593 ;; Mark %() embedded elisp for later evaluation.
1594 (org-capture-expand-embedded-elisp 'mark
)
1596 ;; Expand non-interactive templates.
1597 (let ((regexp "%\\(:[-a-za-z]+\\|<\\([^>\n]+\\)>\\|[aAcfFikKlntTuUx]\\)"))
1599 (while (re-search-forward regexp nil t
)
1600 ;; `org-capture-escaped-%' may modify buffer and cripple
1601 ;; match-data. Use markers instead. Ditto for other
1603 (let ((pos (copy-marker (match-beginning 0)))
1604 (end (copy-marker (match-end 0)))
1605 (value (match-string 1))
1606 (time-string (match-string 2)))
1607 (unless (org-capture-escaped-%
)
1608 (delete-region pos end
)
1609 (set-marker pos nil
)
1610 (set-marker end nil
)
1611 (let* ((inside-sexp?
(org-capture-inside-embedded-elisp-p))
1613 (pcase (string-to-char value
)
1614 (?
< (format-time-string time-string time
))
1616 (or (plist-get org-store-link-plist
(intern value
))
1619 (if inside-sexp? v-i
1620 ;; Outside embedded Lisp, repeat leading
1621 ;; characters before initial place holder
1623 (let ((lead (buffer-substring-no-properties
1624 (line-beginning-position) (point))))
1625 (replace-regexp-in-string "\n\\(.\\)"
1644 ;; Escape sensitive characters.
1645 (replace-regexp-in-string "[\\\"]" "\\\\\\&" replacement
)
1648 ;; Expand %() embedded Elisp. Limit to Sexp originally marked.
1649 (org-capture-expand-embedded-elisp)
1651 ;; Expand interactive templates. This is the last step so that
1652 ;; template is mostly expanded when prompting happens. Turn on
1653 ;; Org mode and set local variables. This is to support
1654 ;; completion in interactive prompts.
1655 (let ((org-inhibit-startup t
)) (org-mode))
1656 (org-clone-local-variables buffer
"\\`org-")
1657 (let (strings) ; Stores interactive answers.
1659 (let ((regexp "%\\^\\(?:{\\([^}]*\\)}\\)?\\([CgGLptTuU]\\)?"))
1660 (while (re-search-forward regexp nil t
)
1661 (let* ((items (and (match-end 1)
1663 (split-string (match-string-no-properties 1)
1665 (key (match-string 2))
1666 (beg (copy-marker (match-beginning 0)))
1667 (end (copy-marker (match-end 0)))
1668 (prompt (nth 0 items
))
1669 (default (nth 1 items
))
1670 (completions (nthcdr 2 items
)))
1671 (unless (org-capture-escaped-%
)
1672 (delete-region beg end
)
1673 (set-marker beg nil
)
1674 (set-marker end nil
)
1677 (let* ((org-last-tags-completion-table
1678 (org-global-tags-completion-table
1679 (cond ((equal key
"G") (org-agenda-files))
1682 (org-add-colon-after-tag-completion t
)
1687 (if prompt
(concat prompt
": ") "Tags: ")
1688 'org-tags-completion-function nil nil nil
1690 "[^[:alnum:]_@#%]+")
1692 (when (org-string-nw-p ins
)
1693 (unless (eq (char-before) ?
:) (insert ":"))
1695 (unless (eq (char-after) ?
:) (insert ":"))
1696 (when (org-at-heading-p) (org-align-tags)))))
1698 (let ((insert-fun (if (equal key
"C") #'insert
1699 (lambda (s) (org-insert-link 0 s
)))))
1700 (pcase org-capture--clipboards
1702 (`(,value
) (funcall insert-fun value
))
1703 (`(,first-value .
,_
)
1705 (read-string "Clipboard/kill value: "
1707 'org-capture--clipboards
1709 (_ (error "Invalid `org-capture--clipboards' value: %S"
1710 org-capture--clipboards
)))))
1712 ;; We remove file properties inherited from
1713 ;; target buffer so `org-read-property-value' has
1714 ;; a chance to find allowed values in sub-trees
1715 ;; from the target buffer.
1716 (setq-local org-file-properties nil
)
1717 (let* ((origin (set-marker (make-marker)
1718 (org-capture-get :pos
)
1719 (org-capture-get :buffer
)))
1720 ;; Find location from where to get allowed
1721 ;; values. If `:target-entry-p' is
1722 ;; non-nil, the current headline in the
1723 ;; target buffer is going to be a parent
1724 ;; headline, so location is fine.
1725 ;; Otherwise, find the parent headline in
1726 ;; the target buffer.
1727 (pom (if (org-capture-get :target-entry-p
) origin
1729 (while (org-up-heading-safe))
1730 (org-current-level))))
1731 (org-with-point-at origin
1732 (let ((l (if (org-at-heading-p)
1734 most-positive-fixnum
)))
1735 (while (and l
(>= l level
))
1736 (setq l
(org-up-heading-safe)))
1737 (if l
(point-marker)
1738 (point-min-marker)))))))
1739 (value (org-read-property-value prompt pom
)))
1740 (org-set-property prompt value
)))
1741 ((or "t" "T" "u" "U")
1742 ;; These are the date/time related ones.
1743 (let* ((upcase?
(equal (upcase key
) key
))
1744 (org-end-time-was-given nil
)
1745 (time (org-read-date upcase? t nil prompt
)))
1746 (org-insert-time-stamp
1747 time
(or org-time-was-given upcase?
)
1748 (member key
'("u" "U"))
1749 nil nil
(list org-end-time-was-given
))))
1751 ;; Load history list for current prompt.
1752 (setq org-capture--prompt-history
1753 (gethash prompt org-capture--prompt-history-table
))
1754 (push (org-completing-read
1755 (concat (or prompt
"Enter string")
1756 (and default
(format " [%s]" default
))
1759 nil nil nil
'org-capture--prompt-history default
)
1761 (insert (car strings
))
1762 ;; Save updated history list for current prompt.
1763 (puthash prompt org-capture--prompt-history
1764 org-capture--prompt-history-table
))
1766 (error "Unknown template placeholder: \"%%^%s\""
1769 ;; Replace %n escapes with nth %^{...} string.
1770 (setq strings
(nreverse strings
))
1772 (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t
)
1773 (unless (org-capture-escaped-%
)
1775 (nth (1- (string-to-number (match-string 1))) strings
)
1778 ;; Make sure there are no empty lines before the text, and that
1779 ;; it ends with a newline character or it is empty.
1780 (skip-chars-forward " \t\n")
1781 (delete-region (point-min) (line-beginning-position))
1782 (goto-char (point-max))
1783 (skip-chars-backward " \t\n")
1784 (delete-region (point) (point-max))
1785 (unless (bobp) (insert "\n"))
1787 ;; Return the expanded template and kill the capture buffer.
1788 (untabify (point-min) (point-max))
1789 (set-buffer-modified-p nil
)
1790 (prog1 (buffer-substring-no-properties (point-min) (point-max))
1791 (kill-buffer (current-buffer))))))
1793 (defun org-capture-escaped-%
()
1794 "Non-nil if % was escaped.
1795 If yes, unescape it now. Assume match-data contains the
1796 placeholder to check."
1798 (goto-char (match-beginning 0))
1799 (let ((n (abs (skip-chars-backward "\\\\"))))
1800 (delete-char (/ (1+ n
) 2))
1803 (defun org-capture-expand-embedded-elisp (&optional mark
)
1804 "Evaluate embedded elisp %(sexp) and replace with the result.
1805 When optional MARK argument is non-nil, mark Sexp with a text
1806 property (`org-embedded-elisp') for later evaluation. Only
1807 marked Sexp are evaluated when this argument is nil."
1809 (goto-char (point-min))
1810 (while (re-search-forward "%(" nil t
)
1812 ((get-text-property (match-beginning 0) 'org-embedded-elisp
)
1813 (goto-char (match-beginning 0))
1814 (let ((template-start (point)))
1816 (let* ((sexp (read (current-buffer)))
1818 (org-capture--expand-keyword-in-embedded-elisp
1820 (delete-region template-start
(point))
1823 ((stringp result
) (insert result
))
1825 "Capture template sexp `%s' must evaluate to string or nil"
1828 ;; Only mark valid and non-escaped sexp.
1829 ((org-capture-escaped-%
) nil
)
1831 (let ((end (with-syntax-table emacs-lisp-mode-syntax-table
1832 (ignore-errors (scan-sexps (1- (point)) 1)))))
1834 (put-text-property (- (point) 2) end
'org-embedded-elisp t
))))))))
1836 (defun org-capture--expand-keyword-in-embedded-elisp (attr)
1837 "Recursively replace capture link keywords in ATTR sexp.
1838 Such keywords are prefixed with \"%:\". See
1839 `org-capture-template' for more information."
1841 (mapcar 'org-capture--expand-keyword-in-embedded-elisp attr
))
1843 (let* ((attr-symbol (symbol-name attr
))
1844 (key (and (string-match "%\\(:.*\\)" attr-symbol
)
1845 (intern (match-string 1 attr-symbol
)))))
1846 (or (plist-get org-store-link-plist key
)
1850 (defun org-capture-inside-embedded-elisp-p ()
1851 "Non-nil if point is inside of embedded elisp %(sexp).
1852 Assume sexps have been marked with
1853 `org-capture-expand-embedded-elisp' beforehand."
1854 (get-text-property (point) 'org-embedded-elisp
))
1857 (defun org-capture-import-remember-templates ()
1858 "Set `org-capture-templates' to be similar to `org-remember-templates'."
1860 (when (and (yes-or-no-p
1861 "Import old remember templates into org-capture-templates? ")
1863 "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
1864 (require 'org-remember
)
1865 (setq org-capture-templates
1868 (let ((desc (car entry
))
1869 (key (char-to-string (nth 1 entry
)))
1870 (template (nth 2 entry
))
1871 (file (or (nth 3 entry
) org-default-notes-file
))
1872 (position (or (nth 4 entry
) org-remember-default-headline
))
1874 (prepend org-reverse-note-order
)
1875 immediate target jump-to-captured
)
1877 ((member position
'(top bottom
))
1878 (setq target
(list 'file file
)
1879 prepend
(eq position
'top
)))
1880 ((eq position
'date-tree
)
1881 (setq target
(list 'file
+datetree file
)
1883 (t (setq target
(list 'file
+headline file position
))))
1885 (when (string-match "%!" template
)
1886 (setq template
(replace-match "" t t template
)
1889 (when (string-match "%&" template
)
1890 (setq jump-to-captured t
))
1892 (append (list key desc type target template
)
1893 (and prepend
'(:prepend t
))
1894 (and immediate
'(:immediate-finish t
))
1895 (and jump-to-captured
'(:jump-to-captured t
)))))
1897 org-remember-templates
))))
1900 (provide 'org-capture
)
1902 ;;; org-capture.el ends here