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