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