org-babel-exp-lob-one-liners should not parse the entire buffer.
[org-mode.git] / lisp / org-capture.el
blob92f2b81053191a54cd8707b717f511d7c7332d36
1 ;;; org-capture.el --- Fast note taking in Org-mode
3 ;; Copyright (C) 2010-2011 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 preperty 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 (time-to-days prompt-time)))
784 ;; current date, possible corrected for late night workers
785 (org-today))))))
787 ((eq (car target) 'file+function)
788 (set-buffer (org-capture-target-buffer (nth 1 target)))
789 (org-capture-put-target-region-and-position)
790 (widen)
791 (funcall (nth 2 target))
792 (org-capture-put :exact-position (point))
793 (setq target-entry-p (and (eq major-mode 'org-mode) (org-at-heading-p))))
795 ((eq (car target) 'function)
796 (funcall (nth 1 target))
797 (org-capture-put :exact-position (point))
798 (setq target-entry-p (and (eq major-mode 'org-mode) (org-at-heading-p))))
800 ((eq (car target) 'clock)
801 (if (and (markerp org-clock-hd-marker)
802 (marker-buffer org-clock-hd-marker))
803 (progn (set-buffer (marker-buffer org-clock-hd-marker))
804 (org-capture-put-target-region-and-position)
805 (widen)
806 (goto-char org-clock-hd-marker))
807 (error "No running clock that could be used as capture target")))
809 (t (error "Invalid capture target specification")))
811 (org-capture-put :buffer (current-buffer) :pos (point)
812 :target-entry-p target-entry-p))))
814 (defun org-capture-expand-file (file)
815 "Expand functions and symbols for FILE.
816 When FILE is a function, call it. When it is a form, evaluate
817 it. When it is a variable, retrieve the value. Return whatever we get."
818 (cond
819 ((org-string-nw-p file) file)
820 ((functionp file) (funcall file))
821 ((and (symbolp file) (boundp file)) (symbol-value file))
822 ((and file (consp file)) (eval file))
823 (t file)))
825 (defun org-capture-target-buffer (file)
826 "Get a buffer for FILE."
827 (setq file (org-capture-expand-file file))
828 (setq file (or (org-string-nw-p file)
829 org-default-notes-file
830 (error "No notes file specified, and no default available")))
831 (or (org-find-base-buffer-visiting file)
832 (progn (org-capture-put :new-buffer t)
833 (find-file-noselect (expand-file-name file org-directory)))))
835 (defun org-capture-steal-local-variables (buffer)
836 "Install Org-mode local variables."
837 (mapc (lambda (v)
838 (ignore-errors (org-set-local (car v) (cdr v))))
839 (buffer-local-variables buffer)))
841 (defun org-capture-place-template ()
842 "Insert the template at the target location, and display the buffer."
843 (org-capture-put :return-to-wconf (current-window-configuration))
844 (delete-other-windows)
845 (org-switch-to-buffer-other-window
846 (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE"))
847 (widen)
848 (show-all)
849 (goto-char (org-capture-get :pos))
850 (org-set-local 'org-capture-target-marker
851 (move-marker (make-marker) (point)))
852 (org-set-local 'outline-level 'org-outline-level)
853 (let* ((template (org-capture-get :template))
854 (type (org-capture-get :type)))
855 (case type
856 ((nil entry) (org-capture-place-entry))
857 (table-line (org-capture-place-table-line))
858 (plain (org-capture-place-plain-text))
859 (item (org-capture-place-item))
860 (checkitem (org-capture-place-item))))
861 (org-capture-mode 1)
862 (org-set-local 'org-capture-current-plist org-capture-plist))
864 (defun org-capture-place-entry ()
865 "Place the template as a new Org entry."
866 (let* ((txt (org-capture-get :template))
867 (reversed (org-capture-get :prepend))
868 (target-entry-p (org-capture-get :target-entry-p))
869 level beg end file)
871 (cond
872 ((org-capture-get :exact-position)
873 (goto-char (org-capture-get :exact-position)))
874 ((not target-entry-p)
875 ;; Insert as top-level entry, either at beginning or at end of file
876 (setq level 1)
877 (if reversed
878 (progn (goto-char (point-min))
879 (or (org-at-heading-p)
880 (outline-next-heading)))
881 (goto-char (point-max))
882 (or (bolp) (insert "\n"))))
884 ;; Insert as a child of the current entry
885 (and (looking-at "\\*+")
886 (setq level (- (match-end 0) (match-beginning 0))))
887 (setq level (org-get-valid-level (or level 1) 1))
888 (if reversed
889 (progn
890 (outline-next-heading)
891 (or (bolp) (insert "\n")))
892 (org-end-of-subtree t t)
893 (or (bolp) (insert "\n")))))
894 (org-capture-empty-lines-before)
895 (setq beg (point))
896 (org-capture-verify-tree txt)
897 (org-paste-subtree level txt 'for-yank)
898 (org-capture-empty-lines-after 1)
899 (org-capture-position-for-last-stored beg)
900 (outline-next-heading)
901 (setq end (point))
902 (org-capture-mark-kill-region beg (1- end))
903 (org-capture-narrow beg (1- end))
904 (goto-char beg)
905 (if (re-search-forward "%\\?" end t) (replace-match ""))))
907 (defun org-capture-place-item ()
908 "Place the template as a new plain list item."
909 (let* ((txt (org-capture-get :template))
910 (target-entry-p (org-capture-get :target-entry-p))
911 (ind 0)
912 beg end)
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 beg (point-min) end (point-max)))
920 (setq beg (1+ (point-at-eol))
921 end (save-excursion (outline-next-heading) (point)))))
922 (if (org-capture-get :prepend)
923 (progn
924 (goto-char beg)
925 (if (org-list-search-forward (org-item-beginning-re) end t)
926 (progn
927 (goto-char (match-beginning 0))
928 (setq ind (org-get-indentation)))
929 (goto-char end)
930 (setq ind 0)))
931 (goto-char end)
932 (if (org-list-search-backward (org-item-beginning-re) beg t)
933 (progn
934 (setq ind (org-get-indentation))
935 (org-end-of-item))
936 (setq ind 0)))
937 ;; Remove common indentation
938 (setq txt (org-remove-indentation txt))
939 ;; Make sure this is indeed an item
940 (unless (string-match (concat "\\`" (org-item-re)) txt)
941 (setq txt (concat "- "
942 (mapconcat 'identity (split-string txt "\n")
943 "\n "))))
944 ;; Set the correct indentation, depending on context
945 (setq ind (make-string ind ?\ ))
946 (setq txt (concat ind
947 (mapconcat 'identity (split-string txt "\n")
948 (concat "\n" ind))
949 "\n"))
950 ;; Insert, with surrounding empty lines
951 (org-capture-empty-lines-before)
952 (setq beg (point))
953 (insert txt)
954 (or (bolp) (insert "\n"))
955 (org-capture-empty-lines-after 1)
956 (org-capture-position-for-last-stored beg)
957 (forward-char 1)
958 (setq end (point))
959 (org-capture-mark-kill-region beg (1- end))
960 (org-capture-narrow beg (1- end))
961 (if (re-search-forward "%\\?" end t) (replace-match ""))))
963 (defun org-capture-place-table-line ()
964 "Place the template as a table line."
965 (require 'org-table)
966 (let* ((txt (org-capture-get :template))
967 (target-entry-p (org-capture-get :target-entry-p))
968 (table-line-pos (org-capture-get :table-line-pos))
969 ind beg end)
970 (cond
971 ((org-capture-get :exact-position)
972 (goto-char (org-capture-get :exact-position)))
973 ((not target-entry-p)
974 ;; Table is not necessarily under a heading
975 (setq beg (point-min) end (point-max)))
977 ;; WE are at a heading, limit search to the body
978 (setq beg (1+ (point-at-eol))
979 end (save-excursion (outline-next-heading) (point)))))
980 (if (re-search-forward org-table-dataline-regexp end t)
981 (let ((b (org-table-begin)) (e (org-table-end)))
982 (goto-char e)
983 (if (looking-at "[ \t]*#\\+TBLFM:")
984 (forward-line 1))
985 (narrow-to-region b (point)))
986 (goto-char end)
987 (insert "\n| |\n|----|\n| |\n")
988 (narrow-to-region (1+ end) (point)))
989 ;; We are narrowed to the table, or to an empty line if there was no table
991 ;; Check if the template is good
992 (if (not (string-match org-table-dataline-regexp txt))
993 (setq txt "| %?Bad template |\n"))
994 (cond
995 ((and table-line-pos
996 (string-match "\\(I+\\)\\([-+][0-9]\\)" table-line-pos))
997 ;; we have a complex line specification
998 (goto-char (point-min))
999 (let ((nh (- (match-end 1) (match-beginning 1)))
1000 (delta (string-to-number (match-string 2 table-line-pos)))
1002 ;; The user wants a special position in the table
1003 (org-table-get-specials)
1004 (setq ll (ignore-errors (aref org-table-hlines nh)))
1005 (unless ll (error "Invalid table line specification \"%s\""
1006 table-line-pos))
1007 (setq ll (+ ll delta (if (< delta 0) 0 -1)))
1008 (org-goto-line ll)
1009 (org-table-insert-row 'below)
1010 (beginning-of-line 1)
1011 (delete-region (point) (1+ (point-at-eol)))
1012 (setq beg (point))
1013 (insert txt)
1014 (setq end (point))))
1015 ((org-capture-get :prepend)
1016 (goto-char (point-min))
1017 (re-search-forward org-table-hline-regexp nil t)
1018 (beginning-of-line 1)
1019 (re-search-forward org-table-dataline-regexp nil t)
1020 (beginning-of-line 1)
1021 (setq beg (point))
1022 (org-table-insert-row)
1023 (beginning-of-line 1)
1024 (delete-region (point) (1+ (point-at-eol)))
1025 (insert txt)
1026 (setq end (point)))
1028 (goto-char (point-max))
1029 (re-search-backward org-table-dataline-regexp nil t)
1030 (beginning-of-line 1)
1031 (org-table-insert-row 'below)
1032 (beginning-of-line 1)
1033 (delete-region (point) (1+ (point-at-eol)))
1034 (setq beg (point))
1035 (insert txt)
1036 (setq end (point))))
1037 (goto-char beg)
1038 (org-capture-position-for-last-stored 'table-line)
1039 (if (re-search-forward "%\\?" end t) (replace-match ""))
1040 (org-table-align)))
1042 (defun org-capture-place-plain-text ()
1043 "Place the template plainly.
1044 If the target locator points at an Org node, place the template into
1045 the text of the entry, before the first child. If not, place the
1046 template at the beginning or end of the file.
1047 Of course, if exact position has been required, just put it there."
1048 (let* ((txt (org-capture-get :template))
1049 beg end)
1050 (cond
1051 ((org-capture-get :exact-position)
1052 (goto-char (org-capture-get :exact-position)))
1053 ((and (org-capture-get :target-entry-p)
1054 (bolp)
1055 (looking-at org-outline-regexp))
1056 ;; we should place the text into this entry
1057 (if (org-capture-get :prepend)
1058 ;; Skip meta data and drawers
1059 (org-end-of-meta-data-and-drawers)
1060 ;; go to ent of the entry text, before the next headline
1061 (outline-next-heading)))
1063 ;; beginning or end of file
1064 (goto-char (if (org-capture-get :prepend) (point-min) (point-max)))))
1065 (or (bolp) (newline))
1066 (org-capture-empty-lines-before)
1067 (setq beg (point))
1068 (insert txt)
1069 (org-capture-empty-lines-after 1)
1070 (org-capture-position-for-last-stored beg)
1071 (setq end (point))
1072 (org-capture-mark-kill-region beg (1- end))
1073 (org-capture-narrow beg (1- end))
1074 (if (re-search-forward "%\\?" end t) (replace-match ""))))
1076 (defun org-capture-mark-kill-region (beg end)
1077 "Mark the region that will have to be killed when aborting capture."
1078 (let ((m1 (move-marker (make-marker) beg))
1079 (m2 (move-marker (make-marker) end)))
1080 (org-capture-put :begin-marker m1)
1081 (org-capture-put :end-marker m2)))
1083 (defun org-capture-position-for-last-stored (where)
1084 "Memorize the position that should later become the position of last capture."
1085 (cond
1086 ((integerp where)
1087 (org-capture-put :position-for-last-stored
1088 (move-marker (make-marker) where
1089 (or (buffer-base-buffer (current-buffer))
1090 (current-buffer)))))
1091 ((eq where 'table-line)
1092 (org-capture-put :position-for-last-stored
1093 (list 'table-line
1094 (org-table-current-dline))))
1095 (t (error "This should not happen"))))
1097 (defun org-capture-bookmark-last-stored-position ()
1098 "Bookmark the last-captured position."
1099 (let* ((where (org-capture-get :position-for-last-stored 'local))
1100 (pos (cond
1101 ((markerp where)
1102 (prog1 (marker-position where)
1103 (move-marker where nil)))
1104 ((and (listp where) (eq (car where) 'table-line))
1105 (if (org-at-table-p)
1106 (save-excursion
1107 (org-table-goto-line (nth 1 where))
1108 (point-at-bol))
1109 (point))))))
1110 (with-current-buffer (buffer-base-buffer (current-buffer))
1111 (save-excursion
1112 (save-restriction
1113 (widen)
1114 (goto-char pos)
1115 (bookmark-set "org-capture-last-stored")
1116 (move-marker org-capture-last-stored-marker (point)))))))
1118 (defun org-capture-narrow (beg end)
1119 "Narrow, unless configuration says not to narrow."
1120 (unless (org-capture-get :unnarrowed)
1121 (narrow-to-region beg end)
1122 (goto-char beg)))
1124 (defun org-capture-empty-lines-before (&optional n)
1125 "Arrange for the correct number of empty lines before the insertion point.
1126 Point will be after the empty lines, so insertion can directly be done."
1127 (setq n (or n (org-capture-get :empty-lines) 0))
1128 (let ((pos (point)))
1129 (org-back-over-empty-lines)
1130 (delete-region (point) pos)
1131 (if (> n 0) (newline n))))
1133 (defun org-capture-empty-lines-after (&optional n)
1134 "Arrange for the correct number of empty lines after the inserted string.
1135 Point will remain at the first line after the inserted text."
1136 (setq n (or n (org-capture-get :empty-lines) 0))
1137 (org-back-over-empty-lines)
1138 (while (looking-at "[ \t]*\n") (replace-match ""))
1139 (let ((pos (point)))
1140 (if (> n 0) (newline n))
1141 (goto-char pos)))
1143 (defvar org-clock-marker) ; Defined in org.el
1144 ;;;###autoload
1145 (defun org-capture-insert-template-here ()
1146 (let* ((template (org-capture-get :template))
1147 (type (org-capture-get :type))
1148 beg end pp)
1149 (or (bolp) (newline))
1150 (setq beg (point))
1151 (cond
1152 ((and (eq type 'entry) (eq major-mode 'org-mode))
1153 (org-capture-verify-tree (org-capture-get :template))
1154 (org-paste-subtree nil template t))
1155 ((and (memq type '(item checkitem))
1156 (eq major-mode 'org-mode)
1157 (save-excursion (skip-chars-backward " \t\n")
1158 (setq pp (point))
1159 (org-in-item-p)))
1160 (goto-char pp)
1161 (org-insert-item)
1162 (skip-chars-backward " ")
1163 (skip-chars-backward "-+*0123456789).")
1164 (delete-region (point) (point-at-eol))
1165 (setq beg (point))
1166 (org-remove-indentation template)
1167 (insert template)
1168 (org-capture-empty-lines-after)
1169 (goto-char beg)
1170 (org-list-repair)
1171 (org-end-of-item)
1172 (setq end (point)))
1173 (t (insert template)))
1174 (setq end (point))
1175 (goto-char beg)
1176 (if (re-search-forward "%\\?" end t)
1177 (replace-match ""))))
1179 (defun org-capture-set-plist (entry)
1180 "Initialize the property list from the template definition."
1181 (setq org-capture-plist (copy-sequence (nthcdr 5 entry)))
1182 (org-capture-put :key (car entry) :description (nth 1 entry)
1183 :target (nth 3 entry))
1184 (let ((txt (nth 4 entry)) (type (or (nth 2 entry) 'entry)))
1185 (when (or (not txt) (and (stringp txt) (not (string-match "\\S-" txt))))
1186 ;; The template may be empty or omitted for special types.
1187 ;; Here we insert the default templates for such cases.
1188 (cond
1189 ((eq type 'item) (setq txt "- %?"))
1190 ((eq type 'checkitem) (setq txt "- [ ] %?"))
1191 ((eq type 'table-line) (setq txt "| %? |"))
1192 ((member type '(nil entry)) (setq txt "* %?\n %a"))))
1193 (org-capture-put :template txt :type type)))
1195 (defun org-capture-goto-target (&optional template-key)
1196 "Go to the target location of a capture template.
1197 The user is queried for the template."
1198 (interactive)
1199 (let* (org-select-template-temp-major-mode
1200 (entry (org-capture-select-template template-key)))
1201 (unless entry
1202 (error "No capture template selected"))
1203 (org-capture-set-plist entry)
1204 (org-capture-set-target-location)
1205 (org-pop-to-buffer-same-window (org-capture-get :buffer))
1206 (goto-char (org-capture-get :pos))))
1208 (defun org-capture-get-indirect-buffer (&optional buffer prefix)
1209 "Make an indirect buffer for a capture process.
1210 Use PREFIX as a prefix for the name of the indirect buffer."
1211 (setq buffer (or buffer (current-buffer)))
1212 (let ((n 1) (base (buffer-name buffer)) bname)
1213 (setq bname (concat prefix "-" base))
1214 (while (buffer-live-p (get-buffer bname))
1215 (setq bname (concat prefix "-" (number-to-string (incf n)) "-" base)))
1216 (condition-case nil
1217 (make-indirect-buffer buffer bname 'clone)
1218 (error
1219 (let ((buf (make-indirect-buffer buffer bname)))
1220 (with-current-buffer buf (org-mode))
1221 buf)))))
1223 (defun org-capture-verify-tree (tree)
1224 "Throw error if TREE is not a valid tree"
1225 (unless (org-kill-is-subtree-p tree)
1226 (error "Template is not a valid Org entry or tree")))
1228 ;;; The template code
1230 (defun org-capture-select-template (&optional keys)
1231 "Select a capture template.
1232 Lisp programs can force the template by setting KEYS to a string."
1233 (let ((org-capture-templates
1234 (or org-capture-templates
1235 '(("t" "Task" entry (file+headline "" "Tasks")
1236 "* TODO %?\n %u\n %a")))))
1237 (if keys
1238 (or (assoc keys org-capture-templates)
1239 (error "No capture template referred to by \"%s\" keys" keys))
1240 (org-mks org-capture-templates
1241 "Select a capture template\n========================="
1242 "Template key: "
1243 '(("C" "Customize org-capture-templates")
1244 ("q" "Abort"))))))
1246 (defun org-capture-fill-template (&optional template initial annotation)
1247 "Fill a template and return the filled template as a string.
1248 The template may still contain \"%?\" for cursor positioning."
1249 (setq template (or template (org-capture-get :template)))
1250 (when (stringp initial)
1251 (setq initial (org-no-properties initial))
1252 (remove-text-properties 0 (length initial) '(read-only t) initial))
1253 (let* ((buffer (org-capture-get :buffer))
1254 (file (buffer-file-name (or (buffer-base-buffer buffer) buffer)))
1255 (ct (org-capture-get :default-time))
1256 (dct (decode-time ct))
1257 (ct1
1258 (if (< (nth 2 dct) org-extend-today-until)
1259 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
1260 ct))
1261 (plist-p (if org-store-link-plist t nil))
1262 (v-c (and (> (length kill-ring) 0) (current-kill 0)))
1263 (v-x (or (org-get-x-clipboard 'PRIMARY)
1264 (org-get-x-clipboard 'CLIPBOARD)
1265 (org-get-x-clipboard 'SECONDARY)))
1266 (v-t (format-time-string (car org-time-stamp-formats) ct))
1267 (v-T (format-time-string (cdr org-time-stamp-formats) ct))
1268 (v-u (concat "[" (substring v-t 1 -1) "]"))
1269 (v-U (concat "[" (substring v-T 1 -1) "]"))
1270 ;; `initial' and `annotation' might habe been passed.
1271 ;; But if the property list has them, we prefer those values
1272 (v-i (or (plist-get org-store-link-plist :initial)
1273 initial
1274 (org-capture-get :initial)
1275 ""))
1276 (v-a (or (plist-get org-store-link-plist :annotation)
1277 annotation
1278 (org-capture-get :annotation)
1279 ""))
1280 ;; Is the link empty? Then we do not want it...
1281 (v-a (if (equal v-a "[[]]") "" v-a))
1282 (clipboards (remove nil (list v-i
1283 (org-get-x-clipboard 'PRIMARY)
1284 (org-get-x-clipboard 'CLIPBOARD)
1285 (org-get-x-clipboard 'SECONDARY)
1286 v-c)))
1287 (v-A (if (and v-a
1288 (string-match
1289 "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
1290 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
1291 v-a))
1292 (v-n user-full-name)
1293 (v-k (if (marker-buffer org-clock-marker)
1294 (org-substring-no-properties org-clock-heading)))
1295 (v-K (if (marker-buffer org-clock-marker)
1296 (org-make-link-string
1297 (buffer-file-name (marker-buffer org-clock-marker))
1298 org-clock-heading)))
1299 (v-f (or (org-capture-get :original-file-nondirectory) ""))
1300 (v-F (or (org-capture-get :original-file) ""))
1302 (org-startup-folded nil)
1303 (org-inhibit-startup t)
1304 org-time-was-given org-end-time-was-given x
1305 prompt completions char time pos default histvar)
1307 (setq org-store-link-plist
1308 (plist-put org-store-link-plist :annotation v-a)
1309 org-store-link-plist
1310 (plist-put org-store-link-plist :initial v-i))
1311 (setq initial v-i)
1313 (unless template (setq template "") (message "No template") (ding)
1314 (sit-for 1))
1315 (save-window-excursion
1316 (delete-other-windows)
1317 (org-pop-to-buffer-same-window (get-buffer-create "*Capture*"))
1318 (erase-buffer)
1319 (insert template)
1320 (goto-char (point-min))
1321 (org-capture-steal-local-variables buffer)
1322 (setq buffer-file-name nil)
1324 ;; %[] Insert contents of a file.
1325 (goto-char (point-min))
1326 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
1327 (unless (org-capture-escaped-%)
1328 (let ((start (match-beginning 0))
1329 (end (match-end 0))
1330 (filename (expand-file-name (match-string 1))))
1331 (goto-char start)
1332 (delete-region start end)
1333 (condition-case error
1334 (insert-file-contents filename)
1335 (error (insert (format "%%![Couldn't insert %s: %s]"
1336 filename error)))))))
1337 ;; %() embedded elisp
1338 (goto-char (point-min))
1339 (while (re-search-forward "%\\((.+)\\)" nil t)
1340 (unless (org-capture-escaped-%)
1341 (goto-char (match-beginning 0))
1342 (let ((template-start (point)))
1343 (forward-char 1)
1344 (let ((result (org-eval (read (current-buffer)))))
1345 (delete-region template-start (point))
1346 (insert result)))))
1348 ;; The current time
1349 (goto-char (point-min))
1350 (while (re-search-forward "%<\\([^>\n]+\\)>" nil t)
1351 (replace-match (format-time-string (match-string 1)) t t))
1353 ;; Simple %-escapes
1354 (goto-char (point-min))
1355 (while (re-search-forward "%\\([tTuUaiAcxkKInfF]\\)" nil t)
1356 (unless (org-capture-escaped-%)
1357 (when (and initial (equal (match-string 0) "%i"))
1358 (save-match-data
1359 (let* ((lead (buffer-substring
1360 (point-at-bol) (match-beginning 0))))
1361 (setq v-i (mapconcat 'identity
1362 (org-split-string initial "\n")
1363 (concat "\n" lead))))))
1364 (replace-match
1365 (or (eval (intern (concat "v-" (match-string 1)))) "")
1366 t t)))
1368 ;; From the property list
1369 (when plist-p
1370 (goto-char (point-min))
1371 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
1372 (unless (org-capture-escaped-%)
1373 (and (setq x (or (plist-get org-store-link-plist
1374 (intern (match-string 1))) ""))
1375 (replace-match x t t)))))
1377 ;; Turn on org-mode in temp buffer, set local variables
1378 ;; This is to support completion in interactive prompts
1379 (let ((org-inhibit-startup t)) (org-mode))
1380 ;; Interactive template entries
1381 (goto-char (point-min))
1382 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGtTuUCLp]\\)?"
1383 nil t)
1384 (unless (org-capture-escaped-%)
1385 (setq char (if (match-end 3) (match-string-no-properties 3))
1386 prompt (if (match-end 2) (match-string-no-properties 2)))
1387 (goto-char (match-beginning 0))
1388 (replace-match "")
1389 (setq completions nil default nil)
1390 (when prompt
1391 (setq completions (org-split-string prompt "|")
1392 prompt (pop completions)
1393 default (car completions)
1394 histvar (intern (concat
1395 "org-capture-template-prompt-history::"
1396 (or prompt "")))
1397 completions (mapcar 'list completions)))
1398 (unless (boundp histvar) (set histvar nil))
1399 (cond
1400 ((member char '("G" "g"))
1401 (let* ((org-last-tags-completion-table
1402 (org-global-tags-completion-table
1403 (if (equal char "G")
1404 (org-agenda-files)
1405 (and file (list file)))))
1406 (org-add-colon-after-tag-completion t)
1407 (ins (org-icompleting-read
1408 (if prompt (concat prompt ": ") "Tags: ")
1409 'org-tags-completion-function nil nil nil
1410 'org-tags-history)))
1411 (setq ins (mapconcat 'identity
1412 (org-split-string
1413 ins (org-re "[^[:alnum:]_@#%]+"))
1414 ":"))
1415 (when (string-match "\\S-" ins)
1416 (or (equal (char-before) ?:) (insert ":"))
1417 (insert ins)
1418 (or (equal (char-after) ?:) (insert ":"))
1419 (and (org-on-heading-p) (org-set-tags nil 'align)))))
1420 ((equal char "C")
1421 (cond ((= (length clipboards) 1) (insert (car clipboards)))
1422 ((> (length clipboards) 1)
1423 (insert (read-string "Clipboard/kill value: "
1424 (car clipboards) '(clipboards . 1)
1425 (car clipboards))))))
1426 ((equal char "L")
1427 (cond ((= (length clipboards) 1)
1428 (org-insert-link 0 (car clipboards)))
1429 ((> (length clipboards) 1)
1430 (org-insert-link 0 (read-string "Clipboard/kill value: "
1431 (car clipboards)
1432 '(clipboards . 1)
1433 (car clipboards))))))
1434 ((equal char "p")
1435 (org-set-property (org-substring-no-properties prompt) nil))
1436 (char
1437 ;; These are the date/time related ones
1438 (setq org-time-was-given (equal (upcase char) char))
1439 (setq time (org-read-date (equal (upcase char) char) t nil
1440 prompt))
1441 (if (equal (upcase char) char) (setq org-time-was-given t))
1442 (org-insert-time-stamp time org-time-was-given
1443 (member char '("u" "U"))
1444 nil nil (list org-end-time-was-given)))
1446 (let (org-completion-use-ido)
1447 (insert (org-completing-read-no-i
1448 (concat (if prompt prompt "Enter string")
1449 (if default (concat " [" default "]"))
1450 ": ")
1451 completions nil nil nil histvar default)))))))
1452 ;; Make sure there are no empty lines before the text, and that
1453 ;; it ends with a newline character
1454 (goto-char (point-min))
1455 (while (looking-at "[ \t]*\n") (replace-match ""))
1456 (if (re-search-forward "[ \t\n]*\\'" nil t) (replace-match "\n"))
1457 ;; Return the expanded tempate and kill the temporary buffer
1458 (untabify (point-min) (point-max))
1459 (set-buffer-modified-p nil)
1460 (prog1 (buffer-string) (kill-buffer (current-buffer))))))
1462 (defun org-capture-escaped-% ()
1463 "Check if % was escaped - if yes, unescape it now."
1464 (if (equal (char-before (match-beginning 0)) ?\\)
1465 (progn
1466 (delete-region (1- (match-beginning 0)) (match-beginning 0))
1468 nil))
1470 ;;;###autoload
1471 (defun org-capture-import-remember-templates ()
1472 "Set org-capture-templates to be similar to `org-remember-templates'."
1473 (interactive)
1474 (when (and (yes-or-no-p
1475 "Import old remember templates into org-capture-templates? ")
1476 (yes-or-no-p
1477 "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
1478 (require 'org-remember)
1479 (setq org-capture-templates
1480 (mapcar
1481 (lambda (entry)
1482 (let ((desc (car entry))
1483 (key (char-to-string (nth 1 entry)))
1484 (template (nth 2 entry))
1485 (file (or (nth 3 entry) org-default-notes-file))
1486 (position (or (nth 4 entry) org-remember-default-headline))
1487 (type 'entry)
1488 (prepend org-reverse-note-order)
1489 immediate target)
1490 (cond
1491 ((member position '(top bottom))
1492 (setq target (list 'file file)
1493 prepend (eq position 'top)))
1494 ((eq position 'date-tree)
1495 (setq target (list 'file+datetree file)
1496 prepend nil))
1497 (t (setq target (list 'file+headline file position))))
1499 (when (string-match "%!" template)
1500 (setq template (replace-match "" t t template)
1501 immediate t))
1503 (append (list key desc type target template)
1504 (if prepend '(:prepend t))
1505 (if immediate '(:immediate-finish t)))))
1507 org-remember-templates))))
1509 (provide 'org-capture)
1511 ;;; org-capture.el ends here