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