org-capture.el: Minor code cleanup
[org-mode.git] / lisp / org-capture.el
blob7d5945a19d8bdce51757d7cdae16fe64db341d08
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
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)
53 (require 'org-mks)
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))
62 (defvar org-remember-default-headline)
63 (defvar org-remember-templates)
64 (defvar org-table-hlines)
65 (defvar dired-buffers)
67 (defvar org-capture-clock-was-started nil
68 "Internal flag, noting if the clock was started.")
70 (defvar org-capture-last-stored-marker (make-marker)
71 "Marker pointing to the entry most recently stored with `org-capture'.")
73 ;; The following variable is scoped dynamically by org-protocol
74 ;; to indicate that the link properties have already been stored
75 (defvar org-capture-link-is-already-stored nil)
77 (defgroup org-capture nil
78 "Options concerning capturing new entries."
79 :tag "Org Capture"
80 :group 'org)
82 (defcustom org-capture-templates nil
83 "Templates for the creation of new entries.
85 Each entry is a list with the following items:
87 keys The keys that will select the template, as a string, characters
88 only, for example \"a\" for a template to be selected with a
89 single key, or \"bt\" for selection with two keys. When using
90 several keys, keys using the same prefix key must be together
91 in the list and preceded by a 2-element entry explaining the
92 prefix key, for example
94 (\"b\" \"Templates for marking stuff to buy\")
96 The \"C\" key is used by default for quick access to the
97 customization of the template variable. But if you want to use
98 that key for a template, you can.
100 description A short string describing the template, will be shown during
101 selection.
103 type The type of entry. Valid types are:
104 entry an Org-mode node, with a headline. Will be
105 filed as the child of the target entry or as
106 a top-level entry.
107 item a plain list item, will be placed in the
108 first plain list at the target
109 location.
110 checkitem a checkbox item. This differs from the
111 plain list item only is so far as it uses a
112 different default template.
113 table-line a new line in the first table at target location.
114 plain text to be inserted as it is.
116 target Specification of where the captured item should be placed.
117 In Org-mode files, targets usually define a node. Entries will
118 become children of this node, other types will be added to the
119 table or list in the body of this node.
121 Most target specifications contain a file name. If that file
122 name is the empty string, it defaults to `org-default-notes-file'.
123 A file can also be given as a variable, function, or Emacs Lisp
124 form.
126 Valid values are:
128 (file \"path/to/file\")
129 Text will be placed at the beginning or end of that file
131 (id \"id of existing org entry\")
132 File as child of this entry, or in the body of the entry
134 (file+headline \"path/to/file\" \"node headline\")
135 Fast configuration if the target heading is unique in the file
137 (file+olp \"path/to/file\" \"Level 1 heading\" \"Level 2\" ...)
138 For non-unique headings, the full path is safer
140 (file+regexp \"path/to/file\" \"regexp to find location\")
141 File to the entry matching regexp
143 (file+datetree \"path/to/file\")
144 Will create a heading in a date tree for today's date
146 (file+datetree+prompt \"path/to/file\")
147 Will create a heading in a date tree, prompts for date
149 (file+function \"path/to/file\" function-finding-location)
150 A function to find the right location in the file
152 (clock)
153 File to the entry that is currently being clocked
155 (function function-finding-location)
156 Most general way, write your own function to find both
157 file and location
159 template The template for creating the capture item. If you leave this
160 empty, an appropriate default template will be used. See below
161 for more details. Instead of a string, this may also be one of
163 (file \"/path/to/template-file\")
164 (function function-returning-the-template)
166 in order to get a template from a file, or dynamically
167 from a function.
169 The rest of the entry is a property list of additional options. Recognized
170 properties are:
172 :prepend Normally newly captured information will be appended at
173 the target location (last child, last table line,
174 last list item...). Setting this property will
175 change that.
177 :immediate-finish When set, do not offer to edit the information, just
178 file it away immediately. This makes sense if the
179 template only needs information that can be added
180 automatically.
182 :empty-lines Set this to the number of lines the should be inserted
183 before and after the new item. Default 0, only common
184 other value is 1.
186 :empty-lines-before Set this to the number of lines the should be inserted
187 before the new item. Overrides :empty-lines for the
188 number lines inserted before.
190 :empty-lines-after Set this to the number of lines the should be inserted
191 after the new item. Overrides :empty-lines for the
192 number of lines inserted after.
194 :clock-in Start the clock in this item.
196 :clock-keep Keep the clock running when filing the captured entry.
198 :clock-resume Start the interrupted clock when finishing the capture.
199 Note that :clock-keep has precedence over :clock-resume.
200 When setting both to `t', the current clock will run and
201 the previous one will not be resumed.
203 :unnarrowed Do not narrow the target buffer, simply show the
204 full buffer. Default is to narrow it so that you
205 only see the new stuff.
207 :table-line-pos Specification of the location in the table where the
208 new line should be inserted. It should be a string like
209 \"II-3\", meaning that the new line should become the
210 third line before the second horizontal separator line.
212 :kill-buffer If the target file was not yet visited by a buffer when
213 capture was invoked, kill the buffer again after capture
214 is finalized.
216 The template defines the text to be inserted. Often this is an
217 org-mode entry (so the first line should start with a star) that
218 will be filed as a child of the target headline. It can also be
219 freely formatted text. Furthermore, the following %-escapes will
220 be replaced with content and expanded in this order:
222 %[pathname] Insert the contents of the file given by `pathname'.
223 %(sexp) Evaluate elisp `(sexp)' and replace with the result.
224 %<...> The result of format-time-string on the ... format specification.
225 %t Time stamp, date only.
226 %T Time stamp with date and time.
227 %u, %U Like the above, but inactive time stamps.
228 %i Initial content, copied from the active region. If %i is
229 indented, the entire inserted text will be indented as well.
230 %a Annotation, normally the link created with `org-store-link'.
231 %A Like %a, but prompt for the description part.
232 %l Like %a, but only insert the literal link.
233 %c Current kill ring head.
234 %x Content of the X clipboard.
235 %k Title of currently clocked task.
236 %K Link to currently clocked task.
237 %n User name (taken from `user-full-name').
238 %f File visited by current buffer when org-capture was called.
239 %F Full path of the file or directory visited by current buffer.
240 %:keyword Specific information for certain link types, see below.
241 %^g Prompt for tags, with completion on tags in target file.
242 %^G Prompt for tags, with completion on all tags in all agenda files.
243 %^t Like %t, but prompt for date. Similarly %^T, %^u, %^U.
244 You may define a prompt like %^{Please specify birthday.
245 %^C Interactive selection of which kill or clip to use.
246 %^L Like %^C, but insert as link.
247 %^{prop}p Prompt the user for a value for property `prop'.
248 %^{prompt} Prompt the user for a string and replace this sequence with it.
249 A default value and a completion table ca be specified like this:
250 %^{prompt|default|completion2|completion3|...}.
251 %? After completing the template, position cursor here.
252 %\\n Insert the text entered at the nth %^{prompt}, where `n' is
253 a number, starting from 1.
255 Apart from these general escapes, you can access information specific to
256 the link type that is created. For example, calling `org-capture' in emails
257 or in Gnus will record the author and the subject of the message, which you
258 can access with \"%:from\" and \"%:subject\", respectively. Here is a
259 complete list of what is recorded for each link type.
261 Link type | Available information
262 ------------------------+------------------------------------------------------
263 bbdb | %:type %:name %:company
264 vm, wl, mh, mew, rmail, | %:type %:subject %:message-id
265 gnus | %:from %:fromname %:fromaddress
266 | %:to %:toname %:toaddress
267 | %:fromto (either \"to NAME\" or \"from NAME\")
268 | %:date %:date-timestamp (as active timestamp)
269 | %:date-timestamp-inactive (as inactive timestamp)
270 gnus | %:group, for messages also all email fields
271 w3, w3m | %:type %:url
272 info | %:type %:file %:node
273 calendar | %:type %:date"
274 :group 'org-capture
275 :version "24.1"
276 :type
277 '(repeat
278 (choice :value ("" "" entry (file "~/org/notes.org") "")
279 (list :tag "Multikey description"
280 (string :tag "Keys ")
281 (string :tag "Description"))
282 (list :tag "Template entry"
283 (string :tag "Keys ")
284 (string :tag "Description ")
285 (choice :tag "Capture Type " :value entry
286 (const :tag "Org entry" entry)
287 (const :tag "Plain list item" item)
288 (const :tag "Checkbox item" checkitem)
289 (const :tag "Plain text" plain)
290 (const :tag "Table line" table-line))
291 (choice :tag "Target location"
292 (list :tag "File"
293 (const :format "" file)
294 (file :tag " File"))
295 (list :tag "ID"
296 (const :format "" id)
297 (string :tag " ID"))
298 (list :tag "File & Headline"
299 (const :format "" file+headline)
300 (file :tag " File ")
301 (string :tag " Headline"))
302 (list :tag "File & Outline path"
303 (const :format "" file+olp)
304 (file :tag " File ")
305 (repeat :tag "Outline path" :inline t
306 (string :tag "Headline")))
307 (list :tag "File & Regexp"
308 (const :format "" file+regexp)
309 (file :tag " File ")
310 (regexp :tag " Regexp"))
311 (list :tag "File & Date tree"
312 (const :format "" file+datetree)
313 (file :tag " File"))
314 (list :tag "File & Date tree, prompt for date"
315 (const :format "" file+datetree+prompt)
316 (file :tag " File"))
317 (list :tag "File & function"
318 (const :format "" file+function)
319 (file :tag " File ")
320 (sexp :tag " Function"))
321 (list :tag "Current clocking task"
322 (const :format "" clock))
323 (list :tag "Function"
324 (const :format "" function)
325 (sexp :tag " Function")))
326 (choice :tag "Template"
327 (string)
328 (list :tag "File"
329 (const :format "" file)
330 (file :tag "Template file"))
331 (list :tag "Function"
332 (const :format "" function)
333 (function :tag "Template function")))
334 (plist :inline t
335 ;; Give the most common options as checkboxes
336 :options (((const :format "%v " :prepend) (const t))
337 ((const :format "%v " :immediate-finish) (const t))
338 ((const :format "%v " :empty-lines) (const 1))
339 ((const :format "%v " :clock-in) (const t))
340 ((const :format "%v " :clock-keep) (const t))
341 ((const :format "%v " :clock-resume) (const t))
342 ((const :format "%v " :unnarrowed) (const t))
343 ((const :format "%v " :kill-buffer) (const t))))))))
345 (defcustom org-capture-before-finalize-hook nil
346 "Hook that is run right before a capture process is finalized.
347 The capture buffer is still current when this hook runs and it is
348 widened to the entire buffer."
349 :group 'org-capture
350 :version "24.1"
351 :type 'hook)
353 (defcustom org-capture-after-finalize-hook nil
354 "Hook that is run right after a capture process is finalized.
355 Suitable for window cleanup."
356 :group 'org-capture
357 :version "24.1"
358 :type 'hook)
360 (defcustom org-capture-prepare-finalize-hook nil
361 "Hook that is run before the finalization starts.
362 The capture buffer is current and still narrowed."
363 :group 'org-capture
364 :version "24.1"
365 :type 'hook)
367 (defcustom org-capture-bookmark t
368 "When non-nil, add a bookmark pointing at the last stored
369 position when capturing."
370 :group 'org-capture
371 :version "24.2"
372 :type 'boolean)
374 ;;; The property list for keeping information about the capture process
376 (defvar org-capture-plist nil
377 "Plist for the current capture process, global, to avoid having to pass it.")
379 (defvar org-capture-current-plist nil
380 "Local variable holding the plist in a capture buffer.
381 This is used to store the plist for use when finishing a capture process
382 because another such process might have changed the global variable by then.
384 Each time a new capture buffer has been set up, the global `org-capture-plist'
385 is copied to this variable, which is local in the indirect buffer.")
387 (defvar org-capture-clock-keep nil
388 "Local variable to store the value of the :clock-keep parameter.
389 This is needed in case org-capture-finalize is called interactively.")
391 (defun org-capture-put (&rest stuff)
392 "Add properties to the capture property list `org-capture-plist'."
393 (while stuff
394 (setq org-capture-plist (plist-put org-capture-plist
395 (pop stuff) (pop stuff)))))
396 (defun org-capture-get (prop &optional local)
397 "Get properties from the capture property list `org-capture-plist'.
398 When LOCAL is set, use the local variable `org-capture-current-plist',
399 this is necessary after initialization of the capture process,
400 to avoid conflicts with other active capture processes."
401 (plist-get (if local org-capture-current-plist org-capture-plist) prop))
403 (defun org-capture-member (prop &optional local)
404 "Is PROP a property in `org-capture-plist'.
405 When LOCAL is set, use the local variable `org-capture-current-plist',
406 this is necessary after initialization of the capture process,
407 to avoid conflicts with other active capture processes."
408 (plist-get (if local org-capture-current-plist org-capture-plist) prop))
410 ;;; The minor mode
412 (defvar org-capture-mode-map (make-sparse-keymap)
413 "Keymap for `org-capture-mode', a minor mode.
414 Use this map to set additional keybindings for when Org-mode is used
415 for a capture buffer.")
417 (defvar org-capture-mode-hook nil
418 "Hook for the minor `org-capture-mode'.")
420 (define-minor-mode org-capture-mode
421 "Minor mode for special key bindings in a capture buffer."
422 nil " Rem" org-capture-mode-map
423 (org-set-local
424 'header-line-format
425 "Capture buffer. Finish `C-c C-c', refile `C-c C-w', abort `C-c C-k'.")
426 (run-hooks 'org-capture-mode-hook))
427 (define-key org-capture-mode-map "\C-c\C-c" 'org-capture-finalize)
428 (define-key org-capture-mode-map "\C-c\C-k" 'org-capture-kill)
429 (define-key org-capture-mode-map "\C-c\C-w" 'org-capture-refile)
431 ;;; The main commands
433 ;;;###autoload
434 (defvar org-capture-initial nil)
435 (defun org-capture-string (string &optional keys)
436 (interactive "sInitial text: \n")
437 (let ((org-capture-initial string)
438 (entry (org-capture-select-template keys)))
439 (org-capture)))
441 ;;;###autoload
442 (defun org-capture (&optional goto keys)
443 "Capture something.
444 \\<org-capture-mode-map>
445 This will let you select a template from `org-capture-templates', and then
446 file the newly captured information. The text is immediately inserted
447 at the target location, and an indirect buffer is shown where you can
448 edit it. Pressing \\[org-capture-finalize] brings you back to the previous state
449 of Emacs, so that you can continue your work.
451 When called interactively with a \\[universal-argument] prefix argument GOTO, don't capture
452 anything, just go to the file/headline where the selected template
453 stores its notes. With a double prefix argument \
454 \\[universal-argument] \\[universal-argument], go to the last note
455 stored.
457 When called with a `C-0' (zero) prefix, insert a template at point.
459 Lisp programs can set KEYS to a string associated with a template in
460 `org-capture-templates'. In this case, interactive selection will be
461 bypassed."
462 (interactive "P")
463 (cond
464 ((equal goto '(4)) (org-capture-goto-target))
465 ((equal goto '(16)) (org-capture-goto-last-stored))
467 ;; FIXME: Are these needed?
468 (let* ((orig-buf (current-buffer))
469 (annotation (if (and (boundp 'org-capture-link-is-already-stored)
470 org-capture-link-is-already-stored)
471 (plist-get org-store-link-plist :annotation)
472 (ignore-errors (org-store-link nil))))
473 (entry (or entry (org-capture-select-template keys)))
474 initial)
475 (setq initial (or org-capture-initial
476 (and (org-region-active-p)
477 (buffer-substring (point) (mark)))))
478 (when (stringp initial)
479 (remove-text-properties 0 (length initial) '(read-only t) initial))
480 (when (stringp annotation)
481 (remove-text-properties 0 (length annotation)
482 '(read-only t) annotation))
483 (cond
484 ((equal entry "C")
485 (customize-variable 'org-capture-templates))
486 ((equal entry "q")
487 (error "Abort"))
489 (org-capture-set-plist entry)
490 (org-capture-get-template)
491 (org-capture-put :original-buffer orig-buf
492 :original-file (or (buffer-file-name orig-buf)
493 (and (featurep 'dired)
494 (car (rassq orig-buf
495 dired-buffers))))
496 :original-file-nondirectory
497 (and (buffer-file-name orig-buf)
498 (file-name-nondirectory
499 (buffer-file-name orig-buf)))
500 :annotation annotation
501 :initial initial)
502 (org-capture-put :default-time
503 (or org-overriding-default-time
504 (org-current-time)))
505 (org-capture-set-target-location)
506 (condition-case error
507 (org-capture-put :template (org-capture-fill-template))
508 ((error quit)
509 (if (get-buffer "*Capture*") (kill-buffer "*Capture*"))
510 (error "Capture abort: %s" error)))
512 (setq org-capture-clock-keep (org-capture-get :clock-keep))
513 (if (equal goto 0)
514 ;;insert at point
515 (org-capture-insert-template-here)
516 (condition-case error
517 (org-capture-place-template)
518 ((error quit)
519 (if (and (buffer-base-buffer (current-buffer))
520 (string-match "\\`CAPTURE-" (buffer-name)))
521 (kill-buffer (current-buffer)))
522 (set-window-configuration (org-capture-get :return-to-wconf))
523 (error "Capture template `%s': %s"
524 (org-capture-get :key)
525 (nth 1 error))))
526 (if (and (derived-mode-p 'org-mode)
527 (org-capture-get :clock-in))
528 (condition-case nil
529 (progn
530 (if (org-clock-is-active)
531 (org-capture-put :interrupted-clock
532 (copy-marker org-clock-marker)))
533 (org-clock-in)
534 (org-set-local 'org-capture-clock-was-started t))
535 (error
536 "Could not start the clock in this capture buffer")))
537 (if (org-capture-get :immediate-finish)
538 (org-capture-finalize nil)))))))))
540 (defun org-capture-get-template ()
541 "Get the template from a file or a function if necessary."
542 (let ((txt (org-capture-get :template)) file)
543 (cond
544 ((and (listp txt) (eq (car txt) 'file))
545 (if (file-exists-p
546 (setq file (expand-file-name (nth 1 txt) org-directory)))
547 (setq txt (org-file-contents file))
548 (setq txt (format "* Template file %s not found" (nth 1 txt)))))
549 ((and (listp txt) (eq (car txt) 'function))
550 (if (fboundp (nth 1 txt))
551 (setq txt (funcall (nth 1 txt)))
552 (setq txt (format "* Template function %s not found" (nth 1 txt)))))
553 ((not txt) (setq txt ""))
554 ((stringp txt))
555 (t (setq txt "* Invalid capture template")))
556 (org-capture-put :template txt)))
558 (defun org-capture-finalize (&optional stay-with-capture)
559 "Finalize the capture process.
560 With prefix argument STAY-WITH-CAPTURE, jump to the location of the
561 captured item after finalizing."
562 (interactive "P")
563 (unless (and org-capture-mode
564 (buffer-base-buffer (current-buffer)))
565 (error "This does not seem to be a capture buffer for Org-mode"))
567 (run-hooks 'org-capture-prepare-finalize-hook)
569 ;; Did we start the clock in this capture buffer?
570 (when (and org-capture-clock-was-started
571 org-clock-marker (marker-buffer org-clock-marker)
572 (equal (marker-buffer org-clock-marker) (buffer-base-buffer))
573 (> org-clock-marker (point-min))
574 (< org-clock-marker (point-max)))
575 ;; Looks like the clock we started is still running. Clock out.
576 (when (not org-capture-clock-keep) (let (org-log-note-clock-out) (org-clock-out)))
577 (when (and (not org-capture-clock-keep)
578 (org-capture-get :clock-resume 'local)
579 (markerp (org-capture-get :interrupted-clock 'local))
580 (buffer-live-p (marker-buffer
581 (org-capture-get :interrupted-clock 'local))))
582 (let ((clock-in-task (org-capture-get :interrupted-clock 'local)))
583 (org-with-point-at clock-in-task
584 (org-clock-in)))
585 (message "Interrupted clock has been resumed")))
587 (let ((beg (point-min))
588 (end (point-max))
589 (abort-note nil))
590 ;; Store the size of the capture buffer
591 (org-capture-put :captured-entry-size (- (point-max) (point-min)))
592 (widen)
593 ;; Store the insertion point in the target buffer
594 (org-capture-put :insertion-point (point))
596 (if org-note-abort
597 (let ((m1 (org-capture-get :begin-marker 'local))
598 (m2 (org-capture-get :end-marker 'local)))
599 (if (and m1 m2 (= m1 beg) (= m2 end))
600 (progn
601 (setq m2 (if (cdr (assoc 'heading org-blank-before-new-entry))
602 m2 (1+ m2))
603 m2 (if (< (point-max) m2) (point-max) m2))
604 (setq abort-note 'clean)
605 (kill-region m1 m2))
606 (setq abort-note 'dirty)))
608 ;; Make sure that the empty lines after are correct
609 (when (and (> (point-max) end) ; indeed, the buffer was still narrowed
610 (member (org-capture-get :type 'local)
611 '(entry item checkitem plain)))
612 (save-excursion
613 (goto-char end)
614 (or (bolp) (newline))
615 (org-capture-empty-lines-after
616 (or (org-capture-get :empty-lines-after 'local)
617 (org-capture-get :empty-lines 'local) 0))))
618 ;; Postprocessing: Update Statistics cookies, do the sorting
619 (when (derived-mode-p 'org-mode)
620 (save-excursion
621 (when (ignore-errors (org-back-to-heading))
622 (org-update-parent-todo-statistics)
623 (org-update-checkbox-count)))
624 ;; FIXME Here we should do the sorting
625 ;; If we have added a table line, maybe recompute?
626 (when (and (eq (org-capture-get :type 'local) 'table-line)
627 (org-at-table-p))
628 (if (org-table-get-stored-formulas)
629 (org-table-recalculate 'all) ;; FIXME: Should we iterate???
630 (org-table-align))))
631 ;; Store this place as the last one where we stored something
632 ;; Do the marking in the base buffer, so that it makes sense after
633 ;; the indirect buffer has been killed.
634 (when org-capture-bookmark
635 (org-capture-bookmark-last-stored-position))
637 ;; Run the hook
638 (run-hooks 'org-capture-before-finalize-hook))
640 ;; Kill the indirect buffer
641 (save-buffer)
642 (let ((return-wconf (org-capture-get :return-to-wconf 'local))
643 (new-buffer (org-capture-get :new-buffer 'local))
644 (kill-buffer (org-capture-get :kill-buffer 'local))
645 (base-buffer (buffer-base-buffer (current-buffer))))
647 ;; Kill the indirect buffer
648 (kill-buffer (current-buffer))
650 ;; Narrow back the target buffer to its previous state
651 (with-current-buffer (org-capture-get :buffer)
652 (let ((reg (org-capture-get :initial-target-region))
653 (pos (org-capture-get :initial-target-position))
654 (ipt (org-capture-get :insertion-point))
655 (size (org-capture-get :captured-entry-size)))
656 (when reg
657 (cond ((< ipt (car reg))
658 ;; insertion point is before the narrowed region
659 (narrow-to-region (+ size (car reg)) (+ size (cdr reg))))
660 ((> ipt (cdr reg))
661 ;; insertion point is after the narrowed region
662 (narrow-to-region (car reg) (cdr reg)))
664 ;; insertion point is within the narrowed region
665 (narrow-to-region (car reg) (+ size (cdr reg)))))
666 ;; now place back the point at its original position
667 (if (< ipt (car reg))
668 (goto-char (+ size pos))
669 (goto-char (if (< ipt pos) (+ size pos) pos))))))
671 ;; Kill the target buffer if that is desired
672 (when (and base-buffer new-buffer kill-buffer)
673 (with-current-buffer base-buffer (save-buffer))
674 (kill-buffer base-buffer))
676 ;; Restore the window configuration before capture
677 (set-window-configuration return-wconf))
679 (run-hooks 'org-capture-after-finalize-hook)
680 ;; Special cases
681 (cond
682 (abort-note
683 (cond
684 ((equal abort-note 'clean)
685 (message "Capture process aborted and target buffer cleaned up"))
686 ((equal abort-note 'dirty)
687 (error "Capture process aborted, but target buffer could not be cleaned up correctly"))))
688 (stay-with-capture
689 (org-capture-goto-last-stored)))
690 ;; Return if we did store something
691 (not abort-note)))
693 (defun org-capture-refile ()
694 "Finalize the current capture and then refile the entry.
695 Refiling is done from the base buffer, because the indirect buffer is then
696 already gone. Any prefix argument will be passed to the refile command."
697 (interactive)
698 (unless (eq (org-capture-get :type 'local) 'entry)
699 (error
700 "Refiling from a capture buffer makes only sense for `entry'-type templates"))
701 (let ((pos (point))
702 (base (buffer-base-buffer (current-buffer)))
703 (org-refile-for-capture t))
704 (org-capture-finalize)
705 (save-window-excursion
706 (with-current-buffer (or base (current-buffer))
707 (save-excursion
708 (save-restriction
709 (widen)
710 (goto-char pos)
711 (call-interactively 'org-refile)))))))
713 (defun org-capture-kill ()
714 "Abort the current capture process."
715 (interactive)
716 ;; FIXME: This does not do the right thing, we need to remove the
717 ;; new stuff by hand it is easy: undo, then kill the buffer
718 (let ((org-note-abort t)
719 (org-capture-before-finalize-hook nil))
720 (org-capture-finalize)))
722 (defun org-capture-goto-last-stored ()
723 "Go to the location where the last capture note was stored."
724 (interactive)
725 (org-goto-marker-or-bmk org-capture-last-stored-marker
726 "org-capture-last-stored")
727 (message "This is the last note stored by a capture process"))
729 ;;; Supporting functions for handling the process
731 (defun org-capture-put-target-region-and-position ()
732 "Store the initial region with `org-capture-put'."
733 (org-capture-put
734 :initial-target-region
735 ;; Check if the buffer is currently narrowed
736 (when (/= (buffer-size) (- (point-max) (point-min)))
737 (cons (point-min) (point-max))))
738 ;; store the current point
739 (org-capture-put :initial-target-position (point)))
741 (defun org-capture-set-target-location (&optional target)
742 "Find target buffer and position and store then in the property list."
743 (let ((target-entry-p t))
744 (setq target (or target (org-capture-get :target)))
745 (save-excursion
746 (cond
747 ((eq (car target) 'file)
748 (set-buffer (org-capture-target-buffer (nth 1 target)))
749 (org-capture-put-target-region-and-position)
750 (widen)
751 (setq target-entry-p nil))
753 ((eq (car target) 'id)
754 (let ((loc (org-id-find (nth 1 target))))
755 (if (not loc)
756 (error "Cannot find target ID \"%s\"" (nth 1 target))
757 (set-buffer (org-capture-target-buffer (car loc)))
758 (widen)
759 (org-capture-put-target-region-and-position)
760 (goto-char (cdr loc)))))
762 ((eq (car target) 'file+headline)
763 (set-buffer (org-capture-target-buffer (nth 1 target)))
764 (org-capture-put-target-region-and-position)
765 (widen)
766 (let ((hd (nth 2 target)))
767 (goto-char (point-min))
768 (unless (derived-mode-p 'org-mode)
769 (error
770 "Target buffer \"%s\" for file+headline should be in Org mode"
771 (current-buffer)))
772 (if (re-search-forward
773 (format org-complex-heading-regexp-format (regexp-quote hd))
774 nil t)
775 (goto-char (point-at-bol))
776 (goto-char (point-max))
777 (or (bolp) (insert "\n"))
778 (insert "* " hd "\n")
779 (beginning-of-line 0))))
781 ((eq (car target) 'file+olp)
782 (let ((m (org-find-olp
783 (cons (org-capture-expand-file (nth 1 target))
784 (cddr target)))))
785 (set-buffer (marker-buffer m))
786 (org-capture-put-target-region-and-position)
787 (widen)
788 (goto-char m)))
790 ((eq (car target) 'file+regexp)
791 (set-buffer (org-capture-target-buffer (nth 1 target)))
792 (org-capture-put-target-region-and-position)
793 (widen)
794 (goto-char (point-min))
795 (if (re-search-forward (nth 2 target) nil t)
796 (progn
797 (goto-char (if (org-capture-get :prepend)
798 (match-beginning 0) (match-end 0)))
799 (org-capture-put :exact-position (point))
800 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
801 (error "No match for target regexp in file %s" (nth 1 target))))
803 ((memq (car target) '(file+datetree file+datetree+prompt))
804 (require 'org-datetree)
805 (set-buffer (org-capture-target-buffer (nth 1 target)))
806 (org-capture-put-target-region-and-position)
807 (widen)
808 ;; Make a date tree entry, with the current date (or yesterday,
809 ;; if we are extending dates for a couple of hours)
810 (org-datetree-find-date-create
811 (calendar-gregorian-from-absolute
812 (cond
813 (org-overriding-default-time
814 ;; use the overriding default time
815 (time-to-days org-overriding-default-time))
817 ((eq (car target) 'file+datetree+prompt)
818 ;; prompt for date
819 (let ((prompt-time (org-read-date
820 nil t nil "Date for tree entry:"
821 (current-time))))
822 (org-capture-put :prompt-time prompt-time
823 :default-time prompt-time)
824 (time-to-days prompt-time)))
826 ;; current date, possible corrected for late night workers
827 (org-today))))))
829 ((eq (car target) 'file+function)
830 (set-buffer (org-capture-target-buffer (nth 1 target)))
831 (org-capture-put-target-region-and-position)
832 (widen)
833 (funcall (nth 2 target))
834 (org-capture-put :exact-position (point))
835 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
837 ((eq (car target) 'function)
838 (funcall (nth 1 target))
839 (org-capture-put :exact-position (point))
840 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
842 ((eq (car target) 'clock)
843 (if (and (markerp org-clock-hd-marker)
844 (marker-buffer org-clock-hd-marker))
845 (progn (set-buffer (marker-buffer org-clock-hd-marker))
846 (org-capture-put-target-region-and-position)
847 (widen)
848 (goto-char org-clock-hd-marker))
849 (error "No running clock that could be used as capture target")))
851 (t (error "Invalid capture target specification")))
853 (org-capture-put :buffer (current-buffer) :pos (point)
854 :target-entry-p target-entry-p))))
856 (defun org-capture-expand-file (file)
857 "Expand functions and symbols for FILE.
858 When FILE is a function, call it. When it is a form, evaluate
859 it. When it is a variable, retrieve the value. Return whatever we get."
860 (cond
861 ((org-string-nw-p file) file)
862 ((functionp file) (funcall file))
863 ((and (symbolp file) (boundp file)) (symbol-value file))
864 ((and file (consp file)) (eval file))
865 (t file)))
867 (defun org-capture-target-buffer (file)
868 "Get a buffer for FILE."
869 (setq file (org-capture-expand-file file))
870 (setq file (or (org-string-nw-p file)
871 org-default-notes-file
872 (error "No notes file specified, and no default available")))
873 (or (org-find-base-buffer-visiting file)
874 (progn (org-capture-put :new-buffer t)
875 (find-file-noselect (expand-file-name file org-directory)))))
877 (defun org-capture-steal-local-variables (buffer)
878 "Install Org-mode local variables."
879 (mapc (lambda (v)
880 (ignore-errors (org-set-local (car v) (cdr v))))
881 (buffer-local-variables buffer)))
883 (defun org-capture-place-template ()
884 "Insert the template at the target location, and display the buffer."
885 (org-capture-put :return-to-wconf (current-window-configuration))
886 (delete-other-windows)
887 (org-switch-to-buffer-other-window
888 (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE"))
889 (widen)
890 (show-all)
891 (goto-char (org-capture-get :pos))
892 (org-set-local 'org-capture-target-marker
893 (move-marker (make-marker) (point)))
894 (org-set-local 'outline-level 'org-outline-level)
895 (let* ((template (org-capture-get :template))
896 (type (org-capture-get :type)))
897 (case type
898 ((nil entry) (org-capture-place-entry))
899 (table-line (org-capture-place-table-line))
900 (plain (org-capture-place-plain-text))
901 (item (org-capture-place-item))
902 (checkitem (org-capture-place-item))))
903 (org-capture-mode 1)
904 (org-set-local 'org-capture-current-plist org-capture-plist))
906 (defun org-capture-place-entry ()
907 "Place the template as a new Org entry."
908 (let* ((txt (org-capture-get :template))
909 (reversed (org-capture-get :prepend))
910 (target-entry-p (org-capture-get :target-entry-p))
911 level beg end file)
913 (cond
914 ((org-capture-get :exact-position)
915 (goto-char (org-capture-get :exact-position)))
916 ((not target-entry-p)
917 ;; Insert as top-level entry, either at beginning or at end of file
918 (setq level 1)
919 (if reversed
920 (progn (goto-char (point-min))
921 (or (org-at-heading-p)
922 (outline-next-heading)))
923 (goto-char (point-max))
924 (or (bolp) (insert "\n"))))
926 ;; Insert as a child of the current entry
927 (and (looking-at "\\*+")
928 (setq level (- (match-end 0) (match-beginning 0))))
929 (setq level (org-get-valid-level (or level 1) 1))
930 (if reversed
931 (progn
932 (outline-next-heading)
933 (or (bolp) (insert "\n")))
934 (org-end-of-subtree t nil)
935 (or (bolp) (insert "\n")))))
936 (org-capture-empty-lines-before)
937 (setq beg (point))
938 (org-capture-verify-tree txt)
939 (org-paste-subtree level txt 'for-yank)
940 (org-capture-empty-lines-after 1)
941 (org-capture-position-for-last-stored beg)
942 (outline-next-heading)
943 (setq end (point))
944 (org-capture-mark-kill-region beg (1- end))
945 (org-capture-narrow beg (1- end))
946 (if (or (re-search-backward "%\\?" beg t)
947 (re-search-forward "%\\?" end t))
948 (replace-match ""))))
950 (defun org-capture-place-item ()
951 "Place the template as a new plain list item."
952 (let* ((txt (org-capture-get :template))
953 (target-entry-p (org-capture-get :target-entry-p))
954 (ind 0)
955 beg end)
956 (if (org-capture-get :exact-position)
957 (goto-char (org-capture-get :exact-position))
958 (cond
959 ((not target-entry-p)
960 ;; Insert as top-level entry, either at beginning or at end of file
961 (setq beg (point-min) end (point-max)))
963 (setq beg (1+ (point-at-eol))
964 end (save-excursion (outline-next-heading) (point)))))
965 (if (org-capture-get :prepend)
966 (progn
967 (goto-char beg)
968 (if (org-list-search-forward (org-item-beginning-re) end t)
969 (progn
970 (goto-char (match-beginning 0))
971 (setq ind (org-get-indentation)))
972 (goto-char end)
973 (setq ind 0)))
974 (goto-char end)
975 (if (org-list-search-backward (org-item-beginning-re) beg t)
976 (progn
977 (setq ind (org-get-indentation))
978 (org-end-of-item))
979 (setq ind 0))))
980 ;; Remove common indentation
981 (setq txt (org-remove-indentation txt))
982 ;; Make sure this is indeed an item
983 (unless (string-match (concat "\\`" (org-item-re)) txt)
984 (setq txt (concat "- "
985 (mapconcat 'identity (split-string txt "\n")
986 "\n "))))
987 ;; Set the correct indentation, depending on context
988 (setq ind (make-string ind ?\ ))
989 (setq txt (concat ind
990 (mapconcat 'identity (split-string txt "\n")
991 (concat "\n" ind))
992 "\n"))
993 ;; Insert, with surrounding empty lines
994 (org-capture-empty-lines-before)
995 (setq beg (point))
996 (insert txt)
997 (or (bolp) (insert "\n"))
998 (org-capture-empty-lines-after 1)
999 (org-capture-position-for-last-stored beg)
1000 (forward-char 1)
1001 (setq end (point))
1002 (org-capture-mark-kill-region beg (1- end))
1003 (org-capture-narrow beg (1- end))
1004 (if (or (re-search-backward "%\\?" beg t)
1005 (re-search-forward "%\\?" end t))
1006 (replace-match ""))))
1008 (defun org-capture-place-table-line ()
1009 "Place the template as a table line."
1010 (require 'org-table)
1011 (let* ((txt (org-capture-get :template))
1012 (target-entry-p (org-capture-get :target-entry-p))
1013 (table-line-pos (org-capture-get :table-line-pos))
1014 ind beg end)
1015 (cond
1016 ((org-capture-get :exact-position)
1017 (goto-char (org-capture-get :exact-position)))
1018 ((not target-entry-p)
1019 ;; Table is not necessarily under a heading
1020 (setq beg (point-min) end (point-max)))
1022 ;; WE are at a heading, limit search to the body
1023 (setq beg (1+ (point-at-eol))
1024 end (save-excursion (outline-next-heading) (point)))))
1025 (if (re-search-forward org-table-dataline-regexp end t)
1026 (let ((b (org-table-begin)) (e (org-table-end)) (case-fold-search t))
1027 (goto-char e)
1028 (if (looking-at "[ \t]*#\\+tblfm:")
1029 (forward-line 1))
1030 (narrow-to-region b (point)))
1031 (goto-char end)
1032 (insert "\n| |\n|----|\n| |\n")
1033 (narrow-to-region (1+ end) (point)))
1034 ;; We are narrowed to the table, or to an empty line if there was no table
1036 ;; Check if the template is good
1037 (if (not (string-match org-table-dataline-regexp txt))
1038 (setq txt "| %?Bad template |\n"))
1039 (cond
1040 ((and table-line-pos
1041 (string-match "\\(I+\\)\\([-+][0-9]\\)" table-line-pos))
1042 ;; we have a complex line specification
1043 (goto-char (point-min))
1044 (let ((nh (- (match-end 1) (match-beginning 1)))
1045 (delta (string-to-number (match-string 2 table-line-pos)))
1047 ;; The user wants a special position in the table
1048 (org-table-get-specials)
1049 (setq ll (ignore-errors (aref org-table-hlines nh)))
1050 (unless ll (error "Invalid table line specification \"%s\""
1051 table-line-pos))
1052 (setq ll (+ ll delta (if (< delta 0) 0 -1)))
1053 (org-goto-line ll)
1054 (org-table-insert-row 'below)
1055 (beginning-of-line 1)
1056 (delete-region (point) (1+ (point-at-eol)))
1057 (setq beg (point))
1058 (insert txt)
1059 (setq end (point))))
1060 ((org-capture-get :prepend)
1061 (goto-char (point-min))
1062 (re-search-forward org-table-hline-regexp nil t)
1063 (beginning-of-line 1)
1064 (re-search-forward org-table-dataline-regexp nil t)
1065 (beginning-of-line 1)
1066 (setq beg (point))
1067 (org-table-insert-row)
1068 (beginning-of-line 1)
1069 (delete-region (point) (1+ (point-at-eol)))
1070 (insert txt)
1071 (setq end (point)))
1073 (goto-char (point-max))
1074 (re-search-backward org-table-dataline-regexp nil t)
1075 (beginning-of-line 1)
1076 (org-table-insert-row 'below)
1077 (beginning-of-line 1)
1078 (delete-region (point) (1+ (point-at-eol)))
1079 (setq beg (point))
1080 (insert txt)
1081 (setq end (point))))
1082 (goto-char beg)
1083 (org-capture-position-for-last-stored 'table-line)
1084 (if (or (re-search-backward "%\\?" end t)
1085 (re-search-forward "%\\?" beg t))
1086 (replace-match ""))
1087 (org-table-align)))
1089 (defun org-capture-place-plain-text ()
1090 "Place the template plainly.
1091 If the target locator points at an Org node, place the template into
1092 the text of the entry, before the first child. If not, place the
1093 template at the beginning or end of the file.
1094 Of course, if exact position has been required, just put it there."
1095 (let* ((txt (org-capture-get :template))
1096 beg end)
1097 (cond
1098 ((org-capture-get :exact-position)
1099 (goto-char (org-capture-get :exact-position)))
1100 ((and (org-capture-get :target-entry-p)
1101 (bolp)
1102 (looking-at org-outline-regexp))
1103 ;; we should place the text into this entry
1104 (if (org-capture-get :prepend)
1105 ;; Skip meta data and drawers
1106 (org-end-of-meta-data-and-drawers)
1107 ;; go to ent of the entry text, before the next headline
1108 (outline-next-heading)))
1110 ;; beginning or end of file
1111 (goto-char (if (org-capture-get :prepend) (point-min) (point-max)))))
1112 (or (bolp) (newline))
1113 (org-capture-empty-lines-before)
1114 (setq beg (point))
1115 (insert txt)
1116 (org-capture-empty-lines-after 1)
1117 (org-capture-position-for-last-stored beg)
1118 (setq end (point))
1119 (org-capture-mark-kill-region beg (1- end))
1120 (org-capture-narrow beg (1- end))
1121 (if (or (re-search-backward "%\\?" beg t)
1122 (re-search-forward "%\\?" end t))
1123 (replace-match ""))))
1125 (defun org-capture-mark-kill-region (beg end)
1126 "Mark the region that will have to be killed when aborting capture."
1127 (let ((m1 (move-marker (make-marker) beg))
1128 (m2 (move-marker (make-marker) end)))
1129 (org-capture-put :begin-marker m1)
1130 (org-capture-put :end-marker m2)))
1132 (defun org-capture-position-for-last-stored (where)
1133 "Memorize the position that should later become the position of last capture."
1134 (cond
1135 ((integerp where)
1136 (org-capture-put :position-for-last-stored
1137 (move-marker (make-marker) where
1138 (or (buffer-base-buffer (current-buffer))
1139 (current-buffer)))))
1140 ((eq where 'table-line)
1141 (org-capture-put :position-for-last-stored
1142 (list 'table-line
1143 (org-table-current-dline))))
1144 (t (error "This should not happen"))))
1146 (defun org-capture-bookmark-last-stored-position ()
1147 "Bookmark the last-captured position."
1148 (let* ((where (org-capture-get :position-for-last-stored 'local))
1149 (pos (cond
1150 ((markerp where)
1151 (prog1 (marker-position where)
1152 (move-marker where nil)))
1153 ((and (listp where) (eq (car where) 'table-line))
1154 (if (org-at-table-p)
1155 (save-excursion
1156 (org-table-goto-line (nth 1 where))
1157 (point-at-bol))
1158 (point))))))
1159 (with-current-buffer (buffer-base-buffer (current-buffer))
1160 (save-excursion
1161 (save-restriction
1162 (widen)
1163 (goto-char pos)
1164 (bookmark-set "org-capture-last-stored")
1165 (move-marker org-capture-last-stored-marker (point)))))))
1167 (defun org-capture-narrow (beg end)
1168 "Narrow, unless configuration says not to narrow."
1169 (unless (org-capture-get :unnarrowed)
1170 (narrow-to-region beg end)
1171 (goto-char beg)))
1173 (defun org-capture-empty-lines-before (&optional n)
1174 "Arrange for the correct number of empty lines before the insertion point.
1175 Point will be after the empty lines, so insertion can directly be done."
1176 (setq n (or n (org-capture-get :empty-lines-before)
1177 (org-capture-get :empty-lines) 0))
1178 (let ((pos (point)))
1179 (org-back-over-empty-lines)
1180 (delete-region (point) pos)
1181 (if (> n 0) (newline n))))
1183 (defun org-capture-empty-lines-after (&optional n)
1184 "Arrange for the correct number of empty lines after the inserted string.
1185 Point will remain at the first line after the inserted text."
1186 (setq n (or n (org-capture-get :empty-lines-after)
1187 (org-capture-get :empty-lines) 0))
1188 (org-back-over-empty-lines)
1189 (while (looking-at "[ \t]*\n") (replace-match ""))
1190 (let ((pos (point)))
1191 (if (> n 0) (newline n))
1192 (goto-char pos)))
1194 (defvar org-clock-marker) ; Defined in org.el
1195 ;;;###autoload
1196 (defun org-capture-insert-template-here ()
1197 (let* ((template (org-capture-get :template))
1198 (type (org-capture-get :type))
1199 beg end pp)
1200 (or (bolp) (newline))
1201 (setq beg (point))
1202 (cond
1203 ((and (eq type 'entry) (derived-mode-p 'org-mode))
1204 (org-capture-verify-tree (org-capture-get :template))
1205 (org-paste-subtree nil template t))
1206 ((and (memq type '(item checkitem))
1207 (derived-mode-p 'org-mode)
1208 (save-excursion (skip-chars-backward " \t\n")
1209 (setq pp (point))
1210 (org-in-item-p)))
1211 (goto-char pp)
1212 (org-insert-item)
1213 (skip-chars-backward " ")
1214 (skip-chars-backward "-+*0123456789).")
1215 (delete-region (point) (point-at-eol))
1216 (setq beg (point))
1217 (org-remove-indentation template)
1218 (insert template)
1219 (org-capture-empty-lines-after)
1220 (goto-char beg)
1221 (org-list-repair)
1222 (org-end-of-item)
1223 (setq end (point)))
1224 (t (insert template)))
1225 (setq end (point))
1226 (goto-char beg)
1227 (if (re-search-forward "%\\?" end t)
1228 (replace-match ""))))
1230 (defun org-capture-set-plist (entry)
1231 "Initialize the property list from the template definition."
1232 (setq org-capture-plist (copy-sequence (nthcdr 5 entry)))
1233 (org-capture-put :key (car entry) :description (nth 1 entry)
1234 :target (nth 3 entry))
1235 (let ((txt (nth 4 entry)) (type (or (nth 2 entry) 'entry)))
1236 (when (or (not txt) (and (stringp txt) (not (string-match "\\S-" txt))))
1237 ;; The template may be empty or omitted for special types.
1238 ;; Here we insert the default templates for such cases.
1239 (cond
1240 ((eq type 'item) (setq txt "- %?"))
1241 ((eq type 'checkitem) (setq txt "- [ ] %?"))
1242 ((eq type 'table-line) (setq txt "| %? |"))
1243 ((member type '(nil entry)) (setq txt "* %?\n %a"))))
1244 (org-capture-put :template txt :type type)))
1246 (defun org-capture-goto-target (&optional template-key)
1247 "Go to the target location of a capture template.
1248 The user is queried for the template."
1249 (interactive)
1250 (let* (org-select-template-temp-major-mode
1251 (entry (org-capture-select-template template-key)))
1252 (unless entry
1253 (error "No capture template selected"))
1254 (org-capture-set-plist entry)
1255 (org-capture-set-target-location)
1256 (org-pop-to-buffer-same-window (org-capture-get :buffer))
1257 (goto-char (org-capture-get :pos))))
1259 (defun org-capture-get-indirect-buffer (&optional buffer prefix)
1260 "Make an indirect buffer for a capture process.
1261 Use PREFIX as a prefix for the name of the indirect buffer."
1262 (setq buffer (or buffer (current-buffer)))
1263 (let ((n 1) (base (buffer-name buffer)) bname)
1264 (setq bname (concat prefix "-" base))
1265 (while (buffer-live-p (get-buffer bname))
1266 (setq bname (concat prefix "-" (number-to-string (incf n)) "-" base)))
1267 (condition-case nil
1268 (make-indirect-buffer buffer bname 'clone)
1269 (error
1270 (let ((buf (make-indirect-buffer buffer bname)))
1271 (with-current-buffer buf (org-mode))
1272 buf)))))
1274 (defun org-capture-verify-tree (tree)
1275 "Throw error if TREE is not a valid tree."
1276 (unless (org-kill-is-subtree-p tree)
1277 (error "Template is not a valid Org entry or tree")))
1279 ;;; The template code
1281 (defun org-capture-select-template (&optional keys)
1282 "Select a capture template.
1283 Lisp programs can force the template by setting KEYS to a string."
1284 (let ((org-capture-templates
1285 (or org-capture-templates
1286 '(("t" "Task" entry (file+headline "" "Tasks")
1287 "* TODO %?\n %u\n %a")))))
1288 (if keys
1289 (or (assoc keys org-capture-templates)
1290 (error "No capture template referred to by \"%s\" keys" keys))
1291 (org-mks org-capture-templates
1292 "Select a capture template\n========================="
1293 "Template key: "
1294 '(("C" "Customize org-capture-templates")
1295 ("q" "Abort"))))))
1297 (defun org-capture-fill-template (&optional template initial annotation)
1298 "Fill a template and return the filled template as a string.
1299 The template may still contain \"%?\" for cursor positioning."
1300 (setq template (or template (org-capture-get :template)))
1301 (when (stringp initial)
1302 (setq initial (org-no-properties initial))
1303 (remove-text-properties 0 (length initial) '(read-only t) initial))
1304 (let* ((buffer (org-capture-get :buffer))
1305 (file (buffer-file-name (or (buffer-base-buffer buffer) buffer)))
1306 (ct (org-capture-get :default-time))
1307 (dct (decode-time ct))
1308 (ct1
1309 (if (< (nth 2 dct) org-extend-today-until)
1310 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
1311 ct))
1312 (plist-p (if org-store-link-plist t nil))
1313 (v-c (and (> (length kill-ring) 0) (current-kill 0)))
1314 (v-x (or (org-get-x-clipboard 'PRIMARY)
1315 (org-get-x-clipboard 'CLIPBOARD)
1316 (org-get-x-clipboard 'SECONDARY)))
1317 (v-t (format-time-string (car org-time-stamp-formats) ct))
1318 (v-T (format-time-string (cdr org-time-stamp-formats) ct))
1319 (v-u (concat "[" (substring v-t 1 -1) "]"))
1320 (v-U (concat "[" (substring v-T 1 -1) "]"))
1321 ;; `initial' and `annotation' might habe been passed.
1322 ;; But if the property list has them, we prefer those values
1323 (v-i (or (plist-get org-store-link-plist :initial)
1324 initial
1325 (org-capture-get :initial)
1326 ""))
1327 (v-a (or (plist-get org-store-link-plist :annotation)
1328 annotation
1329 (org-capture-get :annotation)
1330 ""))
1331 ;; Is the link empty? Then we do not want it...
1332 (v-a (if (equal v-a "[[]]") "" v-a))
1333 (clipboards (remove nil (list v-i
1334 (org-get-x-clipboard 'PRIMARY)
1335 (org-get-x-clipboard 'CLIPBOARD)
1336 (org-get-x-clipboard 'SECONDARY)
1337 v-c)))
1338 (l-re "\\[\\[\\(.*?\\)\\]\\(\\[.*?\\]\\)?\\]")
1339 (v-A (if (and v-a (string-match l-re v-a))
1340 (replace-match "[[\\1][%^{Link description}]]" nil nil v-a)
1341 v-a))
1342 (v-l (if (and v-a (string-match l-re v-a))
1343 (replace-match "\\1" nil nil v-a)
1344 v-a))
1345 (v-n user-full-name)
1346 (v-k (if (marker-buffer org-clock-marker)
1347 (org-substring-no-properties org-clock-heading)))
1348 (v-K (if (marker-buffer org-clock-marker)
1349 (org-make-link-string
1350 (buffer-file-name (marker-buffer org-clock-marker))
1351 org-clock-heading)))
1352 (v-f (or (org-capture-get :original-file-nondirectory) ""))
1353 (v-F (or (org-capture-get :original-file) ""))
1355 (org-startup-folded nil)
1356 (org-inhibit-startup t)
1357 org-time-was-given org-end-time-was-given x
1358 prompt completions char time pos default histvar strings)
1360 (setq org-store-link-plist
1361 (plist-put org-store-link-plist :annotation v-a)
1362 org-store-link-plist
1363 (plist-put org-store-link-plist :initial v-i))
1364 (setq initial v-i)
1366 (unless template (setq template "") (message "No template") (ding)
1367 (sit-for 1))
1368 (save-window-excursion
1369 (delete-other-windows)
1370 (org-pop-to-buffer-same-window (get-buffer-create "*Capture*"))
1371 (erase-buffer)
1372 (insert template)
1373 (goto-char (point-min))
1374 (org-capture-steal-local-variables buffer)
1375 (setq buffer-file-name nil)
1377 ;; %[] Insert contents of a file.
1378 (goto-char (point-min))
1379 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
1380 (unless (org-capture-escaped-%)
1381 (let ((start (match-beginning 0))
1382 (end (match-end 0))
1383 (filename (expand-file-name (match-string 1))))
1384 (goto-char start)
1385 (delete-region start end)
1386 (condition-case error
1387 (insert-file-contents filename)
1388 (error (insert (format "%%![Couldn't insert %s: %s]"
1389 filename error)))))))
1390 ;; %() embedded elisp
1391 (org-capture-expand-embedded-elisp)
1393 ;; The current time
1394 (goto-char (point-min))
1395 (while (re-search-forward "%<\\([^>\n]+\\)>" nil t)
1396 (replace-match (format-time-string (match-string 1)) t t))
1398 ;; Simple %-escapes
1399 (goto-char (point-min))
1400 (while (re-search-forward "%\\([tTuUaliAcxkKInfF]\\)" nil t)
1401 (unless (org-capture-escaped-%)
1402 (when (and initial (equal (match-string 0) "%i"))
1403 (save-match-data
1404 (let* ((lead (buffer-substring
1405 (point-at-bol) (match-beginning 0))))
1406 (setq v-i (mapconcat 'identity
1407 (org-split-string initial "\n")
1408 (concat "\n" lead))))))
1409 (replace-match
1410 (or (eval (intern (concat "v-" (match-string 1)))) "")
1411 t t)))
1413 ;; From the property list
1414 (when plist-p
1415 (goto-char (point-min))
1416 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
1417 (unless (org-capture-escaped-%)
1418 (and (setq x (or (plist-get org-store-link-plist
1419 (intern (match-string 1))) ""))
1420 (replace-match x t t)))))
1422 ;; Turn on org-mode in temp buffer, set local variables
1423 ;; This is to support completion in interactive prompts
1424 (let ((org-inhibit-startup t)) (org-mode))
1425 ;; Interactive template entries
1426 (goto-char (point-min))
1427 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGtTuUCLp]\\)?"
1428 nil t)
1429 (unless (org-capture-escaped-%)
1430 (setq char (if (match-end 3) (match-string-no-properties 3))
1431 prompt (if (match-end 2) (match-string-no-properties 2)))
1432 (goto-char (match-beginning 0))
1433 (replace-match "")
1434 (setq completions nil default nil)
1435 (when prompt
1436 (setq completions (org-split-string prompt "|")
1437 prompt (pop completions)
1438 default (car completions)
1439 histvar (intern (concat
1440 "org-capture-template-prompt-history::"
1441 (or prompt "")))
1442 completions (mapcar 'list completions)))
1443 (unless (boundp histvar) (set histvar nil))
1444 (cond
1445 ((member char '("G" "g"))
1446 (let* ((org-last-tags-completion-table
1447 (org-global-tags-completion-table
1448 (if (equal char "G")
1449 (org-agenda-files)
1450 (and file (list file)))))
1451 (org-add-colon-after-tag-completion t)
1452 (ins (org-icompleting-read
1453 (if prompt (concat prompt ": ") "Tags: ")
1454 'org-tags-completion-function nil nil nil
1455 'org-tags-history)))
1456 (setq ins (mapconcat 'identity
1457 (org-split-string
1458 ins (org-re "[^[:alnum:]_@#%]+"))
1459 ":"))
1460 (when (string-match "\\S-" ins)
1461 (or (equal (char-before) ?:) (insert ":"))
1462 (insert ins)
1463 (or (equal (char-after) ?:) (insert ":"))
1464 (and (org-at-heading-p) (org-set-tags nil 'align)))))
1465 ((equal char "C")
1466 (cond ((= (length clipboards) 1) (insert (car clipboards)))
1467 ((> (length clipboards) 1)
1468 (insert (read-string "Clipboard/kill value: "
1469 (car clipboards) '(clipboards . 1)
1470 (car clipboards))))))
1471 ((equal char "L")
1472 (cond ((= (length clipboards) 1)
1473 (org-insert-link 0 (car clipboards)))
1474 ((> (length clipboards) 1)
1475 (org-insert-link 0 (read-string "Clipboard/kill value: "
1476 (car clipboards)
1477 '(clipboards . 1)
1478 (car clipboards))))))
1479 ((equal char "p")
1480 (org-set-property (org-substring-no-properties prompt) nil))
1481 (char
1482 ;; These are the date/time related ones
1483 (setq org-time-was-given (equal (upcase char) char))
1484 (setq time (org-read-date (equal (upcase char) char) t nil
1485 prompt))
1486 (if (equal (upcase char) char) (setq org-time-was-given t))
1487 (org-insert-time-stamp time org-time-was-given
1488 (member char '("u" "U"))
1489 nil nil (list org-end-time-was-given)))
1491 (let (org-completion-use-ido)
1492 (push (org-completing-read-no-i
1493 (concat (if prompt prompt "Enter string")
1494 (if default (concat " [" default "]"))
1495 ": ")
1496 completions nil nil nil histvar default)
1497 strings)
1498 (insert (car strings)))))))
1499 ;; Replace %n escapes with nth %^{...} string
1500 (setq strings (nreverse strings))
1501 (goto-char (point-min))
1502 (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t)
1503 (unless (org-capture-escaped-%)
1504 (replace-match
1505 (nth (1- (string-to-number (match-string 1))) strings)
1506 nil t)))
1507 ;; Make sure there are no empty lines before the text, and that
1508 ;; it ends with a newline character
1509 (goto-char (point-min))
1510 (while (looking-at "[ \t]*\n") (replace-match ""))
1511 (if (re-search-forward "[ \t\n]*\\'" nil t) (replace-match "\n"))
1512 ;; Return the expanded template and kill the temporary buffer
1513 (untabify (point-min) (point-max))
1514 (set-buffer-modified-p nil)
1515 (prog1 (buffer-string) (kill-buffer (current-buffer))))))
1517 (defun org-capture-escaped-% ()
1518 "Check if % was escaped - if yes, unescape it now."
1519 (if (equal (char-before (match-beginning 0)) ?\\)
1520 (progn
1521 (delete-region (1- (match-beginning 0)) (match-beginning 0))
1523 nil))
1525 (defun org-capture-expand-embedded-elisp ()
1526 "Evaluate embedded elisp %(sexp) and replace with the result."
1527 (goto-char (point-min))
1528 (while (re-search-forward "%(" nil t)
1529 (unless (org-capture-escaped-%)
1530 (goto-char (match-beginning 0))
1531 (let ((template-start (point)))
1532 (forward-char 1)
1533 (let ((result (org-eval (read (current-buffer)))))
1534 (delete-region template-start (point))
1535 (insert result))))))
1537 (defun org-capture-inside-embedded-elisp-p ()
1538 "Return non-nil if point is inside of embedded elisp %(sexp)."
1539 (let (beg end)
1540 (with-syntax-table emacs-lisp-mode-syntax-table
1541 (save-excursion
1542 (save-match-data
1543 (when (or (looking-at "%(")
1544 (and (search-backward "%" nil t) (looking-at "%(")))
1545 (setq beg (point))
1546 (setq end (progn (forward-char) (forward-sexp) (1- (point)))))))
1547 (when (and beg end)
1548 (and (<= (point) end) (>= (point) beg))))))
1550 ;;;###autoload
1551 (defun org-capture-import-remember-templates ()
1552 "Set org-capture-templates to be similar to `org-remember-templates'."
1553 (interactive)
1554 (when (and (yes-or-no-p
1555 "Import old remember templates into org-capture-templates? ")
1556 (yes-or-no-p
1557 "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
1558 (require 'org-remember)
1559 (setq org-capture-templates
1560 (mapcar
1561 (lambda (entry)
1562 (let ((desc (car entry))
1563 (key (char-to-string (nth 1 entry)))
1564 (template (nth 2 entry))
1565 (file (or (nth 3 entry) org-default-notes-file))
1566 (position (or (nth 4 entry) org-remember-default-headline))
1567 (type 'entry)
1568 (prepend org-reverse-note-order)
1569 immediate target)
1570 (cond
1571 ((member position '(top bottom))
1572 (setq target (list 'file file)
1573 prepend (eq position 'top)))
1574 ((eq position 'date-tree)
1575 (setq target (list 'file+datetree file)
1576 prepend nil))
1577 (t (setq target (list 'file+headline file position))))
1579 (when (string-match "%!" template)
1580 (setq template (replace-match "" t t template)
1581 immediate t))
1583 (append (list key desc type target template)
1584 (if prepend '(:prepend t))
1585 (if immediate '(:immediate-finish t)))))
1587 org-remember-templates))))
1589 (provide 'org-capture)
1591 ;;; org-capture.el ends here