Revert "org-capture.el (org-capture): Don't store multiple links over lines in the...
[org-mode.git] / lisp / org-capture.el
blob6a014b4b0ab2db19e6c920360529d57a12124ff0
1 ;;; org-capture.el --- Fast note taking in Org-mode
3 ;; Copyright (C) 2010-2013 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;;
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;; Commentary:
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.
39 ;;; TODO
41 ;; - find a clever way to not always insert an annotation maybe a
42 ;; predicate function that can check for conditions for %a to be
43 ;; used. This could be one of the properties.
45 ;; - Should there be plist members that arrange for properties to be
46 ;; asked for, like James proposed in his RFC?
48 ;;; Code:
50 (eval-when-compile
51 (require 'cl))
52 (require 'org)
54 (declare-function org-datetree-find-date-create "org-datetree"
55 (date &optional keep-restriction))
56 (declare-function org-table-get-specials "org-table" ())
57 (declare-function org-table-goto-line "org-table" (N))
58 (declare-function org-pop-to-buffer-same-window "org-compat"
59 (&optional buffer-or-name norecord label))
60 (declare-function org-at-encrypted-entry-p "org-crypt" ())
61 (declare-function org-encrypt-entry "org-crypt" ())
62 (declare-function org-decrypt-entry "org-crypt" ())
64 (defvar org-remember-default-headline)
65 (defvar org-remember-templates)
66 (defvar org-table-hlines)
67 (defvar dired-buffers)
69 (defvar org-capture-clock-was-started nil
70 "Internal flag, noting if the clock was started.")
72 (defvar org-capture-last-stored-marker (make-marker)
73 "Marker pointing to the entry most recently stored with `org-capture'.")
75 ;; The following variable is scoped dynamically by org-protocol
76 ;; to indicate that the link properties have already been stored
77 (defvar org-capture-link-is-already-stored nil)
79 (defgroup org-capture nil
80 "Options concerning capturing new entries."
81 :tag "Org Capture"
82 :group 'org)
84 (defcustom org-capture-templates nil
85 "Templates for the creation of new entries.
87 Each entry is a list with the following items:
89 keys The keys that will select the template, as a string, characters
90 only, for example \"a\" for a template to be selected with a
91 single key, or \"bt\" for selection with two keys. When using
92 several keys, keys using the same prefix key must be together
93 in the list and preceded by a 2-element entry explaining the
94 prefix key, for example
96 (\"b\" \"Templates for marking stuff to buy\")
98 The \"C\" key is used by default for quick access to the
99 customization of the template variable. But if you want to use
100 that key for a template, you can.
102 description A short string describing the template, will be shown during
103 selection.
105 type The type of entry. Valid types are:
106 entry an Org-mode node, with a headline. Will be
107 filed as the child of the target entry or as
108 a top-level entry.
109 item a plain list item, will be placed in the
110 first plain list at the target
111 location.
112 checkitem a checkbox item. This differs from the
113 plain list item only is so far as it uses a
114 different default template.
115 table-line a new line in the first table at target location.
116 plain text to be inserted as it is.
118 target Specification of where the captured item should be placed.
119 In Org-mode files, targets usually define a node. Entries will
120 become children of this node, other types will be added to the
121 table or list in the body of this node.
123 Most target specifications contain a file name. If that file
124 name is the empty string, it defaults to `org-default-notes-file'.
125 A file can also be given as a variable, function, or Emacs Lisp
126 form.
128 Valid values are:
130 (file \"path/to/file\")
131 Text will be placed at the beginning or end of that file
133 (id \"id of existing org entry\")
134 File as child of this entry, or in the body of the entry
136 (file+headline \"path/to/file\" \"node headline\")
137 Fast configuration if the target heading is unique in the file
139 (file+olp \"path/to/file\" \"Level 1 heading\" \"Level 2\" ...)
140 For non-unique headings, the full path is safer
142 (file+regexp \"path/to/file\" \"regexp to find location\")
143 File to the entry matching regexp
145 (file+datetree \"path/to/file\")
146 Will create a heading in a date tree for today's date
148 (file+datetree+prompt \"path/to/file\")
149 Will create a heading in a date tree, prompts for date
151 (file+function \"path/to/file\" function-finding-location)
152 A function to find the right location in the file
154 (clock)
155 File to the entry that is currently being clocked
157 (function function-finding-location)
158 Most general way, write your own function to find both
159 file and location
161 template The template for creating the capture item. If you leave this
162 empty, an appropriate default template will be used. See below
163 for more details. Instead of a string, this may also be one of
165 (file \"/path/to/template-file\")
166 (function function-returning-the-template)
168 in order to get a template from a file, or dynamically
169 from a function.
171 The rest of the entry is a property list of additional options. Recognized
172 properties are:
174 :prepend Normally newly captured information will be appended at
175 the target location (last child, last table line,
176 last list item...). Setting this property will
177 change that.
179 :immediate-finish When set, do not offer to edit the information, just
180 file it away immediately. This makes sense if the
181 template only needs information that can be added
182 automatically.
184 :empty-lines Set this to the number of lines the should be inserted
185 before and after the new item. Default 0, only common
186 other value is 1.
188 :empty-lines-before Set this to the number of lines the should be inserted
189 before the new item. Overrides :empty-lines for the
190 number lines inserted before.
192 :empty-lines-after Set this to the number of lines the should be inserted
193 after the new item. Overrides :empty-lines for the
194 number of lines inserted after.
196 :clock-in Start the clock in this item.
198 :clock-keep Keep the clock running when filing the captured entry.
200 :clock-resume Start the interrupted clock when finishing the capture.
201 Note that :clock-keep has precedence over :clock-resume.
202 When setting both to `t', the current clock will run and
203 the previous one will not be resumed.
205 :unnarrowed Do not narrow the target buffer, simply show the
206 full buffer. Default is to narrow it so that you
207 only see the new stuff.
209 :table-line-pos Specification of the location in the table where the
210 new line should be inserted. It should be a string like
211 \"II-3\", meaning that the new line should become the
212 third line before the second horizontal separator line.
214 :kill-buffer If the target file was not yet visited by a buffer when
215 capture was invoked, kill the buffer again after capture
216 is finalized.
218 The template defines the text to be inserted. Often this is an
219 org-mode entry (so the first line should start with a star) that
220 will be filed as a child of the target headline. It can also be
221 freely formatted text. Furthermore, the following %-escapes will
222 be replaced with content and expanded in this order:
224 %[pathname] Insert the contents of the file given by `pathname'.
225 %(sexp) Evaluate elisp `(sexp)' and replace it with the results.
226 For convenience, %:keyword (see below) placeholders within
227 the expression will be expanded prior to this.
228 %<...> The result of format-time-string on the ... format specification.
229 %t Time stamp, date only.
230 %T Time stamp with date and time.
231 %u, %U Like the above, but inactive time stamps.
232 %i Initial content, copied from the active region. If %i is
233 indented, the entire inserted text will be indented as well.
234 %a Annotation, normally the link created with `org-store-link'.
235 %A Like %a, but prompt for the description part.
236 %l Like %a, but only insert the literal link.
237 %c Current kill ring head.
238 %x Content of the X clipboard.
239 %k Title of currently clocked task.
240 %K Link to currently clocked task.
241 %n User name (taken from the variable `user-full-name').
242 %f File visited by current buffer when org-capture was called.
243 %F Full path of the file or directory visited by current buffer.
244 %:keyword Specific information for certain link types, see below.
245 %^g Prompt for tags, with completion on tags in target file.
246 %^G Prompt for tags, with completion on all tags in all agenda files.
247 %^t Like %t, but prompt for date. Similarly %^T, %^u, %^U.
248 You may define a prompt like: %^{Please specify birthday}t
249 %^C Interactive selection of which kill or clip to use.
250 %^L Like %^C, but insert as link.
251 %^{prop}p Prompt the user for a value for property `prop'.
252 %^{prompt} Prompt the user for a string and replace this sequence with it.
253 A default value and a completion table ca be specified like this:
254 %^{prompt|default|completion2|completion3|...}.
255 %? After completing the template, position cursor here.
256 %\\n Insert the text entered at the nth %^{prompt}, where `n' is
257 a number, starting from 1.
259 Apart from these general escapes, you can access information specific to
260 the link type that is created. For example, calling `org-capture' in emails
261 or in Gnus will record the author and the subject of the message, which you
262 can access with \"%:from\" and \"%:subject\", respectively. Here is a
263 complete list of what is recorded for each link type.
265 Link type | Available information
266 ------------------------+------------------------------------------------------
267 bbdb | %:type %:name %:company
268 vm, wl, mh, mew, rmail, | %:type %:subject %:message-id
269 gnus | %:from %:fromname %:fromaddress
270 | %:to %:toname %:toaddress
271 | %:fromto (either \"to NAME\" or \"from NAME\")
272 | %:date %:date-timestamp (as active timestamp)
273 | %:date-timestamp-inactive (as inactive timestamp)
274 gnus | %:group, for messages also all email fields
275 w3, w3m | %:type %:url
276 info | %:type %:file %:node
277 calendar | %:type %:date"
278 :group 'org-capture
279 :version "24.1"
280 :type
281 '(repeat
282 (choice :value ("" "" entry (file "~/org/notes.org") "")
283 (list :tag "Multikey description"
284 (string :tag "Keys ")
285 (string :tag "Description"))
286 (list :tag "Template entry"
287 (string :tag "Keys ")
288 (string :tag "Description ")
289 (choice :tag "Capture Type " :value entry
290 (const :tag "Org entry" entry)
291 (const :tag "Plain list item" item)
292 (const :tag "Checkbox item" checkitem)
293 (const :tag "Plain text" plain)
294 (const :tag "Table line" table-line))
295 (choice :tag "Target location"
296 (list :tag "File"
297 (const :format "" file)
298 (file :tag " File"))
299 (list :tag "ID"
300 (const :format "" id)
301 (string :tag " ID"))
302 (list :tag "File & Headline"
303 (const :format "" file+headline)
304 (file :tag " File ")
305 (string :tag " Headline"))
306 (list :tag "File & Outline path"
307 (const :format "" file+olp)
308 (file :tag " File ")
309 (repeat :tag "Outline path" :inline t
310 (string :tag "Headline")))
311 (list :tag "File & Regexp"
312 (const :format "" file+regexp)
313 (file :tag " File ")
314 (regexp :tag " Regexp"))
315 (list :tag "File & Date tree"
316 (const :format "" file+datetree)
317 (file :tag " File"))
318 (list :tag "File & Date tree, prompt for date"
319 (const :format "" file+datetree+prompt)
320 (file :tag " File"))
321 (list :tag "File & function"
322 (const :format "" file+function)
323 (file :tag " File ")
324 (sexp :tag " Function"))
325 (list :tag "Current clocking task"
326 (const :format "" clock))
327 (list :tag "Function"
328 (const :format "" function)
329 (sexp :tag " Function")))
330 (choice :tag "Template"
331 (string)
332 (list :tag "File"
333 (const :format "" file)
334 (file :tag "Template file"))
335 (list :tag "Function"
336 (const :format "" function)
337 (function :tag "Template function")))
338 (plist :inline t
339 ;; Give the most common options as checkboxes
340 :options (((const :format "%v " :prepend) (const t))
341 ((const :format "%v " :immediate-finish) (const t))
342 ((const :format "%v " :empty-lines) (const 1))
343 ((const :format "%v " :clock-in) (const t))
344 ((const :format "%v " :clock-keep) (const t))
345 ((const :format "%v " :clock-resume) (const t))
346 ((const :format "%v " :unnarrowed) (const t))
347 ((const :format "%v " :kill-buffer) (const t))))))))
349 (defcustom org-capture-before-finalize-hook nil
350 "Hook that is run right before a capture process is finalized.
351 The capture buffer is still current when this hook runs and it is
352 widened to the entire buffer."
353 :group 'org-capture
354 :version "24.1"
355 :type 'hook)
357 (defcustom org-capture-after-finalize-hook nil
358 "Hook that is run right after a capture process is finalized.
359 Suitable for window cleanup."
360 :group 'org-capture
361 :version "24.1"
362 :type 'hook)
364 (defcustom org-capture-prepare-finalize-hook nil
365 "Hook that is run before the finalization starts.
366 The capture buffer is current and still narrowed."
367 :group 'org-capture
368 :version "24.1"
369 :type 'hook)
371 (defcustom org-capture-bookmark t
372 "When non-nil, add a bookmark pointing at the last stored
373 position when capturing."
374 :group 'org-capture
375 :version "24.3"
376 :type 'boolean)
378 ;;; The property list for keeping information about the capture process
380 (defvar org-capture-plist nil
381 "Plist for the current capture process, global, to avoid having to pass it.")
383 (defvar org-capture-current-plist nil
384 "Local variable holding the plist in a capture buffer.
385 This is used to store the plist for use when finishing a capture process
386 because another such process might have changed the global variable by then.
388 Each time a new capture buffer has been set up, the global `org-capture-plist'
389 is copied to this variable, which is local in the indirect buffer.")
391 (defvar org-capture-clock-keep nil
392 "Local variable to store the value of the :clock-keep parameter.
393 This is needed in case org-capture-finalize is called interactively.")
395 (defun org-capture-put (&rest stuff)
396 "Add properties to the capture property list `org-capture-plist'."
397 (while stuff
398 (setq org-capture-plist (plist-put org-capture-plist
399 (pop stuff) (pop stuff)))))
400 (defun org-capture-get (prop &optional local)
401 "Get properties from the capture property list `org-capture-plist'.
402 When LOCAL is set, use the local variable `org-capture-current-plist',
403 this is necessary after initialization of the capture process,
404 to avoid conflicts with other active capture processes."
405 (plist-get (if local org-capture-current-plist org-capture-plist) prop))
407 (defun org-capture-member (prop &optional local)
408 "Is PROP a property in `org-capture-plist'.
409 When LOCAL is set, use the local variable `org-capture-current-plist',
410 this is necessary after initialization of the capture process,
411 to avoid conflicts with other active capture processes."
412 (plist-get (if local org-capture-current-plist org-capture-plist) prop))
414 ;;; The minor mode
416 (defvar org-capture-mode-map (make-sparse-keymap)
417 "Keymap for `org-capture-mode', a minor mode.
418 Use this map to set additional keybindings for when Org-mode is used
419 for a capture buffer.")
421 (defvar org-capture-mode-hook nil
422 "Hook for the minor `org-capture-mode'.")
424 (define-minor-mode org-capture-mode
425 "Minor mode for special key bindings in a capture buffer.
427 Turning on this mode runs the normal hook `org-capture-mode-hook'."
428 nil " Rem" org-capture-mode-map
429 (org-set-local
430 'header-line-format
431 "Capture buffer. Finish `C-c C-c', refile `C-c C-w', abort `C-c C-k'."))
432 (define-key org-capture-mode-map "\C-c\C-c" 'org-capture-finalize)
433 (define-key org-capture-mode-map "\C-c\C-k" 'org-capture-kill)
434 (define-key org-capture-mode-map "\C-c\C-w" 'org-capture-refile)
436 ;;; The main commands
438 (defvar org-capture-initial nil)
439 (defvar org-capture-entry nil)
441 ;;;###autoload
442 (defun org-capture-string (string &optional keys)
443 "Capture STRING with the template selected by KEYS."
444 (interactive "sInitial text: \n")
445 (let ((org-capture-initial string)
446 (org-capture-entry (org-capture-select-template keys)))
447 (org-capture)))
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,
454 use this:
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 in-buffer: command displayed only in matching buffers
465 not-in-buffer: command not displayed in matching buffers
466 [function]: a custom function taking no argument
468 If you define several checks, the agenda command will be
469 accessible if there is at least one valid check.
471 You can also bind a key to another agenda custom command
472 depending on contextual rules.
474 '((\"c\" \"d\" ((in-mode . \"message-mode\"))))
476 Here it means: in `message-mode buffers', use \"c\" as the
477 key for the capture template otherwise associated with \"d\".
478 \(The template originally associated with \"d\" is not displayed
479 to avoid duplicates.)"
480 :version "24.3"
481 :group 'org-capture
482 :type '(repeat (list :tag "Rule"
483 (string :tag " Capture key")
484 (string :tag "Replace by template")
485 (repeat :tag "Available when"
486 (choice
487 (cons :tag "Condition"
488 (choice
489 (const :tag "In file" in-file)
490 (const :tag "Not in file" not-in-file)
491 (const :tag "In buffer" in-buffer)
492 (const :tag "Not in buffer" not-in-buffer)
493 (const :tag "In mode" in-mode)
494 (const :tag "Not in mode" not-in-mode))
495 (regexp))
496 (function :tag "Custom function"))))))
498 (defcustom org-capture-use-agenda-date nil
499 "Non-nil means use the date at point when capturing from agendas.
500 When nil, you can still capturing using the date at point with \\[org-agenda-capture]]."
501 :group 'org-capture
502 :version "24.3"
503 :type 'boolean)
505 ;;;###autoload
506 (defun org-capture (&optional goto keys)
507 "Capture something.
508 \\<org-capture-mode-map>
509 This will let you select a template from `org-capture-templates', and then
510 file the newly captured information. The text is immediately inserted
511 at the target location, and an indirect buffer is shown where you can
512 edit it. Pressing \\[org-capture-finalize] brings you back to the previous state
513 of Emacs, so that you can continue your work.
515 When called interactively with a \\[universal-argument] prefix argument GOTO, don't capture
516 anything, just go to the file/headline where the selected template
517 stores its notes. With a double prefix argument \
518 \\[universal-argument] \\[universal-argument], go to the last note
519 stored.
521 When called with a `C-0' (zero) prefix, insert a template at point.
523 ELisp programs can set KEYS to a string associated with a template
524 in `org-capture-templates'. In this case, interactive selection
525 will be bypassed.
527 If `org-capture-use-agenda-date' is non-nil, capturing from the
528 agenda will use the date at point as the default date. Then, a
529 `C-1' prefix will tell the capture process to use the HH:MM time
530 of the day at point (if any) or the current HH:MM time."
531 (interactive "P")
532 (when (and org-capture-use-agenda-date
533 (eq major-mode 'org-agenda-mode))
534 (setq org-overriding-default-time
535 (org-get-cursor-date (equal goto 1))))
536 (cond
537 ((equal goto '(4)) (org-capture-goto-target))
538 ((equal goto '(16)) (org-capture-goto-last-stored))
540 ;; FIXME: Are these needed?
541 (let* ((orig-buf (current-buffer))
542 (annotation (if (and (boundp 'org-capture-link-is-already-stored)
543 org-capture-link-is-already-stored)
544 (plist-get org-store-link-plist :annotation)
545 (ignore-errors (org-store-link nil))))
546 (entry (or org-capture-entry (org-capture-select-template keys)))
547 initial)
548 (setq initial (or org-capture-initial
549 (and (org-region-active-p)
550 (buffer-substring (point) (mark)))))
551 (when (stringp initial)
552 (remove-text-properties 0 (length initial) '(read-only t) initial))
553 (when (stringp annotation)
554 (remove-text-properties 0 (length annotation)
555 '(read-only t) annotation))
556 (cond
557 ((equal entry "C")
558 (customize-variable 'org-capture-templates))
559 ((equal entry "q")
560 (error "Abort"))
562 (org-capture-set-plist entry)
563 (org-capture-get-template)
564 (org-capture-put :original-buffer orig-buf
565 :original-file (or (buffer-file-name orig-buf)
566 (and (featurep 'dired)
567 (car (rassq orig-buf
568 dired-buffers))))
569 :original-file-nondirectory
570 (and (buffer-file-name orig-buf)
571 (file-name-nondirectory
572 (buffer-file-name orig-buf)))
573 :annotation annotation
574 :initial initial)
575 (org-capture-put :default-time
576 (or org-overriding-default-time
577 (org-current-time)))
578 (org-capture-set-target-location)
579 (condition-case error
580 (org-capture-put :template (org-capture-fill-template))
581 ((error quit)
582 (if (get-buffer "*Capture*") (kill-buffer "*Capture*"))
583 (error "Capture abort: %s" error)))
585 (setq org-capture-clock-keep (org-capture-get :clock-keep))
586 (if (equal goto 0)
587 ;;insert at point
588 (org-capture-insert-template-here)
589 (condition-case error
590 (org-capture-place-template)
591 ((error quit)
592 (if (and (buffer-base-buffer (current-buffer))
593 (string-match "\\`CAPTURE-" (buffer-name)))
594 (kill-buffer (current-buffer)))
595 (set-window-configuration (org-capture-get :return-to-wconf))
596 (error "Capture template `%s': %s"
597 (org-capture-get :key)
598 (nth 1 error))))
599 (if (and (derived-mode-p 'org-mode)
600 (org-capture-get :clock-in))
601 (condition-case nil
602 (progn
603 (if (org-clock-is-active)
604 (org-capture-put :interrupted-clock
605 (copy-marker org-clock-marker)))
606 (org-clock-in)
607 (org-set-local 'org-capture-clock-was-started t))
608 (error
609 "Could not start the clock in this capture buffer")))
610 (if (org-capture-get :immediate-finish)
611 (org-capture-finalize)))))))))
613 (defun org-capture-get-template ()
614 "Get the template from a file or a function if necessary."
615 (let ((txt (org-capture-get :template)) file)
616 (cond
617 ((and (listp txt) (eq (car txt) 'file))
618 (if (file-exists-p
619 (setq file (expand-file-name (nth 1 txt) org-directory)))
620 (setq txt (org-file-contents file))
621 (setq txt (format "* Template file %s not found" (nth 1 txt)))))
622 ((and (listp txt) (eq (car txt) 'function))
623 (if (fboundp (nth 1 txt))
624 (setq txt (funcall (nth 1 txt)))
625 (setq txt (format "* Template function %s not found" (nth 1 txt)))))
626 ((not txt) (setq txt ""))
627 ((stringp txt))
628 (t (setq txt "* Invalid capture template")))
629 (org-capture-put :template txt)))
631 (defun org-capture-finalize (&optional stay-with-capture)
632 "Finalize the capture process.
633 With prefix argument STAY-WITH-CAPTURE, jump to the location of the
634 captured item after finalizing."
635 (interactive "P")
636 (unless (and org-capture-mode
637 (buffer-base-buffer (current-buffer)))
638 (error "This does not seem to be a capture buffer for Org-mode"))
640 (run-hooks 'org-capture-prepare-finalize-hook)
642 ;; Did we start the clock in this capture buffer?
643 (when (and org-capture-clock-was-started
644 org-clock-marker (marker-buffer org-clock-marker)
645 (equal (marker-buffer org-clock-marker) (buffer-base-buffer))
646 (> org-clock-marker (point-min))
647 (< org-clock-marker (point-max)))
648 ;; Looks like the clock we started is still running. Clock out.
649 (when (not org-capture-clock-keep) (let (org-log-note-clock-out) (org-clock-out)))
650 (when (and (not org-capture-clock-keep)
651 (org-capture-get :clock-resume 'local)
652 (markerp (org-capture-get :interrupted-clock 'local))
653 (buffer-live-p (marker-buffer
654 (org-capture-get :interrupted-clock 'local))))
655 (let ((clock-in-task (org-capture-get :interrupted-clock 'local)))
656 (org-with-point-at clock-in-task
657 (org-clock-in)))
658 (message "Interrupted clock has been resumed")))
660 (let ((beg (point-min))
661 (end (point-max))
662 (abort-note nil))
663 ;; Store the size of the capture buffer
664 (org-capture-put :captured-entry-size (- (point-max) (point-min)))
665 (widen)
666 ;; Store the insertion point in the target buffer
667 (org-capture-put :insertion-point (point))
669 (if org-note-abort
670 (let ((m1 (org-capture-get :begin-marker 'local))
671 (m2 (org-capture-get :end-marker 'local)))
672 (if (and m1 m2 (= m1 beg) (= m2 end))
673 (progn
674 (setq m2 (if (cdr (assoc 'heading org-blank-before-new-entry))
675 m2 (1+ m2))
676 m2 (if (< (point-max) m2) (point-max) m2))
677 (setq abort-note 'clean)
678 (kill-region m1 m2))
679 (setq abort-note 'dirty)))
681 ;; Make sure that the empty lines after are correct
682 (when (and (> (point-max) end) ; indeed, the buffer was still narrowed
683 (member (org-capture-get :type 'local)
684 '(entry item checkitem plain)))
685 (save-excursion
686 (goto-char end)
687 (or (bolp) (newline))
688 (org-capture-empty-lines-after
689 (or (org-capture-get :empty-lines-after 'local)
690 (org-capture-get :empty-lines 'local) 0))))
691 ;; Postprocessing: Update Statistics cookies, do the sorting
692 (when (derived-mode-p 'org-mode)
693 (save-excursion
694 (when (ignore-errors (org-back-to-heading))
695 (org-update-parent-todo-statistics)
696 (org-update-checkbox-count)))
697 ;; FIXME Here we should do the sorting
698 ;; If we have added a table line, maybe recompute?
699 (when (and (eq (org-capture-get :type 'local) 'table-line)
700 (org-at-table-p))
701 (if (org-table-get-stored-formulas)
702 (org-table-recalculate 'all) ;; FIXME: Should we iterate???
703 (org-table-align))))
704 ;; Store this place as the last one where we stored something
705 ;; Do the marking in the base buffer, so that it makes sense after
706 ;; the indirect buffer has been killed.
707 (when org-capture-bookmark
708 (org-capture-bookmark-last-stored-position))
710 ;; Run the hook
711 (run-hooks 'org-capture-before-finalize-hook))
713 (when (org-capture-get :decrypted)
714 (save-excursion
715 (goto-char (org-capture-get :decrypted))
716 (org-encrypt-entry)))
718 ;; Kill the indirect buffer
719 (save-buffer)
720 (let ((return-wconf (org-capture-get :return-to-wconf 'local))
721 (new-buffer (org-capture-get :new-buffer 'local))
722 (kill-buffer (org-capture-get :kill-buffer 'local))
723 (base-buffer (buffer-base-buffer (current-buffer))))
725 ;; Kill the indirect buffer
726 (kill-buffer (current-buffer))
728 ;; Narrow back the target buffer to its previous state
729 (with-current-buffer (org-capture-get :buffer)
730 (let ((reg (org-capture-get :initial-target-region))
731 (pos (org-capture-get :initial-target-position))
732 (ipt (org-capture-get :insertion-point))
733 (size (org-capture-get :captured-entry-size)))
734 (when reg
735 (cond ((< ipt (car reg))
736 ;; insertion point is before the narrowed region
737 (narrow-to-region (+ size (car reg)) (+ size (cdr reg))))
738 ((> ipt (cdr reg))
739 ;; insertion point is after the narrowed region
740 (narrow-to-region (car reg) (cdr reg)))
742 ;; insertion point is within the narrowed region
743 (narrow-to-region (car reg) (+ size (cdr reg)))))
744 ;; now place back the point at its original position
745 (if (< ipt (car reg))
746 (goto-char (+ size pos))
747 (goto-char (if (< ipt pos) (+ size pos) pos))))))
749 ;; Kill the target buffer if that is desired
750 (when (and base-buffer new-buffer kill-buffer)
751 (with-current-buffer base-buffer (save-buffer))
752 (kill-buffer base-buffer))
754 ;; Restore the window configuration before capture
755 (set-window-configuration return-wconf))
757 (run-hooks 'org-capture-after-finalize-hook)
758 ;; Special cases
759 (cond
760 (abort-note
761 (cond
762 ((equal abort-note 'clean)
763 (message "Capture process aborted and target buffer cleaned up"))
764 ((equal abort-note 'dirty)
765 (error "Capture process aborted, but target buffer could not be cleaned up correctly"))))
766 (stay-with-capture
767 (org-capture-goto-last-stored)))
768 ;; Return if we did store something
769 (not abort-note)))
771 (defun org-capture-refile ()
772 "Finalize the current capture and then refile the entry.
773 Refiling is done from the base buffer, because the indirect buffer is then
774 already gone. Any prefix argument will be passed to the refile command."
775 (interactive)
776 (unless (eq (org-capture-get :type 'local) 'entry)
777 (error
778 "Refiling from a capture buffer makes only sense for `entry'-type templates"))
779 (let ((pos (point))
780 (base (buffer-base-buffer (current-buffer)))
781 (org-refile-for-capture t))
782 (org-capture-finalize)
783 (save-window-excursion
784 (with-current-buffer (or base (current-buffer))
785 (save-excursion
786 (save-restriction
787 (widen)
788 (goto-char pos)
789 (call-interactively 'org-refile)))))))
791 (defun org-capture-kill ()
792 "Abort the current capture process."
793 (interactive)
794 ;; FIXME: This does not do the right thing, we need to remove the
795 ;; new stuff by hand it is easy: undo, then kill the buffer
796 (let ((org-note-abort t)
797 (org-capture-before-finalize-hook nil))
798 (org-capture-finalize)))
800 (defun org-capture-goto-last-stored ()
801 "Go to the location where the last capture note was stored."
802 (interactive)
803 (org-goto-marker-or-bmk org-capture-last-stored-marker
804 "org-capture-last-stored")
805 (message "This is the last note stored by a capture process"))
807 ;;; Supporting functions for handling the process
809 (defun org-capture-put-target-region-and-position ()
810 "Store the initial region with `org-capture-put'."
811 (org-capture-put
812 :initial-target-region
813 ;; Check if the buffer is currently narrowed
814 (when (/= (buffer-size) (- (point-max) (point-min)))
815 (cons (point-min) (point-max))))
816 ;; store the current point
817 (org-capture-put :initial-target-position (point)))
819 (defvar org-time-was-given) ; dynamically scoped parameter
820 (defun org-capture-set-target-location (&optional target)
821 "Find TARGET buffer and position.
822 Store them in the capture property list."
823 (let ((target-entry-p t) decrypted-hl-pos)
824 (setq target (or target (org-capture-get :target)))
825 (save-excursion
826 (cond
827 ((eq (car target) 'file)
828 (set-buffer (org-capture-target-buffer (nth 1 target)))
829 (org-capture-put-target-region-and-position)
830 (widen)
831 (setq target-entry-p nil))
833 ((eq (car target) 'id)
834 (let ((loc (org-id-find (nth 1 target))))
835 (if (not loc)
836 (error "Cannot find target ID \"%s\"" (nth 1 target))
837 (set-buffer (org-capture-target-buffer (car loc)))
838 (widen)
839 (org-capture-put-target-region-and-position)
840 (goto-char (cdr loc)))))
842 ((eq (car target) 'file+headline)
843 (set-buffer (org-capture-target-buffer (nth 1 target)))
844 (org-capture-put-target-region-and-position)
845 (widen)
846 (let ((hd (nth 2 target)))
847 (goto-char (point-min))
848 (unless (derived-mode-p 'org-mode)
849 (error
850 "Target buffer \"%s\" for file+headline should be in Org mode"
851 (current-buffer)))
852 (if (re-search-forward
853 (format org-complex-heading-regexp-format (regexp-quote hd))
854 nil t)
855 (goto-char (point-at-bol))
856 (goto-char (point-max))
857 (or (bolp) (insert "\n"))
858 (insert "* " hd "\n")
859 (beginning-of-line 0))))
861 ((eq (car target) 'file+olp)
862 (let ((m (org-find-olp
863 (cons (org-capture-expand-file (nth 1 target))
864 (cddr target)))))
865 (set-buffer (marker-buffer m))
866 (org-capture-put-target-region-and-position)
867 (widen)
868 (goto-char m)))
870 ((eq (car target) 'file+regexp)
871 (set-buffer (org-capture-target-buffer (nth 1 target)))
872 (org-capture-put-target-region-and-position)
873 (widen)
874 (goto-char (point-min))
875 (if (re-search-forward (nth 2 target) nil t)
876 (progn
877 (goto-char (if (org-capture-get :prepend)
878 (match-beginning 0) (match-end 0)))
879 (org-capture-put :exact-position (point))
880 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
881 (error "No match for target regexp in file %s" (nth 1 target))))
883 ((memq (car target) '(file+datetree file+datetree+prompt))
884 (require 'org-datetree)
885 (set-buffer (org-capture-target-buffer (nth 1 target)))
886 (org-capture-put-target-region-and-position)
887 (widen)
888 ;; Make a date tree entry, with the current date (or yesterday,
889 ;; if we are extending dates for a couple of hours)
890 (org-datetree-find-date-create
891 (calendar-gregorian-from-absolute
892 (cond
893 (org-overriding-default-time
894 ;; use the overriding default time
895 (time-to-days org-overriding-default-time))
897 ((eq (car target) 'file+datetree+prompt)
898 ;; prompt for date
899 (let ((prompt-time (org-read-date
900 nil t nil "Date for tree entry:"
901 (current-time))))
902 (org-capture-put
903 :default-time
904 (cond ((and (not org-time-was-given)
905 (not (= (time-to-days prompt-time) (org-today))))
906 ;; Use 00:00 when no time is given for another date than today?
907 (apply 'encode-time (append '(0 0 0) (cdddr (decode-time prompt-time)))))
908 ((string-match "\\([^ ]+\\)--?[^ ]+[ ]+\\(.*\\)" org-read-date-final-answer)
909 ;; Replace any time range by its start
910 (apply 'encode-time
911 (org-read-date-analyze
912 (replace-match "\\1 \\2" nil nil org-read-date-final-answer)
913 prompt-time (decode-time prompt-time))))
914 (t prompt-time)))
915 (time-to-days prompt-time)))
917 ;; current date, possibly corrected for late night workers
918 (org-today))))))
920 ((eq (car target) 'file+function)
921 (set-buffer (org-capture-target-buffer (nth 1 target)))
922 (org-capture-put-target-region-and-position)
923 (widen)
924 (funcall (nth 2 target))
925 (org-capture-put :exact-position (point))
926 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
928 ((eq (car target) 'function)
929 (funcall (nth 1 target))
930 (org-capture-put :exact-position (point))
931 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
933 ((eq (car target) 'clock)
934 (if (and (markerp org-clock-hd-marker)
935 (marker-buffer org-clock-hd-marker))
936 (progn (set-buffer (marker-buffer org-clock-hd-marker))
937 (org-capture-put-target-region-and-position)
938 (widen)
939 (goto-char org-clock-hd-marker))
940 (error "No running clock that could be used as capture target")))
942 (t (error "Invalid capture target specification")))
944 (when (and (featurep 'org-crypt) (org-at-encrypted-entry-p))
945 (org-decrypt-entry)
946 (setq decrypted-hl-pos
947 (save-excursion (and (org-back-to-heading t) (point)))))
949 (org-capture-put :buffer (current-buffer) :pos (point)
950 :target-entry-p target-entry-p
951 :decrypted decrypted-hl-pos))))
953 (defun org-capture-expand-file (file)
954 "Expand functions and symbols for FILE.
955 When FILE is a function, call it. When it is a form, evaluate
956 it. When it is a variable, retrieve the value. Return whatever we get."
957 (cond
958 ((org-string-nw-p file) file)
959 ((functionp file) (funcall file))
960 ((and (symbolp file) (boundp file)) (symbol-value file))
961 ((and file (consp file)) (eval file))
962 (t file)))
964 (defun org-capture-target-buffer (file)
965 "Get a buffer for FILE."
966 (setq file (org-capture-expand-file file))
967 (setq file (or (org-string-nw-p file)
968 org-default-notes-file
969 (error "No notes file specified, and no default available")))
970 (or (org-find-base-buffer-visiting file)
971 (progn (org-capture-put :new-buffer t)
972 (find-file-noselect (expand-file-name file org-directory)))))
974 (defun org-capture-steal-local-variables (buffer)
975 "Install Org-mode local variables of BUFFER."
976 (mapc (lambda (v)
977 (ignore-errors (org-set-local (car v) (cdr v))))
978 (buffer-local-variables buffer)))
980 (defun org-capture-place-template ()
981 "Insert the template at the target location, and display the buffer."
982 (org-capture-put :return-to-wconf (current-window-configuration))
983 (delete-other-windows)
984 (org-switch-to-buffer-other-window
985 (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE"))
986 (widen)
987 (show-all)
988 (goto-char (org-capture-get :pos))
989 (org-set-local 'org-capture-target-marker
990 (point-marker))
991 (org-set-local 'outline-level 'org-outline-level)
992 (let* ((template (org-capture-get :template))
993 (type (org-capture-get :type)))
994 (case type
995 ((nil entry) (org-capture-place-entry))
996 (table-line (org-capture-place-table-line))
997 (plain (org-capture-place-plain-text))
998 (item (org-capture-place-item))
999 (checkitem (org-capture-place-item))))
1000 (org-capture-mode 1)
1001 (org-set-local 'org-capture-current-plist org-capture-plist))
1003 (defun org-capture-place-entry ()
1004 "Place the template as a new Org entry."
1005 (let* ((txt (org-capture-get :template))
1006 (reversed (org-capture-get :prepend))
1007 (target-entry-p (org-capture-get :target-entry-p))
1008 level beg end file)
1010 (cond
1011 ((org-capture-get :exact-position)
1012 (goto-char (org-capture-get :exact-position)))
1013 ((not target-entry-p)
1014 ;; Insert as top-level entry, either at beginning or at end of file
1015 (setq level 1)
1016 (if reversed
1017 (progn (goto-char (point-min))
1018 (or (org-at-heading-p)
1019 (outline-next-heading)))
1020 (goto-char (point-max))
1021 (or (bolp) (insert "\n"))))
1023 ;; Insert as a child of the current entry
1024 (and (looking-at "\\*+")
1025 (setq level (- (match-end 0) (match-beginning 0))))
1026 (setq level (org-get-valid-level (or level 1) 1))
1027 (if reversed
1028 (progn
1029 (outline-next-heading)
1030 (or (bolp) (insert "\n")))
1031 (org-end-of-subtree t nil)
1032 (or (bolp) (insert "\n")))))
1033 (org-capture-empty-lines-before)
1034 (setq beg (point))
1035 (org-capture-verify-tree txt)
1036 (org-paste-subtree level txt 'for-yank)
1037 (org-capture-empty-lines-after 1)
1038 (org-capture-position-for-last-stored beg)
1039 (outline-next-heading)
1040 (setq end (point))
1041 (org-capture-mark-kill-region beg (1- end))
1042 (org-capture-narrow beg (1- end))
1043 (if (or (re-search-backward "%\\?" beg t)
1044 (re-search-forward "%\\?" end t))
1045 (replace-match ""))))
1047 (defun org-capture-place-item ()
1048 "Place the template as a new plain list item."
1049 (let* ((txt (org-capture-get :template))
1050 (target-entry-p (org-capture-get :target-entry-p))
1051 (ind 0)
1052 beg end)
1053 (if (org-capture-get :exact-position)
1054 (goto-char (org-capture-get :exact-position))
1055 (cond
1056 ((not target-entry-p)
1057 ;; Insert as top-level entry, either at beginning or at end of file
1058 (setq beg (point-min) end (point-max)))
1060 (setq beg (1+ (point-at-eol))
1061 end (save-excursion (outline-next-heading) (point)))))
1062 (if (org-capture-get :prepend)
1063 (progn
1064 (goto-char beg)
1065 (if (org-list-search-forward (org-item-beginning-re) end t)
1066 (progn
1067 (goto-char (match-beginning 0))
1068 (setq ind (org-get-indentation)))
1069 (goto-char end)
1070 (setq ind 0)))
1071 (goto-char end)
1072 (if (org-list-search-backward (org-item-beginning-re) beg t)
1073 (progn
1074 (setq ind (org-get-indentation))
1075 (org-end-of-item))
1076 (setq ind 0))))
1077 ;; Remove common indentation
1078 (setq txt (org-remove-indentation txt))
1079 ;; Make sure this is indeed an item
1080 (unless (string-match (concat "\\`" (org-item-re)) txt)
1081 (setq txt (concat "- "
1082 (mapconcat 'identity (split-string txt "\n")
1083 "\n "))))
1084 ;; Set the correct indentation, depending on context
1085 (setq ind (make-string ind ?\ ))
1086 (setq txt (concat ind
1087 (mapconcat 'identity (split-string txt "\n")
1088 (concat "\n" ind))
1089 "\n"))
1090 ;; Insert, with surrounding empty lines
1091 (org-capture-empty-lines-before)
1092 (setq beg (point))
1093 (insert txt)
1094 (or (bolp) (insert "\n"))
1095 (org-capture-empty-lines-after 1)
1096 (org-capture-position-for-last-stored beg)
1097 (forward-char 1)
1098 (setq end (point))
1099 (org-capture-mark-kill-region beg (1- end))
1100 (org-capture-narrow beg (1- end))
1101 (if (or (re-search-backward "%\\?" beg t)
1102 (re-search-forward "%\\?" end t))
1103 (replace-match ""))))
1105 (defun org-capture-place-table-line ()
1106 "Place the template as a table line."
1107 (require 'org-table)
1108 (let* ((txt (org-capture-get :template))
1109 (target-entry-p (org-capture-get :target-entry-p))
1110 (table-line-pos (org-capture-get :table-line-pos))
1111 ind beg end)
1112 (cond
1113 ((org-capture-get :exact-position)
1114 (goto-char (org-capture-get :exact-position)))
1115 ((not target-entry-p)
1116 ;; Table is not necessarily under a heading
1117 (setq beg (point-min) end (point-max)))
1119 ;; WE are at a heading, limit search to the body
1120 (setq beg (1+ (point-at-eol))
1121 end (save-excursion (outline-next-heading) (point)))))
1122 (if (re-search-forward org-table-dataline-regexp end t)
1123 (let ((b (org-table-begin)) (e (org-table-end)) (case-fold-search t))
1124 (goto-char e)
1125 (if (looking-at "[ \t]*#\\+tblfm:")
1126 (forward-line 1))
1127 (narrow-to-region b (point)))
1128 (goto-char end)
1129 (insert "\n| |\n|----|\n| |\n")
1130 (narrow-to-region (1+ end) (point)))
1131 ;; We are narrowed to the table, or to an empty line if there was no table
1133 ;; Check if the template is good
1134 (if (not (string-match org-table-dataline-regexp txt))
1135 (setq txt "| %?Bad template |\n"))
1136 (cond
1137 ((and table-line-pos
1138 (string-match "\\(I+\\)\\([-+][0-9]\\)" table-line-pos))
1139 ;; we have a complex line specification
1140 (goto-char (point-min))
1141 (let ((nh (- (match-end 1) (match-beginning 1)))
1142 (delta (string-to-number (match-string 2 table-line-pos)))
1144 ;; The user wants a special position in the table
1145 (org-table-get-specials)
1146 (setq ll (ignore-errors (aref org-table-hlines nh)))
1147 (unless ll (error "Invalid table line specification \"%s\""
1148 table-line-pos))
1149 (setq ll (+ ll delta (if (< delta 0) 0 -1)))
1150 (org-goto-line ll)
1151 (org-table-insert-row 'below)
1152 (beginning-of-line 1)
1153 (delete-region (point) (1+ (point-at-eol)))
1154 (setq beg (point))
1155 (insert txt)
1156 (setq end (point))))
1157 ((org-capture-get :prepend)
1158 (goto-char (point-min))
1159 (re-search-forward org-table-hline-regexp nil t)
1160 (beginning-of-line 1)
1161 (re-search-forward org-table-dataline-regexp nil t)
1162 (beginning-of-line 1)
1163 (setq beg (point))
1164 (org-table-insert-row)
1165 (beginning-of-line 1)
1166 (delete-region (point) (1+ (point-at-eol)))
1167 (insert txt)
1168 (setq end (point)))
1170 (goto-char (point-max))
1171 (re-search-backward org-table-dataline-regexp nil t)
1172 (beginning-of-line 1)
1173 (org-table-insert-row 'below)
1174 (beginning-of-line 1)
1175 (delete-region (point) (1+ (point-at-eol)))
1176 (setq beg (point))
1177 (insert txt)
1178 (setq end (point))))
1179 (goto-char beg)
1180 (org-capture-position-for-last-stored 'table-line)
1181 (if (or (re-search-backward "%\\?" beg t)
1182 (re-search-forward "%\\?" end t))
1183 (replace-match ""))
1184 (org-table-align)))
1186 (defun org-capture-place-plain-text ()
1187 "Place the template plainly.
1188 If the target locator points at an Org node, place the template into
1189 the text of the entry, before the first child. If not, place the
1190 template at the beginning or end of the file.
1191 Of course, if exact position has been required, just put it there."
1192 (let* ((txt (org-capture-get :template))
1193 beg end)
1194 (cond
1195 ((org-capture-get :exact-position)
1196 (goto-char (org-capture-get :exact-position)))
1197 ((and (org-capture-get :target-entry-p)
1198 (bolp)
1199 (looking-at org-outline-regexp))
1200 ;; we should place the text into this entry
1201 (if (org-capture-get :prepend)
1202 ;; Skip meta data and drawers
1203 (org-end-of-meta-data-and-drawers)
1204 ;; go to ent of the entry text, before the next headline
1205 (outline-next-heading)))
1207 ;; beginning or end of file
1208 (goto-char (if (org-capture-get :prepend) (point-min) (point-max)))))
1209 (or (bolp) (newline))
1210 (org-capture-empty-lines-before)
1211 (setq beg (point))
1212 (insert txt)
1213 (org-capture-empty-lines-after 1)
1214 (org-capture-position-for-last-stored beg)
1215 (setq end (point))
1216 (org-capture-mark-kill-region beg (1- end))
1217 (org-capture-narrow beg (1- end))
1218 (if (or (re-search-backward "%\\?" beg t)
1219 (re-search-forward "%\\?" end t))
1220 (replace-match ""))))
1222 (defun org-capture-mark-kill-region (beg end)
1223 "Mark the region that will have to be killed when aborting capture."
1224 (let ((m1 (move-marker (make-marker) beg))
1225 (m2 (move-marker (make-marker) end)))
1226 (org-capture-put :begin-marker m1)
1227 (org-capture-put :end-marker m2)))
1229 (defun org-capture-position-for-last-stored (where)
1230 "Memorize the position that should later become the position of last capture."
1231 (cond
1232 ((integerp where)
1233 (org-capture-put :position-for-last-stored
1234 (move-marker (make-marker) where
1235 (or (buffer-base-buffer (current-buffer))
1236 (current-buffer)))))
1237 ((eq where 'table-line)
1238 (org-capture-put :position-for-last-stored
1239 (list 'table-line
1240 (org-table-current-dline))))
1241 (t (error "This should not happen"))))
1243 (defun org-capture-bookmark-last-stored-position ()
1244 "Bookmark the last-captured position."
1245 (let* ((where (org-capture-get :position-for-last-stored 'local))
1246 (pos (cond
1247 ((markerp where)
1248 (prog1 (marker-position where)
1249 (move-marker where nil)))
1250 ((and (listp where) (eq (car where) 'table-line))
1251 (if (org-at-table-p)
1252 (save-excursion
1253 (org-table-goto-line (nth 1 where))
1254 (point-at-bol))
1255 (point))))))
1256 (with-current-buffer (buffer-base-buffer (current-buffer))
1257 (save-excursion
1258 (save-restriction
1259 (widen)
1260 (goto-char pos)
1261 (with-demoted-errors
1262 (bookmark-set "org-capture-last-stored"))
1263 (move-marker org-capture-last-stored-marker (point)))))))
1265 (defun org-capture-narrow (beg end)
1266 "Narrow, unless configuration says not to narrow."
1267 (unless (org-capture-get :unnarrowed)
1268 (narrow-to-region beg end)
1269 (goto-char beg)))
1271 (defun org-capture-empty-lines-before (&optional n)
1272 "Set the correct number of empty lines before the insertion point.
1273 Point will be after the empty lines, so insertion can directly be done."
1274 (setq n (or n (org-capture-get :empty-lines-before)
1275 (org-capture-get :empty-lines) 0))
1276 (let ((pos (point)))
1277 (org-back-over-empty-lines)
1278 (delete-region (point) pos)
1279 (if (> n 0) (newline n))))
1281 (defun org-capture-empty-lines-after (&optional n)
1282 "Set the correct number of empty lines after the inserted string.
1283 Point will remain at the first line after the inserted text."
1284 (setq n (or n (org-capture-get :empty-lines-after)
1285 (org-capture-get :empty-lines) 0))
1286 (org-back-over-empty-lines)
1287 (while (looking-at "[ \t]*\n") (replace-match ""))
1288 (let ((pos (point)))
1289 (if (> n 0) (newline n))
1290 (goto-char pos)))
1292 (defvar org-clock-marker) ; Defined in org.el
1294 (defun org-capture-insert-template-here ()
1295 "Insert the capture template at point."
1296 (let* ((template (org-capture-get :template))
1297 (type (org-capture-get :type))
1298 beg end pp)
1299 (or (bolp) (newline))
1300 (setq beg (point))
1301 (cond
1302 ((and (eq type 'entry) (derived-mode-p 'org-mode))
1303 (org-capture-verify-tree (org-capture-get :template))
1304 (org-paste-subtree nil template t))
1305 ((and (memq type '(item checkitem))
1306 (derived-mode-p 'org-mode)
1307 (save-excursion (skip-chars-backward " \t\n")
1308 (setq pp (point))
1309 (org-in-item-p)))
1310 (goto-char pp)
1311 (org-insert-item)
1312 (skip-chars-backward " ")
1313 (skip-chars-backward "-+*0123456789).")
1314 (delete-region (point) (point-at-eol))
1315 (setq beg (point))
1316 (org-remove-indentation template)
1317 (insert template)
1318 (org-capture-empty-lines-after)
1319 (goto-char beg)
1320 (org-list-repair)
1321 (org-end-of-item)
1322 (setq end (point)))
1323 (t (insert template)))
1324 (setq end (point))
1325 (goto-char beg)
1326 (if (re-search-forward "%\\?" end t)
1327 (replace-match ""))))
1329 (defun org-capture-set-plist (entry)
1330 "Initialize the property list from the template definition."
1331 (setq org-capture-plist (copy-sequence (nthcdr 5 entry)))
1332 (org-capture-put :key (car entry) :description (nth 1 entry)
1333 :target (nth 3 entry))
1334 (let ((txt (nth 4 entry)) (type (or (nth 2 entry) 'entry)))
1335 (when (or (not txt) (and (stringp txt) (not (string-match "\\S-" txt))))
1336 ;; The template may be empty or omitted for special types.
1337 ;; Here we insert the default templates for such cases.
1338 (cond
1339 ((eq type 'item) (setq txt "- %?"))
1340 ((eq type 'checkitem) (setq txt "- [ ] %?"))
1341 ((eq type 'table-line) (setq txt "| %? |"))
1342 ((member type '(nil entry)) (setq txt "* %?\n %a"))))
1343 (org-capture-put :template txt :type type)))
1345 (defun org-capture-goto-target (&optional template-key)
1346 "Go to the target location of a capture template.
1347 The user is queried for the template."
1348 (interactive)
1349 (let* (org-select-template-temp-major-mode
1350 (entry (org-capture-select-template template-key)))
1351 (unless entry
1352 (error "No capture template selected"))
1353 (org-capture-set-plist entry)
1354 (org-capture-set-target-location)
1355 (org-pop-to-buffer-same-window (org-capture-get :buffer))
1356 (goto-char (org-capture-get :pos))))
1358 (defun org-capture-get-indirect-buffer (&optional buffer prefix)
1359 "Make an indirect buffer for a capture process.
1360 Use PREFIX as a prefix for the name of the indirect buffer."
1361 (setq buffer (or buffer (current-buffer)))
1362 (let ((n 1) (base (buffer-name buffer)) bname)
1363 (setq bname (concat prefix "-" base))
1364 (while (buffer-live-p (get-buffer bname))
1365 (setq bname (concat prefix "-" (number-to-string (incf n)) "-" base)))
1366 (condition-case nil
1367 (make-indirect-buffer buffer bname 'clone)
1368 (error
1369 (let ((buf (make-indirect-buffer buffer bname)))
1370 (with-current-buffer buf (org-mode))
1371 buf)))))
1373 (defun org-capture-verify-tree (tree)
1374 "Throw error if TREE is not a valid tree."
1375 (unless (org-kill-is-subtree-p tree)
1376 (error "Template is not a valid Org entry or tree")))
1378 (defun org-mks (table title &optional prompt specials)
1379 "Select a member of an alist with multiple keys.
1380 TABLE is the alist which should contain entries where the car is a string.
1381 There should be two types of entries.
1383 1. prefix descriptions like (\"a\" \"Description\")
1384 This indicates that `a' is a prefix key for multi-letter selection, and
1385 that there are entries following with keys like \"ab\", \"ax\"...
1387 2. Selectable members must have more than two elements, with the first
1388 being the string of keys that lead to selecting it, and the second a
1389 short description string of the item.
1391 The command will then make a temporary buffer listing all entries
1392 that can be selected with a single key, and all the single key
1393 prefixes. When you press the key for a single-letter entry, it is selected.
1394 When you press a prefix key, the commands (and maybe further prefixes)
1395 under this key will be shown and offered for selection.
1397 TITLE will be placed over the selection in the temporary buffer,
1398 PROMPT will be used when prompting for a key. SPECIAL is an alist with
1399 also (\"key\" \"description\") entries. When one of these is selection,
1400 only the bare key is returned."
1401 (setq prompt (or prompt "Select: "))
1402 (let (tbl orig-table dkey ddesc des-keys allowed-keys
1403 current prefix rtn re pressed buffer (inhibit-quit t))
1404 (save-window-excursion
1405 (setq buffer (org-switch-to-buffer-other-window "*Org Select*"))
1406 (setq orig-table table)
1407 (catch 'exit
1408 (while t
1409 (erase-buffer)
1410 (insert title "\n\n")
1411 (setq tbl table
1412 des-keys nil
1413 allowed-keys nil)
1414 (setq prefix (if current (concat current " ") ""))
1415 (while tbl
1416 (cond
1417 ((and (= 2 (length (car tbl))) (= (length (caar tbl)) 1))
1418 ;; This is a description on this level
1419 (setq dkey (caar tbl) ddesc (cadar tbl))
1420 (pop tbl)
1421 (push dkey des-keys)
1422 (push dkey allowed-keys)
1423 (insert prefix "[" dkey "]" "..." " " ddesc "..." "\n")
1424 ;; Skip keys which are below this prefix
1425 (setq re (concat "\\`" (regexp-quote dkey)))
1426 (while (and tbl (string-match re (caar tbl))) (pop tbl)))
1427 ((= 2 (length (car tbl)))
1428 ;; Not yet a usable description, skip it
1431 ;; usable entry on this level
1432 (insert prefix "[" (caar tbl) "]" " " (nth 1 (car tbl)) "\n")
1433 (push (caar tbl) allowed-keys)
1434 (pop tbl))))
1435 (when specials
1436 (insert "-------------------------------------------------------------------------------\n")
1437 (let ((sp specials))
1438 (while sp
1439 (insert (format "[%s] %s\n"
1440 (caar sp) (nth 1 (car sp))))
1441 (push (caar sp) allowed-keys)
1442 (pop sp))))
1443 (push "\C-g" allowed-keys)
1444 (goto-char (point-min))
1445 (if (not (pos-visible-in-window-p (point-max)))
1446 (org-fit-window-to-buffer))
1447 (message prompt)
1448 (setq pressed (char-to-string (read-char-exclusive)))
1449 (while (not (member pressed allowed-keys))
1450 (message "Invalid key `%s'" pressed) (sit-for 1)
1451 (message prompt)
1452 (setq pressed (char-to-string (read-char-exclusive))))
1453 (when (equal pressed "\C-g")
1454 (kill-buffer buffer)
1455 (error "Abort"))
1456 (when (and (not (assoc pressed table))
1457 (not (member pressed des-keys))
1458 (assoc pressed specials))
1459 (throw 'exit (setq rtn pressed)))
1460 (unless (member pressed des-keys)
1461 (throw 'exit (setq rtn (rassoc (cdr (assoc pressed table))
1462 orig-table))))
1463 (setq current (concat current pressed))
1464 (setq table (mapcar
1465 (lambda (x)
1466 (if (and (> (length (car x)) 1)
1467 (equal (substring (car x) 0 1) pressed))
1468 (cons (substring (car x) 1) (cdr x))
1469 nil))
1470 table))
1471 (setq table (remove nil table)))))
1472 (when buffer (kill-buffer buffer))
1473 rtn))
1475 ;;; The template code
1476 (defun org-capture-select-template (&optional keys)
1477 "Select a capture template.
1478 Lisp programs can force the template by setting KEYS to a string."
1479 (let ((org-capture-templates
1480 (or (org-contextualize-keys
1481 org-capture-templates org-capture-templates-contexts)
1482 '(("t" "Task" entry (file+headline "" "Tasks")
1483 "* TODO %?\n %u\n %a")))))
1484 (if keys
1485 (or (assoc keys org-capture-templates)
1486 (error "No capture template referred to by \"%s\" keys" keys))
1487 (org-mks org-capture-templates
1488 "Select a capture template\n========================="
1489 "Template key: "
1490 '(("C" "Customize org-capture-templates")
1491 ("q" "Abort"))))))
1493 (defun org-capture-fill-template (&optional template initial annotation)
1494 "Fill a template and return the filled template as a string.
1495 The template may still contain \"%?\" for cursor positioning."
1496 (setq template (or template (org-capture-get :template)))
1497 (when (stringp initial)
1498 (setq initial (org-no-properties initial)))
1499 (let* ((buffer (org-capture-get :buffer))
1500 (file (buffer-file-name (or (buffer-base-buffer buffer) buffer)))
1501 (ct (org-capture-get :default-time))
1502 (dct (decode-time ct))
1503 (ct1
1504 (if (< (nth 2 dct) org-extend-today-until)
1505 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
1506 ct))
1507 (plist-p (if org-store-link-plist t nil))
1508 (v-c (and (> (length kill-ring) 0) (current-kill 0)))
1509 (v-x (or (org-get-x-clipboard 'PRIMARY)
1510 (org-get-x-clipboard 'CLIPBOARD)
1511 (org-get-x-clipboard 'SECONDARY)))
1512 (v-t (format-time-string (car org-time-stamp-formats) ct))
1513 (v-T (format-time-string (cdr org-time-stamp-formats) ct))
1514 (v-u (concat "[" (substring v-t 1 -1) "]"))
1515 (v-U (concat "[" (substring v-T 1 -1) "]"))
1516 ;; `initial' and `annotation' might habe been passed.
1517 ;; But if the property list has them, we prefer those values
1518 (v-i (or (plist-get org-store-link-plist :initial)
1519 initial
1520 (org-capture-get :initial)
1521 ""))
1522 (v-a (or (plist-get org-store-link-plist :annotation)
1523 annotation
1524 (org-capture-get :annotation)
1525 ""))
1526 ;; Is the link empty? Then we do not want it...
1527 (v-a (if (equal v-a "[[]]") "" v-a))
1528 (clipboards (remove nil (list v-i
1529 (org-get-x-clipboard 'PRIMARY)
1530 (org-get-x-clipboard 'CLIPBOARD)
1531 (org-get-x-clipboard 'SECONDARY)
1532 v-c)))
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)
1536 v-a))
1537 (v-l (if (and v-a (string-match l-re v-a))
1538 (replace-match "\\1" nil nil v-a)
1539 v-a))
1540 (v-n user-full-name)
1541 (v-k (if (marker-buffer org-clock-marker)
1542 (org-no-properties org-clock-heading)))
1543 (v-K (if (marker-buffer org-clock-marker)
1544 (org-make-link-string
1545 (buffer-file-name (marker-buffer org-clock-marker))
1546 org-clock-heading)))
1547 (v-f (or (org-capture-get :original-file-nondirectory) ""))
1548 (v-F (or (org-capture-get :original-file) ""))
1550 (org-startup-folded nil)
1551 (org-inhibit-startup t)
1552 org-time-was-given org-end-time-was-given x
1553 prompt completions char time pos default histvar strings)
1555 (setq org-store-link-plist
1556 (plist-put org-store-link-plist :annotation v-a)
1557 org-store-link-plist
1558 (plist-put org-store-link-plist :initial v-i))
1559 (setq initial v-i)
1561 (unless template (setq template "") (message "No template") (ding)
1562 (sit-for 1))
1563 (save-window-excursion
1564 (delete-other-windows)
1565 (org-pop-to-buffer-same-window (get-buffer-create "*Capture*"))
1566 (erase-buffer)
1567 (insert template)
1568 (goto-char (point-min))
1569 (org-capture-steal-local-variables buffer)
1570 (setq buffer-file-name nil)
1572 ;; %[] Insert contents of a file.
1573 (goto-char (point-min))
1574 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
1575 (unless (org-capture-escaped-%)
1576 (let ((start (match-beginning 0))
1577 (end (match-end 0))
1578 (filename (expand-file-name (match-string 1))))
1579 (goto-char start)
1580 (delete-region start end)
1581 (condition-case error
1582 (insert-file-contents filename)
1583 (error (insert (format "%%![Couldn't insert %s: %s]"
1584 filename error)))))))
1585 ;; %() embedded elisp
1586 (org-capture-expand-embedded-elisp)
1588 ;; The current time
1589 (goto-char (point-min))
1590 (while (re-search-forward "%<\\([^>\n]+\\)>" nil t)
1591 (replace-match (format-time-string (match-string 1)) t t))
1593 ;; Simple %-escapes
1594 (goto-char (point-min))
1595 (while (re-search-forward "%\\([tTuUaliAcxkKInfF]\\)" nil t)
1596 (unless (org-capture-escaped-%)
1597 (when (and initial (equal (match-string 0) "%i"))
1598 (save-match-data
1599 (let* ((lead (buffer-substring
1600 (point-at-bol) (match-beginning 0))))
1601 (setq v-i (mapconcat 'identity
1602 (org-split-string initial "\n")
1603 (concat "\n" lead))))))
1604 (replace-match (or (eval (intern (concat "v-" (match-string 1)))) "")
1605 t t)))
1607 ;; From the property list
1608 (when plist-p
1609 (goto-char (point-min))
1610 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
1611 (unless (org-capture-escaped-%)
1612 (and (setq x (or (plist-get org-store-link-plist
1613 (intern (match-string 1))) ""))
1614 (replace-match x t t)))))
1616 ;; Turn on org-mode in temp buffer, set local variables
1617 ;; This is to support completion in interactive prompts
1618 (let ((org-inhibit-startup t)) (org-mode))
1619 ;; Interactive template entries
1620 (goto-char (point-min))
1621 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGtTuUCLp]\\)?" nil t)
1622 (unless (org-capture-escaped-%)
1623 (setq char (if (match-end 3) (match-string-no-properties 3))
1624 prompt (if (match-end 2) (match-string-no-properties 2)))
1625 (goto-char (match-beginning 0))
1626 (replace-match "")
1627 (setq completions nil default nil)
1628 (when prompt
1629 (setq completions (org-split-string prompt "|")
1630 prompt (pop completions)
1631 default (car completions)
1632 histvar (intern (concat
1633 "org-capture-template-prompt-history::"
1634 (or prompt "")))
1635 completions (mapcar 'list completions)))
1636 (unless (boundp histvar) (set histvar nil))
1637 (cond
1638 ((member char '("G" "g"))
1639 (let* ((org-last-tags-completion-table
1640 (org-global-tags-completion-table
1641 (if (equal char "G")
1642 (org-agenda-files)
1643 (and file (list file)))))
1644 (org-add-colon-after-tag-completion t)
1645 (ins (org-icompleting-read
1646 (if prompt (concat prompt ": ") "Tags: ")
1647 'org-tags-completion-function nil nil nil
1648 'org-tags-history)))
1649 (setq ins (mapconcat 'identity
1650 (org-split-string
1651 ins (org-re "[^[:alnum:]_@#%]+"))
1652 ":"))
1653 (when (string-match "\\S-" ins)
1654 (or (equal (char-before) ?:) (insert ":"))
1655 (insert ins)
1656 (or (equal (char-after) ?:) (insert ":"))
1657 (and (org-at-heading-p) (org-set-tags nil 'align)))))
1658 ((equal char "C")
1659 (cond ((= (length clipboards) 1) (insert (car clipboards)))
1660 ((> (length clipboards) 1)
1661 (insert (read-string "Clipboard/kill value: "
1662 (car clipboards) '(clipboards . 1)
1663 (car clipboards))))))
1664 ((equal char "L")
1665 (cond ((= (length clipboards) 1)
1666 (org-insert-link 0 (car clipboards)))
1667 ((> (length clipboards) 1)
1668 (org-insert-link 0 (read-string "Clipboard/kill value: "
1669 (car clipboards)
1670 '(clipboards . 1)
1671 (car clipboards))))))
1672 ((equal char "p")
1673 (org-set-property (org-no-properties prompt) nil))
1674 (char
1675 ;; These are the date/time related ones
1676 (setq org-time-was-given (equal (upcase char) char))
1677 (setq time (org-read-date (equal (upcase char) char) t nil
1678 prompt))
1679 (if (equal (upcase char) char) (setq org-time-was-given t))
1680 (org-insert-time-stamp time org-time-was-given
1681 (member char '("u" "U"))
1682 nil nil (list org-end-time-was-given)))
1684 (let (org-completion-use-ido)
1685 (push (org-completing-read-no-i
1686 (concat (if prompt prompt "Enter string")
1687 (if default (concat " [" default "]"))
1688 ": ")
1689 completions nil nil nil histvar default)
1690 strings)
1691 (insert (car strings)))))))
1692 ;; Replace %n escapes with nth %^{...} string
1693 (setq strings (nreverse strings))
1694 (goto-char (point-min))
1695 (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t)
1696 (unless (org-capture-escaped-%)
1697 (replace-match
1698 (nth (1- (string-to-number (match-string 1))) strings)
1699 nil t)))
1700 ;; Make sure there are no empty lines before the text, and that
1701 ;; it ends with a newline character
1702 (goto-char (point-min))
1703 (while (looking-at "[ \t]*\n") (replace-match ""))
1704 (if (re-search-forward "[ \t\n]*\\'" nil t) (replace-match "\n"))
1705 ;; Return the expanded template and kill the temporary buffer
1706 (untabify (point-min) (point-max))
1707 (set-buffer-modified-p nil)
1708 (prog1 (buffer-string) (kill-buffer (current-buffer))))))
1710 (defun org-capture-escaped-% ()
1711 "Check if % was escaped - if yes, unescape it now."
1712 (if (equal (char-before (match-beginning 0)) ?\\)
1713 (progn
1714 (delete-region (1- (match-beginning 0)) (match-beginning 0))
1716 nil))
1718 (defun org-capture-expand-embedded-elisp ()
1719 "Evaluate embedded elisp %(sexp) and replace with the result."
1720 (goto-char (point-min))
1721 (while (re-search-forward "%(" nil t)
1722 (unless (org-capture-escaped-%)
1723 (goto-char (match-beginning 0))
1724 (let ((template-start (point)))
1725 (forward-char 1)
1726 (let ((result (org-eval
1727 (org-capture--expand-keyword-in-embedded-elisp
1728 (read (current-buffer))))))
1729 (delete-region template-start (point))
1730 (insert result))))))
1732 (defun org-capture--expand-keyword-in-embedded-elisp (attr)
1733 "Recursively replace capture link keywords in ATTR sexp.
1734 Such keywords are prefixed with \"%:\". See
1735 `org-capture-template' for more information."
1736 (cond ((consp attr)
1737 (mapcar 'org-capture--expand-keyword-in-embedded-elisp attr))
1738 ((symbolp attr)
1739 (let* ((attr-symbol (symbol-name attr))
1740 (key (and (string-match "%\\(:.*\\)" attr-symbol)
1741 (intern (match-string 1 attr-symbol)))))
1742 (or (plist-get org-store-link-plist key)
1743 attr)))
1744 (t attr)))
1746 (defun org-capture-inside-embedded-elisp-p ()
1747 "Return non-nil if point is inside of embedded elisp %(sexp)."
1748 (let (beg end)
1749 (with-syntax-table emacs-lisp-mode-syntax-table
1750 (save-excursion
1751 ;; `looking-at' and `search-backward' below do not match the "%(" if
1752 ;; point is in its middle
1753 (when (equal (char-before) ?%)
1754 (backward-char))
1755 (save-match-data
1756 (when (or (looking-at "%(") (search-backward "%(" nil t))
1757 (setq beg (point))
1758 (setq end (progn (forward-char) (forward-sexp) (1- (point)))))))
1759 (when (and beg end)
1760 (and (<= (point) end) (>= (point) beg))))))
1762 ;;;###autoload
1763 (defun org-capture-import-remember-templates ()
1764 "Set `org-capture-templates' to be similar to `org-remember-templates'."
1765 (interactive)
1766 (when (and (yes-or-no-p
1767 "Import old remember templates into org-capture-templates? ")
1768 (yes-or-no-p
1769 "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
1770 (require 'org-remember)
1771 (setq org-capture-templates
1772 (mapcar
1773 (lambda (entry)
1774 (let ((desc (car entry))
1775 (key (char-to-string (nth 1 entry)))
1776 (template (nth 2 entry))
1777 (file (or (nth 3 entry) org-default-notes-file))
1778 (position (or (nth 4 entry) org-remember-default-headline))
1779 (type 'entry)
1780 (prepend org-reverse-note-order)
1781 immediate target)
1782 (cond
1783 ((member position '(top bottom))
1784 (setq target (list 'file file)
1785 prepend (eq position 'top)))
1786 ((eq position 'date-tree)
1787 (setq target (list 'file+datetree file)
1788 prepend nil))
1789 (t (setq target (list 'file+headline file position))))
1791 (when (string-match "%!" template)
1792 (setq template (replace-match "" t t template)
1793 immediate t))
1795 (append (list key desc type target template)
1796 (if prepend '(:prepend t))
1797 (if immediate '(:immediate-finish t)))))
1799 org-remember-templates))))
1801 (provide 'org-capture)
1803 ;;; org-capture.el ends here