1 ;;; org-capture.el --- Fast note taking in Org-mode
3 ;; Copyright (C) 2010-2012 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://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 <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains an alternative implementation of the same functionality
28 ;; that is also 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 for this
34 ;; 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?
55 (declare-function org-datetree-find-date-create
"org-datetree"
56 (date &optional keep-restriction
))
57 (declare-function org-table-get-specials
"org-table" ())
58 (declare-function org-table-goto-line
"org-table" (N))
59 (declare-function org-pop-to-buffer-same-window
"org-compat"
60 (&optional buffer-or-name norecord label
))
61 (declare-function org-at-encrypted-entry-p
"org-crypt" ())
62 (declare-function org-encrypt-entry
"org-crypt" ())
63 (declare-function org-decrypt-entry
"org-crypt" ())
65 (defvar org-remember-default-headline
)
66 (defvar org-remember-templates
)
67 (defvar org-table-hlines
)
68 (defvar dired-buffers
)
70 (defvar org-capture-clock-was-started nil
71 "Internal flag, noting if the clock was started.")
73 (defvar org-capture-last-stored-marker
(make-marker)
74 "Marker pointing to the entry most recently stored with `org-capture'.")
76 ;; The following variable is scoped dynamically by org-protocol
77 ;; to indicate that the link properties have already been stored
78 (defvar org-capture-link-is-already-stored nil
)
80 (defgroup org-capture nil
81 "Options concerning capturing new entries."
85 (defcustom org-capture-templates nil
86 "Templates for the creation of new entries.
88 Each entry is a list with the following items:
90 keys The keys that will select the template, as a string, characters
91 only, for example \"a\" for a template to be selected with a
92 single key, or \"bt\" for selection with two keys. When using
93 several keys, keys using the same prefix key must be together
94 in the list and preceded by a 2-element entry explaining the
95 prefix key, for example
97 (\"b\" \"Templates for marking stuff to buy\")
99 The \"C\" key is used by default for quick access to the
100 customization of the template variable. But if you want to use
101 that key for a template, you can.
103 description A short string describing the template, will be shown during
106 type The type of entry. Valid types are:
107 entry an Org-mode node, with a headline. Will be
108 filed as the child of the target entry or as
110 item a plain list item, will be placed in the
111 first plain list at the target
113 checkitem a checkbox item. This differs from the
114 plain list item only is so far as it uses a
115 different default template.
116 table-line a new line in the first table at target location.
117 plain text to be inserted as it is.
119 target Specification of where the captured item should be placed.
120 In Org-mode files, targets usually define a node. Entries will
121 become children of this node, other types will be added to the
122 table or list in the body of this node.
124 Most target specifications contain a file name. If that file
125 name is the empty string, it defaults to `org-default-notes-file'.
126 A file can also be given as a variable, function, or Emacs Lisp
131 (file \"path/to/file\")
132 Text will be placed at the beginning or end of that file
134 (id \"id of existing org entry\")
135 File as child of this entry, or in the body of the entry
137 (file+headline \"path/to/file\" \"node headline\")
138 Fast configuration if the target heading is unique in the file
140 (file+olp \"path/to/file\" \"Level 1 heading\" \"Level 2\" ...)
141 For non-unique headings, the full path is safer
143 (file+regexp \"path/to/file\" \"regexp to find location\")
144 File to the entry matching regexp
146 (file+datetree \"path/to/file\")
147 Will create a heading in a date tree for today's date
149 (file+datetree+prompt \"path/to/file\")
150 Will create a heading in a date tree, prompts for date
152 (file+function \"path/to/file\" function-finding-location)
153 A function to find the right location in the file
156 File to the entry that is currently being clocked
158 (function function-finding-location)
159 Most general way, write your own function to find both
162 template The template for creating the capture item. If you leave this
163 empty, an appropriate default template will be used. See below
164 for more details. Instead of a string, this may also be one of
166 (file \"/path/to/template-file\")
167 (function function-returning-the-template)
169 in order to get a template from a file, or dynamically
172 The rest of the entry is a property list of additional options. Recognized
175 :prepend Normally newly captured information will be appended at
176 the target location (last child, last table line,
177 last list item...). Setting this property will
180 :immediate-finish When set, do not offer to edit the information, just
181 file it away immediately. This makes sense if the
182 template only needs information that can be added
185 :empty-lines Set this to the number of lines the should be inserted
186 before and after the new item. Default 0, only common
189 :empty-lines-before Set this to the number of lines the should be inserted
190 before the new item. Overrides :empty-lines for the
191 number lines inserted before.
193 :empty-lines-after Set this to the number of lines the should be inserted
194 after the new item. Overrides :empty-lines for the
195 number of lines inserted after.
197 :clock-in Start the clock in this item.
199 :clock-keep Keep the clock running when filing the captured entry.
201 :clock-resume Start the interrupted clock when finishing the capture.
202 Note that :clock-keep has precedence over :clock-resume.
203 When setting both to `t', the current clock will run and
204 the previous one will not be resumed.
206 :unnarrowed Do not narrow the target buffer, simply show the
207 full buffer. Default is to narrow it so that you
208 only see the new stuff.
210 :table-line-pos Specification of the location in the table where the
211 new line should be inserted. It should be a string like
212 \"II-3\", meaning that the new line should become the
213 third line before the second horizontal separator line.
215 :kill-buffer If the target file was not yet visited by a buffer when
216 capture was invoked, kill the buffer again after capture
219 The template defines the text to be inserted. Often this is an
220 org-mode entry (so the first line should start with a star) that
221 will be filed as a child of the target headline. It can also be
222 freely formatted text. Furthermore, the following %-escapes will
223 be replaced with content and expanded in this order:
225 %[pathname] Insert the contents of the file given by `pathname'.
226 %(sexp) Evaluate elisp `(sexp)' and replace it with the results.
227 For convenience, %:keyword (see below) placeholders within
228 the expression will be expanded prior to this.
229 %<...> The result of format-time-string on the ... format specification.
230 %t Time stamp, date only.
231 %T Time stamp with date and time.
232 %u, %U Like the above, but inactive time stamps.
233 %i Initial content, copied from the active region. If %i is
234 indented, the entire inserted text will be indented as well.
235 %a Annotation, normally the link created with `org-store-link'.
236 %A Like %a, but prompt for the description part.
237 %l Like %a, but only insert the literal link.
238 %c Current kill ring head.
239 %x Content of the X clipboard.
240 %k Title of currently clocked task.
241 %K Link to currently clocked task.
242 %n User name (taken from `user-full-name').
243 %f File visited by current buffer when org-capture was called.
244 %F Full path of the file or directory visited by current buffer.
245 %:keyword Specific information for certain link types, see below.
246 %^g Prompt for tags, with completion on tags in target file.
247 %^G Prompt for tags, with completion on all tags in all agenda files.
248 %^t Like %t, but prompt for date. Similarly %^T, %^u, %^U.
249 You may define a prompt like: %^{Please specify birthday}t
250 %^C Interactive selection of which kill or clip to use.
251 %^L Like %^C, but insert as link.
252 %^{prop}p Prompt the user for a value for property `prop'.
253 %^{prompt} Prompt the user for a string and replace this sequence with it.
254 A default value and a completion table ca be specified like this:
255 %^{prompt|default|completion2|completion3|...}.
256 %? After completing the template, position cursor here.
257 %\\n Insert the text entered at the nth %^{prompt}, where `n' is
258 a number, starting from 1.
260 Apart from these general escapes, you can access information specific to
261 the link type that is created. For example, calling `org-capture' in emails
262 or in Gnus will record the author and the subject of the message, which you
263 can access with \"%:from\" and \"%:subject\", respectively. Here is a
264 complete list of what is recorded for each link type.
266 Link type | Available information
267 ------------------------+------------------------------------------------------
268 bbdb | %:type %:name %:company
269 vm, wl, mh, mew, rmail, | %:type %:subject %:message-id
270 gnus | %:from %:fromname %:fromaddress
271 | %:to %:toname %:toaddress
272 | %:fromto (either \"to NAME\" or \"from NAME\")
273 | %:date %:date-timestamp (as active timestamp)
274 | %:date-timestamp-inactive (as inactive timestamp)
275 gnus | %:group, for messages also all email fields
276 w3, w3m | %:type %:url
277 info | %:type %:file %:node
278 calendar | %:type %:date"
283 (choice :value
("" "" entry
(file "~/org/notes.org") "")
284 (list :tag
"Multikey description"
285 (string :tag
"Keys ")
286 (string :tag
"Description"))
287 (list :tag
"Template entry"
288 (string :tag
"Keys ")
289 (string :tag
"Description ")
290 (choice :tag
"Capture Type " :value entry
291 (const :tag
"Org entry" entry
)
292 (const :tag
"Plain list item" item
)
293 (const :tag
"Checkbox item" checkitem
)
294 (const :tag
"Plain text" plain
)
295 (const :tag
"Table line" table-line
))
296 (choice :tag
"Target location"
298 (const :format
"" file
)
301 (const :format
"" id
)
303 (list :tag
"File & Headline"
304 (const :format
"" file
+headline
)
306 (string :tag
" Headline"))
307 (list :tag
"File & Outline path"
308 (const :format
"" file
+olp
)
310 (repeat :tag
"Outline path" :inline t
311 (string :tag
"Headline")))
312 (list :tag
"File & Regexp"
313 (const :format
"" file
+regexp
)
315 (regexp :tag
" Regexp"))
316 (list :tag
"File & Date tree"
317 (const :format
"" file
+datetree
)
319 (list :tag
"File & Date tree, prompt for date"
320 (const :format
"" file
+datetree
+prompt
)
322 (list :tag
"File & function"
323 (const :format
"" file
+function
)
325 (sexp :tag
" Function"))
326 (list :tag
"Current clocking task"
327 (const :format
"" clock
))
328 (list :tag
"Function"
329 (const :format
"" function
)
330 (sexp :tag
" Function")))
331 (choice :tag
"Template"
334 (const :format
"" file
)
335 (file :tag
"Template file"))
336 (list :tag
"Function"
337 (const :format
"" function
)
338 (function :tag
"Template function")))
340 ;; Give the most common options as checkboxes
341 :options
(((const :format
"%v " :prepend
) (const t
))
342 ((const :format
"%v " :immediate-finish
) (const t
))
343 ((const :format
"%v " :empty-lines
) (const 1))
344 ((const :format
"%v " :clock-in
) (const t
))
345 ((const :format
"%v " :clock-keep
) (const t
))
346 ((const :format
"%v " :clock-resume
) (const t
))
347 ((const :format
"%v " :unnarrowed
) (const t
))
348 ((const :format
"%v " :kill-buffer
) (const t
))))))))
350 (defcustom org-capture-before-finalize-hook nil
351 "Hook that is run right before a capture process is finalized.
352 The capture buffer is still current when this hook runs and it is
353 widened to the entire buffer."
358 (defcustom org-capture-after-finalize-hook nil
359 "Hook that is run right after a capture process is finalized.
360 Suitable for window cleanup."
365 (defcustom org-capture-prepare-finalize-hook nil
366 "Hook that is run before the finalization starts.
367 The capture buffer is current and still narrowed."
372 (defcustom org-capture-bookmark t
373 "When non-nil, add a bookmark pointing at the last stored
374 position when capturing."
379 ;;; The property list for keeping information about the capture process
381 (defvar org-capture-plist nil
382 "Plist for the current capture process, global, to avoid having to pass it.")
384 (defvar org-capture-current-plist nil
385 "Local variable holding the plist in a capture buffer.
386 This is used to store the plist for use when finishing a capture process
387 because another such process might have changed the global variable by then.
389 Each time a new capture buffer has been set up, the global `org-capture-plist'
390 is copied to this variable, which is local in the indirect buffer.")
392 (defvar org-capture-clock-keep nil
393 "Local variable to store the value of the :clock-keep parameter.
394 This is needed in case org-capture-finalize is called interactively.")
396 (defun org-capture-put (&rest stuff
)
397 "Add properties to the capture property list `org-capture-plist'."
399 (setq org-capture-plist
(plist-put org-capture-plist
400 (pop stuff
) (pop stuff
)))))
401 (defun org-capture-get (prop &optional local
)
402 "Get properties from the capture property list `org-capture-plist'.
403 When LOCAL is set, use the local variable `org-capture-current-plist',
404 this is necessary after initialization of the capture process,
405 to avoid conflicts with other active capture processes."
406 (plist-get (if local org-capture-current-plist org-capture-plist
) prop
))
408 (defun org-capture-member (prop &optional local
)
409 "Is PROP a property in `org-capture-plist'.
410 When LOCAL is set, use the local variable `org-capture-current-plist',
411 this is necessary after initialization of the capture process,
412 to avoid conflicts with other active capture processes."
413 (plist-get (if local org-capture-current-plist org-capture-plist
) prop
))
417 (defvar org-capture-mode-map
(make-sparse-keymap)
418 "Keymap for `org-capture-mode', a minor mode.
419 Use this map to set additional keybindings for when Org-mode is used
420 for a capture buffer.")
422 (defvar org-capture-mode-hook nil
423 "Hook for the minor `org-capture-mode'.")
425 (define-minor-mode org-capture-mode
426 "Minor mode for special key bindings in a capture buffer.
428 Turning on this mode runs the normal hook `org-capture-mode-hook'."
429 nil
" Rem" org-capture-mode-map
432 "Capture buffer. Finish `C-c C-c', refile `C-c C-w', abort `C-c C-k'."))
433 (define-key org-capture-mode-map
"\C-c\C-c" 'org-capture-finalize
)
434 (define-key org-capture-mode-map
"\C-c\C-k" 'org-capture-kill
)
435 (define-key org-capture-mode-map
"\C-c\C-w" 'org-capture-refile
)
437 ;;; The main commands
439 (defvar org-capture-initial nil
)
440 (defvar org-capture-entry nil
)
443 (defun org-capture-string (string &optional keys
)
444 (interactive "sInitial text: \n")
445 (let ((org-capture-initial string
)
446 (org-capture-entry (org-capture-select-template keys
)))
449 (defcustom org-capture-templates-contexts nil
450 "Alist of capture templates and valid contexts.
452 For example, if you have a capture template \"c\" and you want
453 this template to be accessible only from `message-mode' buffers,
456 '((\"c\" (in-mode . \"message-mode\")))
458 Here are the available contexts definitions:
460 in-file: command displayed only in matching files
461 in-mode: command displayed only in matching modes
462 not-in-file: command not displayed in matching files
463 not-in-mode: command not displayed in matching modes
464 [function]: a custom function taking no argument
466 If you define several checks, the agenda command will be
467 accessible if there is at least one valid check.
469 You can also bind a key to another agenda custom command
470 depending on contextual rules.
472 '((\"c\" \"d\" (in-mode . \"message-mode\")))
474 Here it means: in `message-mode buffers', use \"d\" as the
475 key for the capture template otherwise associated with \"d\".
476 \(The template originally associated with \"q\" is not displayed
477 to avoid duplicates.)"
480 :type
'(repeat (list :tag
"Rule"
481 (string :tag
" Capture key")
482 (string :tag
"Replace by template")
483 (repeat :tag
"Available when"
485 (cons :tag
"Condition"
487 (const :tag
"In file" in-file
)
488 (const :tag
"Not in file" not-in-file
)
489 (const :tag
"In mode" in-mode
)
490 (const :tag
"Not in mode" not-in-mode
))
492 (function :tag
"Custom function"))))))
494 (defcustom org-capture-use-agenda-date nil
495 "Non-nil means use the date at point when capturing from agendas.
496 When nil, you can still capturing using the date at point with \\[org-agenda-capture]]."
502 (defun org-capture (&optional goto keys
)
504 \\<org-capture-mode-map>
505 This will let you select a template from `org-capture-templates', and then
506 file the newly captured information. The text is immediately inserted
507 at the target location, and an indirect buffer is shown where you can
508 edit it. Pressing \\[org-capture-finalize] brings you back to the previous state
509 of Emacs, so that you can continue your work.
511 When called interactively with a \\[universal-argument] prefix argument GOTO, don't capture
512 anything, just go to the file/headline where the selected template
513 stores its notes. With a double prefix argument \
514 \\[universal-argument] \\[universal-argument], go to the last note
517 When called with a `C-0' (zero) prefix, insert a template at point.
519 Lisp programs can set KEYS to a string associated with a template
520 in `org-capture-templates'. In this case, interactive selection
523 If `org-capture-use-agenda-date' is non-nil, capturing from the
524 agenda will use the date at point as the default date."
526 (when (and org-capture-use-agenda-date
527 (eq major-mode
'org-agenda-mode
))
528 (setq org-overriding-default-time
529 (org-get-cursor-date)))
531 ((equal goto
'(4)) (org-capture-goto-target))
532 ((equal goto
'(16)) (org-capture-goto-last-stored))
534 ;; FIXME: Are these needed?
535 (let* ((orig-buf (current-buffer))
536 (annotation (if (and (boundp 'org-capture-link-is-already-stored
)
537 org-capture-link-is-already-stored
)
538 (plist-get org-store-link-plist
:annotation
)
539 (ignore-errors (org-store-link nil
))))
540 (entry (or org-capture-entry
(org-capture-select-template keys
)))
542 (setq initial
(or org-capture-initial
543 (and (org-region-active-p)
544 (buffer-substring (point) (mark)))))
545 (when (stringp initial
)
546 (remove-text-properties 0 (length initial
) '(read-only t
) initial
))
547 (when (stringp annotation
)
548 (remove-text-properties 0 (length annotation
)
549 '(read-only t
) annotation
))
552 (customize-variable 'org-capture-templates
))
556 (org-capture-set-plist entry
)
557 (org-capture-get-template)
558 (org-capture-put :original-buffer orig-buf
559 :original-file
(or (buffer-file-name orig-buf
)
560 (and (featurep 'dired
)
563 :original-file-nondirectory
564 (and (buffer-file-name orig-buf
)
565 (file-name-nondirectory
566 (buffer-file-name orig-buf
)))
567 :annotation annotation
569 (org-capture-put :default-time
570 (or org-overriding-default-time
572 (org-capture-set-target-location)
573 (condition-case error
574 (org-capture-put :template
(org-capture-fill-template))
576 (if (get-buffer "*Capture*") (kill-buffer "*Capture*"))
577 (error "Capture abort: %s" error
)))
579 (setq org-capture-clock-keep
(org-capture-get :clock-keep
))
582 (org-capture-insert-template-here)
583 (condition-case error
584 (org-capture-place-template)
586 (if (and (buffer-base-buffer (current-buffer))
587 (string-match "\\`CAPTURE-" (buffer-name)))
588 (kill-buffer (current-buffer)))
589 (set-window-configuration (org-capture-get :return-to-wconf
))
590 (error "Capture template `%s': %s"
591 (org-capture-get :key
)
593 (if (and (derived-mode-p 'org-mode
)
594 (org-capture-get :clock-in
))
597 (if (org-clock-is-active)
598 (org-capture-put :interrupted-clock
599 (copy-marker org-clock-marker
)))
601 (org-set-local 'org-capture-clock-was-started t
))
603 "Could not start the clock in this capture buffer")))
604 (if (org-capture-get :immediate-finish
)
605 (org-capture-finalize nil
)))))))))
607 (defun org-capture-get-template ()
608 "Get the template from a file or a function if necessary."
609 (let ((txt (org-capture-get :template
)) file
)
611 ((and (listp txt
) (eq (car txt
) 'file
))
613 (setq file
(expand-file-name (nth 1 txt
) org-directory
)))
614 (setq txt
(org-file-contents file
))
615 (setq txt
(format "* Template file %s not found" (nth 1 txt
)))))
616 ((and (listp txt
) (eq (car txt
) 'function
))
617 (if (fboundp (nth 1 txt
))
618 (setq txt
(funcall (nth 1 txt
)))
619 (setq txt
(format "* Template function %s not found" (nth 1 txt
)))))
620 ((not txt
) (setq txt
""))
622 (t (setq txt
"* Invalid capture template")))
623 (org-capture-put :template txt
)))
625 (defun org-capture-finalize (&optional stay-with-capture
)
626 "Finalize the capture process.
627 With prefix argument STAY-WITH-CAPTURE, jump to the location of the
628 captured item after finalizing."
630 (unless (and org-capture-mode
631 (buffer-base-buffer (current-buffer)))
632 (error "This does not seem to be a capture buffer for Org-mode"))
634 (run-hooks 'org-capture-prepare-finalize-hook
)
636 ;; Did we start the clock in this capture buffer?
637 (when (and org-capture-clock-was-started
638 org-clock-marker
(marker-buffer org-clock-marker
)
639 (equal (marker-buffer org-clock-marker
) (buffer-base-buffer))
640 (> org-clock-marker
(point-min))
641 (< org-clock-marker
(point-max)))
642 ;; Looks like the clock we started is still running. Clock out.
643 (when (not org-capture-clock-keep
) (let (org-log-note-clock-out) (org-clock-out)))
644 (when (and (not org-capture-clock-keep
)
645 (org-capture-get :clock-resume
'local
)
646 (markerp (org-capture-get :interrupted-clock
'local
))
647 (buffer-live-p (marker-buffer
648 (org-capture-get :interrupted-clock
'local
))))
649 (let ((clock-in-task (org-capture-get :interrupted-clock
'local
)))
650 (org-with-point-at clock-in-task
652 (message "Interrupted clock has been resumed")))
654 (let ((beg (point-min))
657 ;; Store the size of the capture buffer
658 (org-capture-put :captured-entry-size
(- (point-max) (point-min)))
660 ;; Store the insertion point in the target buffer
661 (org-capture-put :insertion-point
(point))
664 (let ((m1 (org-capture-get :begin-marker
'local
))
665 (m2 (org-capture-get :end-marker
'local
)))
666 (if (and m1 m2
(= m1 beg
) (= m2 end
))
668 (setq m2
(if (cdr (assoc 'heading org-blank-before-new-entry
))
670 m2
(if (< (point-max) m2
) (point-max) m2
))
671 (setq abort-note
'clean
)
673 (setq abort-note
'dirty
)))
675 ;; Make sure that the empty lines after are correct
676 (when (and (> (point-max) end
) ; indeed, the buffer was still narrowed
677 (member (org-capture-get :type
'local
)
678 '(entry item checkitem plain
)))
681 (or (bolp) (newline))
682 (org-capture-empty-lines-after
683 (or (org-capture-get :empty-lines-after
'local
)
684 (org-capture-get :empty-lines
'local
) 0))))
685 ;; Postprocessing: Update Statistics cookies, do the sorting
686 (when (derived-mode-p 'org-mode
)
688 (when (ignore-errors (org-back-to-heading))
689 (org-update-parent-todo-statistics)
690 (org-update-checkbox-count)))
691 ;; FIXME Here we should do the sorting
692 ;; If we have added a table line, maybe recompute?
693 (when (and (eq (org-capture-get :type
'local
) 'table-line
)
695 (if (org-table-get-stored-formulas)
696 (org-table-recalculate 'all
) ;; FIXME: Should we iterate???
698 ;; Store this place as the last one where we stored something
699 ;; Do the marking in the base buffer, so that it makes sense after
700 ;; the indirect buffer has been killed.
701 (when org-capture-bookmark
702 (org-capture-bookmark-last-stored-position))
705 (run-hooks 'org-capture-before-finalize-hook
))
707 (when (org-capture-get :decrypted
)
709 (goto-char (org-capture-get :decrypted
))
710 (org-encrypt-entry)))
712 ;; Kill the indirect buffer
714 (let ((return-wconf (org-capture-get :return-to-wconf
'local
))
715 (new-buffer (org-capture-get :new-buffer
'local
))
716 (kill-buffer (org-capture-get :kill-buffer
'local
))
717 (base-buffer (buffer-base-buffer (current-buffer))))
719 ;; Kill the indirect buffer
720 (kill-buffer (current-buffer))
722 ;; Narrow back the target buffer to its previous state
723 (with-current-buffer (org-capture-get :buffer
)
724 (let ((reg (org-capture-get :initial-target-region
))
725 (pos (org-capture-get :initial-target-position
))
726 (ipt (org-capture-get :insertion-point
))
727 (size (org-capture-get :captured-entry-size
)))
729 (cond ((< ipt
(car reg
))
730 ;; insertion point is before the narrowed region
731 (narrow-to-region (+ size
(car reg
)) (+ size
(cdr reg
))))
733 ;; insertion point is after the narrowed region
734 (narrow-to-region (car reg
) (cdr reg
)))
736 ;; insertion point is within the narrowed region
737 (narrow-to-region (car reg
) (+ size
(cdr reg
)))))
738 ;; now place back the point at its original position
739 (if (< ipt
(car reg
))
740 (goto-char (+ size pos
))
741 (goto-char (if (< ipt pos
) (+ size pos
) pos
))))))
743 ;; Kill the target buffer if that is desired
744 (when (and base-buffer new-buffer kill-buffer
)
745 (with-current-buffer base-buffer
(save-buffer))
746 (kill-buffer base-buffer
))
748 ;; Restore the window configuration before capture
749 (set-window-configuration return-wconf
))
751 (run-hooks 'org-capture-after-finalize-hook
)
756 ((equal abort-note
'clean
)
757 (message "Capture process aborted and target buffer cleaned up"))
758 ((equal abort-note
'dirty
)
759 (error "Capture process aborted, but target buffer could not be cleaned up correctly"))))
761 (org-capture-goto-last-stored)))
762 ;; Return if we did store something
765 (defun org-capture-refile ()
766 "Finalize the current capture and then refile the entry.
767 Refiling is done from the base buffer, because the indirect buffer is then
768 already gone. Any prefix argument will be passed to the refile command."
770 (unless (eq (org-capture-get :type
'local
) 'entry
)
772 "Refiling from a capture buffer makes only sense for `entry'-type templates"))
774 (base (buffer-base-buffer (current-buffer)))
775 (org-refile-for-capture t
))
776 (org-capture-finalize)
777 (save-window-excursion
778 (with-current-buffer (or base
(current-buffer))
783 (call-interactively 'org-refile
)))))))
785 (defun org-capture-kill ()
786 "Abort the current capture process."
788 ;; FIXME: This does not do the right thing, we need to remove the
789 ;; new stuff by hand it is easy: undo, then kill the buffer
790 (let ((org-note-abort t
)
791 (org-capture-before-finalize-hook nil
))
792 (org-capture-finalize)))
794 (defun org-capture-goto-last-stored ()
795 "Go to the location where the last capture note was stored."
797 (org-goto-marker-or-bmk org-capture-last-stored-marker
798 "org-capture-last-stored")
799 (message "This is the last note stored by a capture process"))
801 ;;; Supporting functions for handling the process
803 (defun org-capture-put-target-region-and-position ()
804 "Store the initial region with `org-capture-put'."
806 :initial-target-region
807 ;; Check if the buffer is currently narrowed
808 (when (/= (buffer-size) (- (point-max) (point-min)))
809 (cons (point-min) (point-max))))
810 ;; store the current point
811 (org-capture-put :initial-target-position
(point)))
813 (defvar org-time-was-given
) ; dynamically scoped parameter
814 (defun org-capture-set-target-location (&optional target
)
815 "Find TARGET buffer and position.
816 Store them in the capture property list."
817 (let ((target-entry-p t
) decrypted-hl-pos
)
818 (setq target
(or target
(org-capture-get :target
)))
821 ((eq (car target
) 'file
)
822 (set-buffer (org-capture-target-buffer (nth 1 target
)))
823 (org-capture-put-target-region-and-position)
825 (setq target-entry-p nil
))
827 ((eq (car target
) 'id
)
828 (let ((loc (org-id-find (nth 1 target
))))
830 (error "Cannot find target ID \"%s\"" (nth 1 target
))
831 (set-buffer (org-capture-target-buffer (car loc
)))
833 (org-capture-put-target-region-and-position)
834 (goto-char (cdr loc
)))))
836 ((eq (car target
) 'file
+headline
)
837 (set-buffer (org-capture-target-buffer (nth 1 target
)))
838 (org-capture-put-target-region-and-position)
840 (let ((hd (nth 2 target
)))
841 (goto-char (point-min))
842 (unless (derived-mode-p 'org-mode
)
844 "Target buffer \"%s\" for file+headline should be in Org mode"
846 (if (re-search-forward
847 (format org-complex-heading-regexp-format
(regexp-quote hd
))
849 (goto-char (point-at-bol))
850 (goto-char (point-max))
851 (or (bolp) (insert "\n"))
852 (insert "* " hd
"\n")
853 (beginning-of-line 0))))
855 ((eq (car target
) 'file
+olp
)
856 (let ((m (org-find-olp
857 (cons (org-capture-expand-file (nth 1 target
))
859 (set-buffer (marker-buffer m
))
860 (org-capture-put-target-region-and-position)
864 ((eq (car target
) 'file
+regexp
)
865 (set-buffer (org-capture-target-buffer (nth 1 target
)))
866 (org-capture-put-target-region-and-position)
868 (goto-char (point-min))
869 (if (re-search-forward (nth 2 target
) nil t
)
871 (goto-char (if (org-capture-get :prepend
)
872 (match-beginning 0) (match-end 0)))
873 (org-capture-put :exact-position
(point))
874 (setq target-entry-p
(and (derived-mode-p 'org-mode
) (org-at-heading-p))))
875 (error "No match for target regexp in file %s" (nth 1 target
))))
877 ((memq (car target
) '(file+datetree file
+datetree
+prompt
))
878 (require 'org-datetree
)
879 (set-buffer (org-capture-target-buffer (nth 1 target
)))
880 (org-capture-put-target-region-and-position)
882 ;; Make a date tree entry, with the current date (or yesterday,
883 ;; if we are extending dates for a couple of hours)
884 (org-datetree-find-date-create
885 (calendar-gregorian-from-absolute
887 (org-overriding-default-time
888 ;; use the overriding default time
889 (time-to-days org-overriding-default-time
))
891 ((eq (car target
) 'file
+datetree
+prompt
)
893 (let ((prompt-time (org-read-date
894 nil t nil
"Date for tree entry:"
898 (cond ((and (not org-time-was-given
)
899 (not (= (time-to-days prompt-time
) (org-today))))
900 ;; Use 00:00 when no time is given for another date than today?
901 (apply 'encode-time
(append '(0 0 0) (cdddr (decode-time prompt-time
)))))
902 ((string-match "\\([^ ]+\\)--?[^ ]+[ ]+\\(.*\\)" org-read-date-final-answer
)
903 ;; Replace any time range by its start
905 (org-read-date-analyze
906 (replace-match "\\1 \\2" nil nil org-read-date-final-answer
)
907 prompt-time
(decode-time prompt-time
))))
909 (time-to-days prompt-time
)))
911 ;; current date, possibly corrected for late night workers
914 ((eq (car target
) 'file
+function
)
915 (set-buffer (org-capture-target-buffer (nth 1 target
)))
916 (org-capture-put-target-region-and-position)
918 (funcall (nth 2 target
))
919 (org-capture-put :exact-position
(point))
920 (setq target-entry-p
(and (derived-mode-p 'org-mode
) (org-at-heading-p))))
922 ((eq (car target
) 'function
)
923 (funcall (nth 1 target
))
924 (org-capture-put :exact-position
(point))
925 (setq target-entry-p
(and (derived-mode-p 'org-mode
) (org-at-heading-p))))
927 ((eq (car target
) 'clock
)
928 (if (and (markerp org-clock-hd-marker
)
929 (marker-buffer org-clock-hd-marker
))
930 (progn (set-buffer (marker-buffer org-clock-hd-marker
))
931 (org-capture-put-target-region-and-position)
933 (goto-char org-clock-hd-marker
))
934 (error "No running clock that could be used as capture target")))
936 (t (error "Invalid capture target specification")))
938 (when (and (featurep 'org-crypt
) (org-at-encrypted-entry-p))
940 (setq decrypted-hl-pos
941 (save-excursion (and (org-back-to-heading t
) (point)))))
943 (org-capture-put :buffer
(current-buffer) :pos
(point)
944 :target-entry-p target-entry-p
945 :decrypted decrypted-hl-pos
))))
947 (defun org-capture-expand-file (file)
948 "Expand functions and symbols for FILE.
949 When FILE is a function, call it. When it is a form, evaluate
950 it. When it is a variable, retrieve the value. Return whatever we get."
952 ((org-string-nw-p file
) file
)
953 ((functionp file
) (funcall file
))
954 ((and (symbolp file
) (boundp file
)) (symbol-value file
))
955 ((and file
(consp file
)) (eval file
))
958 (defun org-capture-target-buffer (file)
959 "Get a buffer for FILE."
960 (setq file
(org-capture-expand-file file
))
961 (setq file
(or (org-string-nw-p file
)
962 org-default-notes-file
963 (error "No notes file specified, and no default available")))
964 (or (org-find-base-buffer-visiting file
)
965 (progn (org-capture-put :new-buffer t
)
966 (find-file-noselect (expand-file-name file org-directory
)))))
968 (defun org-capture-steal-local-variables (buffer)
969 "Install Org-mode local variables."
971 (ignore-errors (org-set-local (car v
) (cdr v
))))
972 (buffer-local-variables buffer
)))
974 (defun org-capture-place-template ()
975 "Insert the template at the target location, and display the buffer."
976 (org-capture-put :return-to-wconf
(current-window-configuration))
977 (delete-other-windows)
978 (org-switch-to-buffer-other-window
979 (org-capture-get-indirect-buffer (org-capture-get :buffer
) "CAPTURE"))
982 (goto-char (org-capture-get :pos
))
983 (org-set-local 'org-capture-target-marker
984 (move-marker (make-marker) (point)))
985 (org-set-local 'outline-level
'org-outline-level
)
986 (let* ((template (org-capture-get :template
))
987 (type (org-capture-get :type
)))
989 ((nil entry
) (org-capture-place-entry))
990 (table-line (org-capture-place-table-line))
991 (plain (org-capture-place-plain-text))
992 (item (org-capture-place-item))
993 (checkitem (org-capture-place-item))))
995 (org-set-local 'org-capture-current-plist org-capture-plist
))
997 (defun org-capture-place-entry ()
998 "Place the template as a new Org entry."
999 (let* ((txt (org-capture-get :template
))
1000 (reversed (org-capture-get :prepend
))
1001 (target-entry-p (org-capture-get :target-entry-p
))
1005 ((org-capture-get :exact-position
)
1006 (goto-char (org-capture-get :exact-position
)))
1007 ((not target-entry-p
)
1008 ;; Insert as top-level entry, either at beginning or at end of file
1011 (progn (goto-char (point-min))
1012 (or (org-at-heading-p)
1013 (outline-next-heading)))
1014 (goto-char (point-max))
1015 (or (bolp) (insert "\n"))))
1017 ;; Insert as a child of the current entry
1018 (and (looking-at "\\*+")
1019 (setq level
(- (match-end 0) (match-beginning 0))))
1020 (setq level
(org-get-valid-level (or level
1) 1))
1023 (outline-next-heading)
1024 (or (bolp) (insert "\n")))
1025 (org-end-of-subtree t nil
)
1026 (or (bolp) (insert "\n")))))
1027 (org-capture-empty-lines-before)
1029 (org-capture-verify-tree txt
)
1030 (org-paste-subtree level txt
'for-yank
)
1031 (org-capture-empty-lines-after 1)
1032 (org-capture-position-for-last-stored beg
)
1033 (outline-next-heading)
1035 (org-capture-mark-kill-region beg
(1- end
))
1036 (org-capture-narrow beg
(1- end
))
1037 (if (or (re-search-backward "%\\?" beg t
)
1038 (re-search-forward "%\\?" end t
))
1039 (replace-match ""))))
1041 (defun org-capture-place-item ()
1042 "Place the template as a new plain list item."
1043 (let* ((txt (org-capture-get :template
))
1044 (target-entry-p (org-capture-get :target-entry-p
))
1047 (if (org-capture-get :exact-position
)
1048 (goto-char (org-capture-get :exact-position
))
1050 ((not target-entry-p
)
1051 ;; Insert as top-level entry, either at beginning or at end of file
1052 (setq beg
(point-min) end
(point-max)))
1054 (setq beg
(1+ (point-at-eol))
1055 end
(save-excursion (outline-next-heading) (point)))))
1056 (if (org-capture-get :prepend
)
1059 (if (org-list-search-forward (org-item-beginning-re) end t
)
1061 (goto-char (match-beginning 0))
1062 (setq ind
(org-get-indentation)))
1066 (if (org-list-search-backward (org-item-beginning-re) beg t
)
1068 (setq ind
(org-get-indentation))
1071 ;; Remove common indentation
1072 (setq txt
(org-remove-indentation txt
))
1073 ;; Make sure this is indeed an item
1074 (unless (string-match (concat "\\`" (org-item-re)) txt
)
1075 (setq txt
(concat "- "
1076 (mapconcat 'identity
(split-string txt
"\n")
1078 ;; Set the correct indentation, depending on context
1079 (setq ind
(make-string ind ?\
))
1080 (setq txt
(concat ind
1081 (mapconcat 'identity
(split-string txt
"\n")
1084 ;; Insert, with surrounding empty lines
1085 (org-capture-empty-lines-before)
1088 (or (bolp) (insert "\n"))
1089 (org-capture-empty-lines-after 1)
1090 (org-capture-position-for-last-stored beg
)
1093 (org-capture-mark-kill-region beg
(1- end
))
1094 (org-capture-narrow beg
(1- end
))
1095 (if (or (re-search-backward "%\\?" beg t
)
1096 (re-search-forward "%\\?" end t
))
1097 (replace-match ""))))
1099 (defun org-capture-place-table-line ()
1100 "Place the template as a table line."
1101 (require 'org-table
)
1102 (let* ((txt (org-capture-get :template
))
1103 (target-entry-p (org-capture-get :target-entry-p
))
1104 (table-line-pos (org-capture-get :table-line-pos
))
1107 ((org-capture-get :exact-position
)
1108 (goto-char (org-capture-get :exact-position
)))
1109 ((not target-entry-p
)
1110 ;; Table is not necessarily under a heading
1111 (setq beg
(point-min) end
(point-max)))
1113 ;; WE are at a heading, limit search to the body
1114 (setq beg
(1+ (point-at-eol))
1115 end
(save-excursion (outline-next-heading) (point)))))
1116 (if (re-search-forward org-table-dataline-regexp end t
)
1117 (let ((b (org-table-begin)) (e (org-table-end)) (case-fold-search t
))
1119 (if (looking-at "[ \t]*#\\+tblfm:")
1121 (narrow-to-region b
(point)))
1123 (insert "\n| |\n|----|\n| |\n")
1124 (narrow-to-region (1+ end
) (point)))
1125 ;; We are narrowed to the table, or to an empty line if there was no table
1127 ;; Check if the template is good
1128 (if (not (string-match org-table-dataline-regexp txt
))
1129 (setq txt
"| %?Bad template |\n"))
1131 ((and table-line-pos
1132 (string-match "\\(I+\\)\\([-+][0-9]\\)" table-line-pos
))
1133 ;; we have a complex line specification
1134 (goto-char (point-min))
1135 (let ((nh (- (match-end 1) (match-beginning 1)))
1136 (delta (string-to-number (match-string 2 table-line-pos
)))
1138 ;; The user wants a special position in the table
1139 (org-table-get-specials)
1140 (setq ll
(ignore-errors (aref org-table-hlines nh
)))
1141 (unless ll
(error "Invalid table line specification \"%s\""
1143 (setq ll
(+ ll delta
(if (< delta
0) 0 -
1)))
1145 (org-table-insert-row 'below
)
1146 (beginning-of-line 1)
1147 (delete-region (point) (1+ (point-at-eol)))
1150 (setq end
(point))))
1151 ((org-capture-get :prepend
)
1152 (goto-char (point-min))
1153 (re-search-forward org-table-hline-regexp nil t
)
1154 (beginning-of-line 1)
1155 (re-search-forward org-table-dataline-regexp nil t
)
1156 (beginning-of-line 1)
1158 (org-table-insert-row)
1159 (beginning-of-line 1)
1160 (delete-region (point) (1+ (point-at-eol)))
1164 (goto-char (point-max))
1165 (re-search-backward org-table-dataline-regexp nil t
)
1166 (beginning-of-line 1)
1167 (org-table-insert-row 'below
)
1168 (beginning-of-line 1)
1169 (delete-region (point) (1+ (point-at-eol)))
1172 (setq end
(point))))
1174 (org-capture-position-for-last-stored 'table-line
)
1175 (if (or (re-search-backward "%\\?" beg t
)
1176 (re-search-forward "%\\?" end t
))
1180 (defun org-capture-place-plain-text ()
1181 "Place the template plainly.
1182 If the target locator points at an Org node, place the template into
1183 the text of the entry, before the first child. If not, place the
1184 template at the beginning or end of the file.
1185 Of course, if exact position has been required, just put it there."
1186 (let* ((txt (org-capture-get :template
))
1189 ((org-capture-get :exact-position
)
1190 (goto-char (org-capture-get :exact-position
)))
1191 ((and (org-capture-get :target-entry-p
)
1193 (looking-at org-outline-regexp
))
1194 ;; we should place the text into this entry
1195 (if (org-capture-get :prepend
)
1196 ;; Skip meta data and drawers
1197 (org-end-of-meta-data-and-drawers)
1198 ;; go to ent of the entry text, before the next headline
1199 (outline-next-heading)))
1201 ;; beginning or end of file
1202 (goto-char (if (org-capture-get :prepend
) (point-min) (point-max)))))
1203 (or (bolp) (newline))
1204 (org-capture-empty-lines-before)
1207 (org-capture-empty-lines-after 1)
1208 (org-capture-position-for-last-stored beg
)
1210 (org-capture-mark-kill-region beg
(1- end
))
1211 (org-capture-narrow beg
(1- end
))
1212 (if (or (re-search-backward "%\\?" beg t
)
1213 (re-search-forward "%\\?" end t
))
1214 (replace-match ""))))
1216 (defun org-capture-mark-kill-region (beg end
)
1217 "Mark the region that will have to be killed when aborting capture."
1218 (let ((m1 (move-marker (make-marker) beg
))
1219 (m2 (move-marker (make-marker) end
)))
1220 (org-capture-put :begin-marker m1
)
1221 (org-capture-put :end-marker m2
)))
1223 (defun org-capture-position-for-last-stored (where)
1224 "Memorize the position that should later become the position of last capture."
1227 (org-capture-put :position-for-last-stored
1228 (move-marker (make-marker) where
1229 (or (buffer-base-buffer (current-buffer))
1230 (current-buffer)))))
1231 ((eq where
'table-line
)
1232 (org-capture-put :position-for-last-stored
1234 (org-table-current-dline))))
1235 (t (error "This should not happen"))))
1237 (defun org-capture-bookmark-last-stored-position ()
1238 "Bookmark the last-captured position."
1239 (let* ((where (org-capture-get :position-for-last-stored
'local
))
1242 (prog1 (marker-position where
)
1243 (move-marker where nil
)))
1244 ((and (listp where
) (eq (car where
) 'table-line
))
1245 (if (org-at-table-p)
1247 (org-table-goto-line (nth 1 where
))
1250 (with-current-buffer (buffer-base-buffer (current-buffer))
1255 (with-demoted-errors
1256 (bookmark-set "org-capture-last-stored"))
1257 (move-marker org-capture-last-stored-marker
(point)))))))
1259 (defun org-capture-narrow (beg end
)
1260 "Narrow, unless configuration says not to narrow."
1261 (unless (org-capture-get :unnarrowed
)
1262 (narrow-to-region beg end
)
1265 (defun org-capture-empty-lines-before (&optional n
)
1266 "Arrange for the correct number of empty lines before the insertion point.
1267 Point will be after the empty lines, so insertion can directly be done."
1268 (setq n
(or n
(org-capture-get :empty-lines-before
)
1269 (org-capture-get :empty-lines
) 0))
1270 (let ((pos (point)))
1271 (org-back-over-empty-lines)
1272 (delete-region (point) pos
)
1273 (if (> n
0) (newline n
))))
1275 (defun org-capture-empty-lines-after (&optional n
)
1276 "Arrange for the correct number of empty lines after the inserted string.
1277 Point will remain at the first line after the inserted text."
1278 (setq n
(or n
(org-capture-get :empty-lines-after
)
1279 (org-capture-get :empty-lines
) 0))
1280 (org-back-over-empty-lines)
1281 (while (looking-at "[ \t]*\n") (replace-match ""))
1282 (let ((pos (point)))
1283 (if (> n
0) (newline n
))
1286 (defvar org-clock-marker
) ; Defined in org.el
1288 (defun org-capture-insert-template-here ()
1289 (let* ((template (org-capture-get :template
))
1290 (type (org-capture-get :type
))
1292 (or (bolp) (newline))
1295 ((and (eq type
'entry
) (derived-mode-p 'org-mode
))
1296 (org-capture-verify-tree (org-capture-get :template
))
1297 (org-paste-subtree nil template t
))
1298 ((and (memq type
'(item checkitem
))
1299 (derived-mode-p 'org-mode
)
1300 (save-excursion (skip-chars-backward " \t\n")
1305 (skip-chars-backward " ")
1306 (skip-chars-backward "-+*0123456789).")
1307 (delete-region (point) (point-at-eol))
1309 (org-remove-indentation template
)
1311 (org-capture-empty-lines-after)
1316 (t (insert template
)))
1319 (if (re-search-forward "%\\?" end t
)
1320 (replace-match ""))))
1322 (defun org-capture-set-plist (entry)
1323 "Initialize the property list from the template definition."
1324 (setq org-capture-plist
(copy-sequence (nthcdr 5 entry
)))
1325 (org-capture-put :key
(car entry
) :description
(nth 1 entry
)
1326 :target
(nth 3 entry
))
1327 (let ((txt (nth 4 entry
)) (type (or (nth 2 entry
) 'entry
)))
1328 (when (or (not txt
) (and (stringp txt
) (not (string-match "\\S-" txt
))))
1329 ;; The template may be empty or omitted for special types.
1330 ;; Here we insert the default templates for such cases.
1332 ((eq type
'item
) (setq txt
"- %?"))
1333 ((eq type
'checkitem
) (setq txt
"- [ ] %?"))
1334 ((eq type
'table-line
) (setq txt
"| %? |"))
1335 ((member type
'(nil entry
)) (setq txt
"* %?\n %a"))))
1336 (org-capture-put :template txt
:type type
)))
1338 (defun org-capture-goto-target (&optional template-key
)
1339 "Go to the target location of a capture template.
1340 The user is queried for the template."
1342 (let* (org-select-template-temp-major-mode
1343 (entry (org-capture-select-template template-key
)))
1345 (error "No capture template selected"))
1346 (org-capture-set-plist entry
)
1347 (org-capture-set-target-location)
1348 (org-pop-to-buffer-same-window (org-capture-get :buffer
))
1349 (goto-char (org-capture-get :pos
))))
1351 (defun org-capture-get-indirect-buffer (&optional buffer prefix
)
1352 "Make an indirect buffer for a capture process.
1353 Use PREFIX as a prefix for the name of the indirect buffer."
1354 (setq buffer
(or buffer
(current-buffer)))
1355 (let ((n 1) (base (buffer-name buffer
)) bname
)
1356 (setq bname
(concat prefix
"-" base
))
1357 (while (buffer-live-p (get-buffer bname
))
1358 (setq bname
(concat prefix
"-" (number-to-string (incf n
)) "-" base
)))
1360 (make-indirect-buffer buffer bname
'clone
)
1362 (let ((buf (make-indirect-buffer buffer bname
)))
1363 (with-current-buffer buf
(org-mode))
1366 (defun org-capture-verify-tree (tree)
1367 "Throw error if TREE is not a valid tree."
1368 (unless (org-kill-is-subtree-p tree
)
1369 (error "Template is not a valid Org entry or tree")))
1371 ;;; The template code
1373 (defun org-capture-select-template (&optional keys
)
1374 "Select a capture template.
1375 Lisp programs can force the template by setting KEYS to a string."
1376 (let ((org-capture-templates
1377 (or (org-contextualize-keys
1378 org-capture-templates org-capture-templates-contexts
)
1379 '(("t" "Task" entry
(file+headline
"" "Tasks")
1380 "* TODO %?\n %u\n %a")))))
1382 (or (assoc keys org-capture-templates
)
1383 (error "No capture template referred to by \"%s\" keys" keys
))
1384 (org-mks org-capture-templates
1385 "Select a capture template\n========================="
1387 '(("C" "Customize org-capture-templates")
1390 (defun org-capture-fill-template (&optional template initial annotation
)
1391 "Fill a template and return the filled template as a string.
1392 The template may still contain \"%?\" for cursor positioning."
1393 (setq template
(or template
(org-capture-get :template
)))
1394 (when (stringp initial
)
1395 (setq initial
(org-no-properties initial
)))
1396 (let* ((buffer (org-capture-get :buffer
))
1397 (file (buffer-file-name (or (buffer-base-buffer buffer
) buffer
)))
1398 (ct (org-capture-get :default-time
))
1399 (dct (decode-time ct
))
1401 (if (< (nth 2 dct
) org-extend-today-until
)
1402 (encode-time 0 59 23 (1- (nth 3 dct
)) (nth 4 dct
) (nth 5 dct
))
1404 (plist-p (if org-store-link-plist t nil
))
1405 (v-c (and (> (length kill-ring
) 0) (current-kill 0)))
1406 (v-x (or (org-get-x-clipboard 'PRIMARY
)
1407 (org-get-x-clipboard 'CLIPBOARD
)
1408 (org-get-x-clipboard 'SECONDARY
)))
1409 (v-t (format-time-string (car org-time-stamp-formats
) ct
))
1410 (v-T (format-time-string (cdr org-time-stamp-formats
) ct
))
1411 (v-u (concat "[" (substring v-t
1 -
1) "]"))
1412 (v-U (concat "[" (substring v-T
1 -
1) "]"))
1413 ;; `initial' and `annotation' might habe been passed.
1414 ;; But if the property list has them, we prefer those values
1415 (v-i (or (plist-get org-store-link-plist
:initial
)
1417 (org-capture-get :initial
)
1419 (v-a (or (plist-get org-store-link-plist
:annotation
)
1421 (org-capture-get :annotation
)
1423 ;; Is the link empty? Then we do not want it...
1424 (v-a (if (equal v-a
"[[]]") "" v-a
))
1425 (clipboards (remove nil
(list v-i
1426 (org-get-x-clipboard 'PRIMARY
)
1427 (org-get-x-clipboard 'CLIPBOARD
)
1428 (org-get-x-clipboard 'SECONDARY
)
1430 (l-re "\\[\\[\\(.*?\\)\\]\\(\\[.*?\\]\\)?\\]")
1431 (v-A (if (and v-a
(string-match l-re v-a
))
1432 (replace-match "[[\\1][%^{Link description}]]" nil nil v-a
)
1434 (v-l (if (and v-a
(string-match l-re v-a
))
1435 (replace-match "\\1" nil nil v-a
)
1437 (v-n user-full-name
)
1438 (v-k (if (marker-buffer org-clock-marker
)
1439 (org-no-properties org-clock-heading
)))
1440 (v-K (if (marker-buffer org-clock-marker
)
1441 (org-make-link-string
1442 (buffer-file-name (marker-buffer org-clock-marker
))
1443 org-clock-heading
)))
1444 (v-f (or (org-capture-get :original-file-nondirectory
) ""))
1445 (v-F (or (org-capture-get :original-file
) ""))
1447 (org-startup-folded nil
)
1448 (org-inhibit-startup t
)
1449 org-time-was-given org-end-time-was-given x
1450 prompt completions char time pos default histvar strings
)
1452 (setq org-store-link-plist
1453 (plist-put org-store-link-plist
:annotation v-a
)
1454 org-store-link-plist
1455 (plist-put org-store-link-plist
:initial v-i
))
1458 (unless template
(setq template
"") (message "No template") (ding)
1460 (save-window-excursion
1461 (delete-other-windows)
1462 (org-pop-to-buffer-same-window (get-buffer-create "*Capture*"))
1465 (goto-char (point-min))
1466 (org-capture-steal-local-variables buffer
)
1467 (setq buffer-file-name nil
)
1469 ;; %[] Insert contents of a file.
1470 (goto-char (point-min))
1471 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t
)
1472 (unless (org-capture-escaped-%
)
1473 (let ((start (match-beginning 0))
1475 (filename (expand-file-name (match-string 1))))
1477 (delete-region start end
)
1478 (condition-case error
1479 (insert-file-contents filename
)
1480 (error (insert (format "%%![Couldn't insert %s: %s]"
1481 filename error
)))))))
1482 ;; %() embedded elisp
1483 (org-capture-expand-embedded-elisp)
1486 (goto-char (point-min))
1487 (while (re-search-forward "%<\\([^>\n]+\\)>" nil t
)
1488 (replace-match (format-time-string (match-string 1)) t t
))
1491 (goto-char (point-min))
1492 (while (re-search-forward "%\\([tTuUaliAcxkKInfF]\\)" nil t
)
1493 (unless (org-capture-escaped-%
)
1494 (when (and initial
(equal (match-string 0) "%i"))
1496 (let* ((lead (buffer-substring
1497 (point-at-bol) (match-beginning 0))))
1498 (setq v-i
(mapconcat 'identity
1499 (org-split-string initial
"\n")
1500 (concat "\n" lead
))))))
1502 (or (org-add-props (eval (intern (concat "v-" (match-string 1))))
1503 '(org-protected t
)) "")
1506 ;; From the property list
1508 (goto-char (point-min))
1509 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t
)
1510 (unless (org-capture-escaped-%
)
1511 (and (setq x
(or (plist-get org-store-link-plist
1512 (intern (match-string 1))) ""))
1513 (replace-match x t t
)))))
1515 ;; Turn on org-mode in temp buffer, set local variables
1516 ;; This is to support completion in interactive prompts
1517 (let ((org-inhibit-startup t
)) (org-mode))
1518 ;; Interactive template entries
1519 (goto-char (point-min))
1520 (while (and (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGtTuUCLp]\\)?" nil t
)
1521 (not (get-text-property (1- (point)) 'org-protected
)))
1522 (unless (org-capture-escaped-%
)
1523 (setq char
(if (match-end 3) (match-string-no-properties 3))
1524 prompt
(if (match-end 2) (match-string-no-properties 2)))
1525 (goto-char (match-beginning 0))
1527 (setq completions nil default nil
)
1529 (setq completions
(org-split-string prompt
"|")
1530 prompt
(pop completions
)
1531 default
(car completions
)
1532 histvar
(intern (concat
1533 "org-capture-template-prompt-history::"
1535 completions
(mapcar 'list completions
)))
1536 (unless (boundp histvar
) (set histvar nil
))
1538 ((member char
'("G" "g"))
1539 (let* ((org-last-tags-completion-table
1540 (org-global-tags-completion-table
1541 (if (equal char
"G")
1543 (and file
(list file
)))))
1544 (org-add-colon-after-tag-completion t
)
1545 (ins (org-icompleting-read
1546 (if prompt
(concat prompt
": ") "Tags: ")
1547 'org-tags-completion-function nil nil nil
1548 'org-tags-history
)))
1549 (setq ins
(mapconcat 'identity
1551 ins
(org-re "[^[:alnum:]_@#%]+"))
1553 (when (string-match "\\S-" ins
)
1554 (or (equal (char-before) ?
:) (insert ":"))
1556 (or (equal (char-after) ?
:) (insert ":"))
1557 (and (org-at-heading-p) (org-set-tags nil
'align
)))))
1559 (cond ((= (length clipboards
) 1) (insert (car clipboards
)))
1560 ((> (length clipboards
) 1)
1561 (insert (read-string "Clipboard/kill value: "
1562 (car clipboards
) '(clipboards .
1)
1563 (car clipboards
))))))
1565 (cond ((= (length clipboards
) 1)
1566 (org-insert-link 0 (car clipboards
)))
1567 ((> (length clipboards
) 1)
1568 (org-insert-link 0 (read-string "Clipboard/kill value: "
1571 (car clipboards
))))))
1573 (org-set-property (org-no-properties prompt
) nil
))
1575 ;; These are the date/time related ones
1576 (setq org-time-was-given
(equal (upcase char
) char
))
1577 (setq time
(org-read-date (equal (upcase char
) char
) t nil
1579 (if (equal (upcase char
) char
) (setq org-time-was-given t
))
1580 (org-insert-time-stamp time org-time-was-given
1581 (member char
'("u" "U"))
1582 nil nil
(list org-end-time-was-given
)))
1584 (let (org-completion-use-ido)
1585 (push (org-completing-read-no-i
1586 (concat (if prompt prompt
"Enter string")
1587 (if default
(concat " [" default
"]"))
1589 completions nil nil nil histvar default
)
1591 (insert (car strings
)))))))
1592 ;; Replace %n escapes with nth %^{...} string
1593 (setq strings
(nreverse strings
))
1594 (goto-char (point-min))
1595 (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t
)
1596 (unless (org-capture-escaped-%
)
1598 (nth (1- (string-to-number (match-string 1))) strings
)
1600 ;; Make sure there are no empty lines before the text, and that
1601 ;; it ends with a newline character
1602 (goto-char (point-min))
1603 (while (looking-at "[ \t]*\n") (replace-match ""))
1604 (if (re-search-forward "[ \t\n]*\\'" nil t
) (replace-match "\n"))
1605 ;; Return the expanded template and kill the temporary buffer
1606 (untabify (point-min) (point-max))
1607 (set-buffer-modified-p nil
)
1608 (prog1 (buffer-string) (kill-buffer (current-buffer))))))
1610 (defun org-capture-escaped-%
()
1611 "Check if % was escaped - if yes, unescape it now."
1612 (if (equal (char-before (match-beginning 0)) ?
\\)
1614 (delete-region (1- (match-beginning 0)) (match-beginning 0))
1618 (defun org-capture-expand-embedded-elisp ()
1619 "Evaluate embedded elisp %(sexp) and replace with the result."
1620 (goto-char (point-min))
1621 (while (re-search-forward "%(" nil t
)
1622 (unless (org-capture-escaped-%
)
1623 (goto-char (match-beginning 0))
1624 (let ((template-start (point)))
1626 (let ((result (org-eval
1627 (org-capture--expand-keyword-in-embedded-elisp
1628 (read (current-buffer))))))
1629 (delete-region template-start
(point))
1630 (insert result
))))))
1632 (defun org-capture--expand-keyword-in-embedded-elisp (attr)
1633 "Recursively replace capture link keywords in ATTR sexp.
1634 Such keywords are prefixed with \"%:\". See
1635 `org-capture-template' for more information."
1637 (mapcar 'org-capture--expand-keyword-in-embedded-elisp attr
))
1639 (let* ((attr-symbol (symbol-name attr
))
1640 (key (and (string-match "%\\(:.*\\)" attr-symbol
)
1641 (intern (match-string 1 attr-symbol
)))))
1642 (or (plist-get org-store-link-plist key
)
1646 (defun org-capture-inside-embedded-elisp-p ()
1647 "Return non-nil if point is inside of embedded elisp %(sexp)."
1649 (with-syntax-table emacs-lisp-mode-syntax-table
1651 ;; `looking-at' and `search-backward' below do not match the "%(" if
1652 ;; point is in its middle
1653 (when (equal (char-before) ?%
)
1656 (when (or (looking-at "%(") (search-backward "%(" nil t
))
1658 (setq end
(progn (forward-char) (forward-sexp) (1- (point)))))))
1660 (and (<= (point) end
) (>= (point) beg
))))))
1663 (defun org-capture-import-remember-templates ()
1664 "Set org-capture-templates to be similar to `org-remember-templates'."
1666 (when (and (yes-or-no-p
1667 "Import old remember templates into org-capture-templates? ")
1669 "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
1670 (require 'org-remember
)
1671 (setq org-capture-templates
1674 (let ((desc (car entry
))
1675 (key (char-to-string (nth 1 entry
)))
1676 (template (nth 2 entry
))
1677 (file (or (nth 3 entry
) org-default-notes-file
))
1678 (position (or (nth 4 entry
) org-remember-default-headline
))
1680 (prepend org-reverse-note-order
)
1683 ((member position
'(top bottom
))
1684 (setq target
(list 'file file
)
1685 prepend
(eq position
'top
)))
1686 ((eq position
'date-tree
)
1687 (setq target
(list 'file
+datetree file
)
1689 (t (setq target
(list 'file
+headline file position
))))
1691 (when (string-match "%!" template
)
1692 (setq template
(replace-match "" t t template
)
1695 (append (list key desc type target template
)
1696 (if prepend
'(:prepend t
))
1697 (if immediate
'(:immediate-finish t
)))))
1699 org-remember-templates
))))
1701 (provide 'org-capture
)
1703 ;;; org-capture.el ends here