Org Capture: Make ?q abort, and allow to specify the line position in table
[org-mode.git] / lisp / org-capture.el
blobbaeab6e7b3b619c419892772f52f1864d00a3e94
1 ;;; org-capture.el --- Fast note taking in Org-mode
3 ;; Copyright (C) 2010 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 ;; Version: 6.36trans
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; This file contains an alternaive implementation of the same functionality
29 ;; that is also provided by org-remember.el. The implementation is more
30 ;; streamlined, can produce more target types (e.g. plain list items or
31 ;; table lines). Also, it does not use a temporary buffer for editing
32 ;; the captured entry - instead it uses an indirect buffer that visits
33 ;; the new entry already in the target buffer (this was an idea by Samuel
34 ;; Wales). John Wiegley's excellent `remember.el' is not needed for this
35 ;; implementation, even though we borrow heavily from its ideas.
37 ;; This implementation heavily draws on ideas by James TD Smith and
38 ;; Samuel Wales, and, of cause, uses John Wiegley's remember.el as inspiration.
40 ;;; TODO
42 ;; - find a clever way to not always insert an annotation maybe a
43 ;; predicate function that can check for conditions for %a to be
44 ;; used. This could be one of the properties.
46 ;; - Should there be plist members that arrange for properties to be
47 ;; asked for, like James proposed in his RFC?
49 ;;; Code:
51 (eval-when-compile
52 (require 'cl))
53 (require 'org)
54 (require 'org-mks)
56 (declare-function org-datetree-find-date-create "org-datetree"
57 (DATE &optional KEEP-RESTRICTION))
58 (defvar org-remember-default-headline)
59 (defvar org-remember-templates)
61 (defvar org-capture-clock-was-started nil
62 "Internal flag, noting if the clock was started.")
64 (defvar org-capture-last-stored-marker (make-marker)
65 "Marker pointing to the entry most recently stored with `org-capture'.")
67 ;; The following variable is scoped dynamically by org-protocol
68 ;; to indicate that the link properties have already been stored
69 (defvar org-capture-link-is-already-stored nil)
71 (defgroup org-capture nil
72 "Options concerning capturing new entries."
73 :tag "Org Capture"
74 :group 'org)
76 (defcustom org-capture-templates nil
77 "Templates for the creation of new entries.
79 Each entry is a list with the following items:
81 keys The keys that will select the template, as a string, characters
82 only, for example \"a\" for a template to be selected with a
83 single key, or \"bt\" for selection with two keys. When using
84 several keys, keys using the same prefix key must be together
85 in the list and preceded by a 2-element entry explaining the
86 prefix key, for example
88 (\"b\" \"Templates for marking stuff to buy\")
90 The \"C\" key is used by default for quick access to the
91 customization of the template variable. But if you want to use
92 that key for a template, you can.
94 description A short string describing the template, will be shown during
95 selection.
97 type The type of entry. Valid are:
98 entry an Org-mode node, with a headline. Will be
99 filed as the child of the target entry or as
100 a top-level entry.
101 item a plain list item, placed in the first plain
102 list a the target location.
103 checkitem a checkbox item. This only differs from the
104 plain lis item by the default template.
105 table-line a new line in the first table at target location.
106 plain text to be inserted as it is.
108 target Specification of where the captured item should be placed.
109 In Org-mode files, targets usually define a node. Entries will
110 become children of this node, other types will be added to the
111 table or list in the body of this node.
113 Valid values are:
115 (file \"path/to/file\")
116 Text will be placed at the beginning or end of that file
118 (id \"id of existing org entry\")
119 Filing as child of this entry, or in the body of the entry
121 (file+headline \"path/to/file\" \"node headline\")
122 Fast configuration if the target heading is unique in the file
124 (file+olp \"path/to/file\" \"Level 1 heading\" \"Level 2\" ...)
125 For non-unique headings, the full path is safer
127 (file+regexp \"path/to/file\" \"regexp to find location\")
129 (file+datetree \"path/to/file\")
130 Will create a heading in a date tree.
132 (file+function \"path/to/file\" function-finding-location)
133 A function to find the right location in the file.
135 (clock)
136 File to the entry that is currently being clocked.
138 (function function-finding-location)
139 Most general way, write your own function to find both
140 file and location.
143 template The template for creating the capture item. If you leave this
144 empty, an appropriate default template will be used. See below
145 for more details.
147 The rest of the entry is a property list of additional options. Recognized
148 properties are:
150 :prepend Normally new captured information will be appended at
151 the target location (last child, last table line,
152 last list item...). Setting this property will
153 change that.
155 :immediate-finish When set, do not offer to edit the information, just
156 file it away immediately. This makes sense if the
157 template only needs information that can be added
158 automatically.
160 :empty-lines Set this to the number of lines the should be inserted
161 before and after the new item. Default 0, only common
162 other value is 1.
164 :clock-in Start the clock in this item.
166 :clock-resume Start the interrupted clock when finishing the capture.
168 :unnarrowed Do not narrow the target buffer, simply show the
169 full buffer. Default is to narrow it so that you
170 only see the new stuff.
172 :table-line-pos Specification of the location in the table where the
173 new line should be inserted. It looks like \"II-3\"
174 which means that the new line should become the third
175 line before the second horizontal separaor line.
177 The template defined the text to be inserted. Often then this is an org-mode
178 entry (so the first line should start with a star) that will be filed as a
179 child of the target headline. It can also be freely formatted text.
180 Furthermore, the following %-escapes will be replaced with content:
182 %^{prompt} Prompt the user for a string and replace this sequence with it.
183 A default value and a completion table ca be specified like this:
184 %^{prompt|default|completion2|completion3|...}
185 %t time stamp, date only
186 %T time stamp with date and time
187 %u, %U like the above, but inactive time stamps
188 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U.
189 You may define a prompt like %^{Please specify birthday
190 %n user name (taken from `user-full-name')
191 %a annotation, normally the link created with `org-store-link'
192 %i initial content, copied from the active region. If %i is
193 indented, the entire inserted text will be indented as well.
194 %c current kill ring head
195 %x content of the X clipboard
196 %^C Interactive selection of which kill or clip to use
197 %^L Like %^C, but insert as link
198 %k title of currently clocked task
199 %K link to currently clocked task
200 %^g prompt for tags, with completion on tags in target file
201 %^G prompt for tags, with completion all tags in all agenda files
202 %^{prop}p Prompt the user for a value for property `prop'
203 %:keyword specific information for certain link types, see below
204 %[pathname] insert the contents of the file given by `pathname'
205 %(sexp) evaluate elisp `(sexp)' and replace with the result
207 %? After completing the template, position cursor here.
209 Apart from these general escapes, you can access information specific to the
210 link type that is created. For example, calling `org-capture' in emails
211 or gnus will record the author and the subject of the message, which you
212 can access with \"%:author\" and \"%:subject\", respectively. Here is a
213 complete list of what is recorded for each link type.
215 Link type | Available information
216 -------------------+------------------------------------------------------
217 bbdb | %:type %:name %:company
218 vm, wl, mh, rmail | %:type %:subject %:message-id
219 | %:from %:fromname %:fromaddress
220 | %:to %:toname %:toaddress
221 | %:fromto (either \"to NAME\" or \"from NAME\")
222 gnus | %:group, for messages also all email fields
223 w3, w3m | %:type %:url
224 info | %:type %:file %:node
225 calendar | %:type %:date"
226 :group 'org-capture
227 :type
228 '(repeat
229 (choice :value ("" "" entry (file "~/org/notes.org") "")
230 (list :tag "Multikey description"
231 (string :tag "Keys ")
232 (string :tag "Description"))
233 (list :tag "Template entry"
234 (string :tag "Keys ")
235 (string :tag "Description ")
236 (choice :tag "Capture Type " :value entry
237 (const :tag "Org entry" entry)
238 (const :tag "Plain list item" item)
239 (const :tag "Checkbox item" checkitem)
240 (const :tag "Plain text" plain)
241 (const :tag "Table line" table-line))
242 (choice :tag "Target location"
243 (list :tag "File"
244 (const :format "" file)
245 (file :tag " File"))
246 (list :tag "ID"
247 (const :format "" id)
248 (string :tag " ID"))
249 (list :tag "File & Headline"
250 (const :format "" file+headline)
251 (file :tag " File ")
252 (string :tag " Headline"))
253 (list :tag "File & Outline path"
254 (const :format "" file+olp)
255 (file :tag " File ")
256 (repeat :tag "Outline path" :inline t
257 (string :tag "Headline")))
258 (list :tag "File & Regexp"
259 (const :format "" file+regexp)
260 (file :tag " File ")
261 (regexp :tag " Regexp"))
262 (list :tag "File & Date tree"
263 (const :format "" file+datetree)
264 (file :tag " File"))
265 (list :tag "File & function"
266 (const :format "" file+function)
267 (file :tag " File ")
268 (sexp :tag " Function"))
269 (list :tag "Current clocking task"
270 (const :format "" clock))
271 (list :tag "Function"
272 (const :format "" function)
273 (sexp :tag " Function")))
274 (string :tag "Template (opt) ")
275 (plist :inline t
276 ;; Give the most common options as checkboxes
277 :options (((const :format "%v " :prepend) (const t))
278 ((const :format "%v " :immediate-finish) (const t))
279 ((const :format "%v " :empty-lines) (const 1))
280 ((const :format "%v " :clock-in) (const t))
281 ((const :format "%v " :clock-resume) (const t))
282 ((const :format "%v " :unnarrowed) (const t))))))))
284 (defcustom org-capture-before-finalize-hook nil
285 "Hook that is run right before a remember process is finalized.
286 The remember buffer is still current when this hook runs."
287 :group 'org-capture
288 :type 'hook)
290 ;;; The property list for keeping information about the capture process
292 (defvar org-capture-plist nil
293 "Plist for the current capture process, global, to avoid having to pass it.")
294 (defvar org-capture-current-plist nil
295 "Local variable holding the plist in a capture buffer.
296 This is used to store the plist for use when finishing a capture process.
297 Another such process might have changed the global varaible by then.")
299 (defun org-capture-put (&rest stuff)
300 (while stuff
301 (setq org-capture-plist (plist-put org-capture-plist
302 (pop stuff) (pop stuff)))))
303 (defun org-capture-get (prop &optional local)
304 (plist-get (if local org-capture-current-plist org-capture-plist) prop))
306 (defun org-capture-member (prop)
307 (plist-get org-capture-plist prop))
309 ;;; The minor mode
311 (defvar org-capture-mode-map (make-sparse-keymap)
312 "Keymap for org-capture-mode, a minor mode.
313 Use this map to set additional keybindings for when Org-mode is used
314 for a Remember buffer.")
316 (defvar org-capture-mode-hook nil
317 "Hook for the minor `org-capture-mode'.")
319 (define-minor-mode org-capture-mode
320 "Minor mode for special key bindings in a remember buffer."
321 nil " Rem" org-capture-mode-map
322 (org-set-local
323 'header-line-format
324 "Capture buffer. Finish `C-c C-c', refile `C-c C-w', abort `C-c C-k'.")
325 (run-hooks 'org-capture-mode-hook))
326 (define-key org-capture-mode-map "\C-c\C-c" 'org-capture-finalize)
327 (define-key org-capture-mode-map "\C-c\C-k" 'org-capture-kill)
328 (define-key org-capture-mode-map "\C-c\C-w" 'org-capture-refile)
330 ;;; The main commands
332 ;;;###autoload
333 (defun org-capture (&optional goto keys)
334 "Capture something.
336 This will let you select a template from org-capture-templates, and then
337 file new captured information. The text is immediately inserted at the
338 target location, and an indirect buffer is shown where you can edit it.
339 Pressing `C-c C-c' brings you back to the previous state of Emacs,
340 so that you can continue your work.
342 When called interactively with a `C-u' prefix argument GOTO, don't capture
343 anything, just go to the file/headline where the selected template
344 stores its notes. With a double prefix arg `C-u C-u', go to the last
345 note stored.
347 When called with a `C-0' (zero) prefix, insert a template at point.
349 Lisp programs can set KEYS to a string associated with a template in
350 `org-capture-templates'. In this case, interactive selection will be
351 bypassed."
352 (interactive "P")
353 (cond
354 ((equal goto '(4)) (org-capture-goto-target))
355 ((equal goto '(16)) (org-capture-goto-last-stored))
357 ;; set temporary variables that will be needed in
358 ;; `org-select-remember-template'
359 (let* ((orig-buf (current-buffer))
360 (annotation (if org-capture-link-is-already-stored
361 (plist-get org-store-link-plist :annotation)
362 (org-store-link nil)))
363 (initial (and (org-region-active-p)
364 (buffer-substring (point) (mark))))
365 (entry (org-capture-select-template keys)))
366 (cond
367 ((equal entry "C")
368 (customize-variable 'org-capture-templates))
369 ((equal entry "q")
370 (error "Abort"))
372 (org-capture-set-plist entry)
373 (org-capture-put :original-buffer orig-buf :annotation annotation
374 :initial initial)
375 (org-capture-put :default-time
376 (or org-overriding-default-time
377 (org-current-time)))
378 (org-capture-set-target-location)
379 (org-capture-put :template (org-capture-fill-template))
380 (if (equal goto 0)
381 ;;insert at point
382 (org-capture-insert-template-here)
383 (org-capture-place-template)
384 (if (org-capture-get :immediate-finish)
385 (org-capture-finalize)
386 (if (and (org-mode-p)
387 (org-capture-get :clock-in))
388 (condition-case nil
389 (progn
390 (if (org-clock-is-active)
391 (org-capture-put :interrupted-clock
392 (copy-marker org-clock-marker)))
393 (org-clock-in)
394 (org-set-local 'org-capture-clock-was-started t))
395 (error
396 "Could not start the clock in this capture buffer")))))))))))
398 (defun org-capture-finalize ()
399 "Finalize the capture process."
400 (interactive)
401 (unless (and org-capture-mode
402 (buffer-base-buffer (current-buffer)))
403 (error "This does not seem to be a capture buffer for Org-mode"))
405 ;; Did we start the clock in this capture buffer?
406 (when (and org-capture-clock-was-started
407 org-clock-marker (marker-buffer org-clock-marker)
408 (equal (marker-buffer org-clock-marker) (buffer-base-buffer))
409 (> org-clock-marker (point-min))
410 (< org-clock-marker (point-max)))
411 ;; Looks like the clock we started is still running. Clock out.
412 (let (org-log-note-clock-out) (org-clock-out))
413 (when (and (org-capture-get :clock-resume 'local)
414 (markerp (org-capture-get :interrupted-clock 'local))
415 (buffer-live-p (marker-buffer
416 (org-capture-get :interrupted-clock 'local))))
417 (org-with-point-at (org-capture-get :interrupted-clock 'local)
418 (org-clock-in))
419 (message "Interrupted clock has been resumed")))
421 (let ((beg (point-min))
422 (end (point-max))
423 (abort-note nil))
424 (widen)
426 (if org-note-abort
427 (let ((m1 (org-capture-get :begin-marker 'local))
428 (m2 (org-capture-get :end-marker 'local)))
429 (if (and m1 m2 (= m1 beg) (= m2 end))
430 (progn
431 (setq abort-note 'clean)
432 (kill-region m1 m2))
433 (setq abort-note 'dirty)))
435 ;; Make sure that the empty lines after are correct
436 (when (and (> (point-max) end) ; indeed, the buffer was still narrowed
437 (member (org-capture-get :type 'local)
438 '(entry item checkitem plain)))
439 (save-excursion
440 (goto-char end)
441 (org-capture-empty-lines-after
442 (or (org-capture-get :empty-lines 'local) 0))))
443 ;; Postprocessing: Update Statistics cookies, do the sorting
444 (when (org-mode-p)
445 (save-excursion
446 (when (ignore-errors (org-back-to-heading))
447 (org-update-parent-todo-statistics)
448 (org-update-checkbox-count)))
449 ;; FIXME Here we should do the sorting
450 ;; If we have added a table line, maybe recompute?
451 (when (and (eq (org-capture-get :type 'local) 'table-line)
452 (org-at-table-p))
453 (if (org-table-get-stored-formulas)
454 (org-table-recalculate 'all) ;; FIXME: Should we iterate???
455 (org-table-align)))
457 ;; Store this place as the last one where we stored something
458 ;; Do the marking in the base buffer, so that it makes sense after
459 ;; the indirect buffer has been killed.
460 (let ((pos (point)))
461 (with-current-buffer (buffer-base-buffer (current-buffer))
462 (save-excursion
463 (save-restriction
464 (widen)
465 (goto-char pos)
466 (bookmark-set "org-capture-last-stored")
467 (move-marker org-capture-last-stored-marker (point))))))
468 ;; Run the hook
469 (run-hooks 'org-capture-before-finalize-hook)
472 ;; Kill the indirect buffer
473 (save-buffer)
474 (let ((return-wconf (org-capture-get :return-to-wconf 'local)))
475 (kill-buffer (current-buffer))
476 ;; Restore the window configuration before capture
477 (set-window-configuration return-wconf))
478 (when abort-note
479 (cond
480 ((equal abort-note 'clean)
481 (message "Capture process aborted and target file cleaned up"))
482 ((equal abort-note 'dirty)
483 (error "Capture process aborted, but target buffer could not be cleaned up correctly"))))))
485 (defun org-capture-refile ()
486 "Finalize the current capture and then refile the entry.
487 Refiling is done from the base buffer, because the indirect buffer is then
488 already gone."
489 (interactive)
490 (unless (eq (org-capture-get :type 'local) 'entry)
491 (error
492 "Refiling from a capture buffer makes only sense for `entry'-type templates"))
493 (let ((pos (point)) (base (buffer-base-buffer (current-buffer))))
494 (org-capture-finalize)
495 (save-window-excursion
496 (with-current-buffer (or base (current-buffer))
497 (save-excursion
498 (save-restriction
499 (widen)
500 (goto-char pos)
501 (call-interactively 'org-refile)))))))
503 (defun org-capture-kill ()
504 "Abort the current capture process."
505 (interactive)
506 ;; FIXME: This does not do the right thing, we need to remove the new stuff
507 ;; By hand it is easy: undo, then kill the buffer
508 (let ((org-note-abort t) (org-capture-before-finalize-hook nil))
509 (org-capture-finalize)))
511 (defun org-capture-goto-last-stored ()
512 "Go to the location where the last remember note was stored."
513 (interactive)
514 (org-goto-marker-or-bmk org-capture-last-stored-marker
515 "org-capture-last-stored")
516 (message "This is the last note stored by a capture process"))
518 ;;; Supporting functions for handling the process
520 (defun org-capture-set-target-location (&optional target)
521 "Find target buffer and position and store then in the property list."
522 (let ((target-entry-p t))
523 (setq target (or target (org-capture-get :target)))
524 (save-excursion
525 (cond
526 ((eq (car target) 'file)
527 (set-buffer (org-capture-target-buffer (nth 1 target)))
528 (setq target-entry-p nil))
530 ((eq (car target) 'id)
531 (let ((loc (org-id-find (nth 1 target))))
532 (if (not loc)
533 (error "Cannot find target ID \"%s\"" (nth 1 target))
534 (set-buffer (org-capture-target-buffer (car loc)))
535 (goto-char (cdr loc)))))
537 ((eq (car target) 'file+headline)
538 (set-buffer (org-capture-target-buffer (nth 1 target)))
539 (let ((hd (nth 2 target)))
540 (goto-char (point-min))
541 (if (re-search-forward
542 (format org-complex-heading-regexp-format (regexp-quote hd))
543 nil t)
544 (goto-char (point-at-bol))
545 (goto-char (point-max))
546 (or (bolp) (insert "\n"))
547 (insert "* " hd "\n")
548 (beginning-of-line 0))))
550 ((eq (car target) 'file+olp)
551 (let ((m (org-find-olp (cdr target))))
552 (set-buffer (marker-buffer m))
553 (goto-char m)))
555 ((eq (car target) 'file+regexp)
556 (set-buffer (org-capture-target-buffer (nth 1 target)))
557 (goto-char (point-min))
558 (if (re-search-forward (nth 1 target) nil t)
559 (progn
560 (goto-char (match-beginning 0))
561 (setq target-entry-p (and (org-mode-p) (org-at-heading-p))))
562 (kill-buffer (current-buffer))
563 (error "No match for target regexp in file %s" (nth 1 target))))
565 ((eq (car target) 'file+datetree)
566 (require 'org-datetree)
567 (set-buffer (org-capture-target-buffer (nth 1 target)))
568 ;; Make a date tree entry, with the current date (or yesterday,
569 ;; if we are extending dates for a couple of hours)
570 (org-datetree-find-date-create
571 (calendar-gregorian-from-absolute
572 (if org-overriding-default-time
573 (time-to-days org-overriding-default-time)
574 (time-to-days
575 (time-subtract (current-time)
576 (list 0 (* 3600 org-extend-today-until) 0)))))))
578 ((eq (car target) 'file+function)
579 (set-buffer (org-capture-target-buffer (nth 1 target)))
580 (funcall (nth 1 target))
581 (setq target-entry-p (and (org-mode-p) (org-at-heading-p))))
583 ((eq (car target) 'clock)
584 (if (and (markerp org-clock-hd-marker)
585 (marker-buffer org-clock-hd-marker))
586 (progn (set-buffer (org-capture-target-buffer
587 (marker-buffer org-clock-hd-marker)))
588 (goto-char org-clock-hd-marker))
589 (error "No running clock that could be used as capture target")))
591 (t (error "Invalid capture target specification")))
593 (org-capture-put :buffer (current-buffer) :pos (point)
594 :target-entry-p target-entry-p))))
596 (defun org-capture-target-buffer (file)
597 "Get a buffer for FILE."
598 (or (org-find-base-buffer-visiting file)
599 (find-file-noselect (expand-file-name file org-directory))))
601 (defun org-capture-steal-local-variables (buffer)
602 "Install Org-mode local variables"
603 (mapc (lambda (v)
604 (ignore-errors (org-set-local (car v) (cdr v))))
605 (buffer-local-variables buffer)))
607 (defun org-capture-place-template ()
608 "Insert the template at the target location, and display the buffer."
609 (org-capture-put :return-to-wconf (current-window-configuration))
610 (delete-other-windows)
611 (org-switch-to-buffer-other-window
612 (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE"))
613 (show-all)
614 (goto-char (org-capture-get :pos))
615 (org-set-local 'org-capture-target-marker
616 (move-marker (make-marker) (point)))
617 (let* ((template (org-capture-get :template))
618 (type (org-capture-get :type)))
619 (case type
620 ((nil entry) (org-capture-place-entry))
621 (table-line (org-capture-place-table-line))
622 (plain (org-capture-place-plain-text))
623 (item (org-capture-place-item))))
624 (org-capture-mode 1)
625 (org-set-local 'org-capture-current-plist org-capture-plist))
627 (defun org-capture-place-entry ()
628 "Place the template as a new Org entry."
629 (let* ((txt (org-capture-get :template))
630 (reversed (org-capture-get :prepend))
631 (target-entry-p (org-capture-get :target-entry-p))
632 level beg end)
633 (cond
634 ((not target-entry-p)
635 ;; Insert as top-level entry, either at beginning or at end of file
636 (setq level 1)
637 (if reversed
638 (progn (goto-char (point-min))
639 (outline-next-heading))
640 (goto-char (point-max))
641 (or (bolp) (insert "\n"))))
643 ;; Insert as a child of the current entry
644 (and (looking-at "\\*+")
645 (setq level (- (match-end 0) (match-beginning 0))))
646 (setq level (org-get-valid-level (or level 1) 1))
647 (if reversed
648 (progn
649 (outline-next-heading)
650 (or (bolp) (insert "\n")))
651 (org-end-of-subtree t t)
652 (or (bolp) (insert "\n")))))
653 (org-capture-empty-lines-before)
654 (setq beg (point))
655 (org-paste-subtree level txt 'for-yank)
656 (org-capture-empty-lines-after 1)
657 (outline-next-heading)
658 (setq end (point))
659 (org-capture-mark-kill-region beg (1- end))
660 (org-capture-narrow beg (1- end))
661 (if (re-search-forward "%\\?" end t) (replace-match ""))))
663 (defun org-capture-place-item ()
664 "Place the template as a new plain list item."
665 (let* ((txt (org-capture-get :template))
666 (target-entry-p (org-capture-get :target-entry-p))
667 ind beg end)
668 (cond
669 ((not target-entry-p)
670 ;; Insert as top-level entry, either at beginning or at end of file
671 (setq beg (point-min) end (point-max)))
673 (setq beg (1+ (point-at-eol))
674 end (save-excursion (outline-next-heading) (point)))))
675 (if (org-capture-get :prepend)
676 (progn
677 (goto-char beg)
678 (if (re-search-forward (concat "^" (org-item-re)) nil t)
679 (progn
680 (goto-char (match-beginning 0))
681 (setq ind (org-get-indentation)))
682 (goto-char end)
683 (setq ind 0)))
684 (goto-char end)
685 (if (re-search-backward (concat "^" (org-item-re)) nil t)
686 (progn
687 (setq ind (org-get-indentation))
688 (org-end-of-item))
689 (setq ind 0)))
690 ;; Remove common indentation
691 (setq txt (org-remove-indentation txt))
692 ;; Make sure this is indeed an item
693 (unless (string-match (concat "\\`" (org-item-re)) txt)
694 (setq txt (concat "- "
695 (mapconcat 'identity (split-string txt "\n")
696 "\n "))))
697 ;; Set the correct indentation, depending on context
698 (setq ind (make-string ind ?\ ))
699 (setq txt (concat ind
700 (mapconcat 'identity (split-string txt "\n")
701 (concat "\n" ind))
702 "\n"))
703 ;; Insert, with surrounding empty lines
704 (org-capture-empty-lines-before)
705 (setq beg (point))
706 (insert txt)
707 (or (bolp) (insert "\n"))
708 (org-capture-empty-lines-after 1)
709 (forward-char 1)
710 (setq end (point))
711 (org-capture-mark-kill-region beg (1- end))
712 (org-capture-narrow beg (1- end))
713 (if (re-search-forward "%\\?" end t) (replace-match ""))))
715 (defun org-capture-place-table-line ()
716 "Place the template as a table line."
717 (let* ((txt (org-capture-get :template))
718 (target-entry-p (org-capture-get :target-entry-p))
719 (table-line-pos (org-capture-get :table-line-pos))
720 ind beg end)
721 (cond
722 ((not target-entry-p)
723 (setq beg (point-min) end (point-max)))
725 (setq beg (1+ (point-at-eol))
726 end (save-excursion (outline-next-heading) (point)))))
727 (if (re-search-forward org-table-dataline-regexp end t)
728 (let ((b (org-table-begin)) (e (org-table-end)))
729 (goto-char e)
730 (if (looking-at "[ \t]*#\\+TBLFM:")
731 (forward-line 1))
732 (narrow-to-region b (point)))
733 (goto-char end)
734 (insert "\n\n")
735 (narrow-to-region (1- (point)) (point)))
736 ;; We are narrowed to the table, or to an empty line if there was no table
738 ;; Check if the template is good
739 (if (not (string-match org-table-dataline-regexp txt))
740 (setq txt "| %?Bad template |\n"))
741 (cond
742 ((and table-line-pos
743 (string-match "\\(I+\\)\\([-+][0-9]\\)" table-line-pos))
744 (goto-char (point-min))
745 (let ((nh (- (match-end 1) (match-beginning 1)))
746 (delta (string-to-number (match-string 2 table-line-pos)))
748 ;; The user wants a special position in the table
749 (org-table-get-specials)
750 (setq ll (aref org-table-hlines nh))
751 (unless ll (error "Invalid table line specification \"%s\""
752 table-line-pos))
753 (setq ll (+ ll delta (if (< delta 0) 0 -1)))
754 (org-goto-line ll)
755 (org-table-insert-row 'below)
756 (beginning-of-line 1)
757 (delete-region (point) (1+ (point-at-eol)))
758 (setq beg (point))
759 (insert txt)
760 (setq end (point))))
761 ((org-capture-get :prepend)
762 (goto-char (point-min))
763 (re-search-forward org-table-hline-regexp nil t)
764 (beginning-of-line 1)
765 (re-search-forward org-table-dataline-regexp nil t)
766 (beginning-of-line 1)
767 (setq beg (point))
768 (org-table-insert-row)
769 (beginning-of-line 1)
770 (delete-region (point) (1+ (point-at-eol)))
771 (insert txt)
772 (setq end (point)))
774 (goto-char (point-max))
775 (re-search-backward org-table-dataline-regexp nil t)
776 (beginning-of-line 1)
777 (org-table-insert-row 'below)
778 (beginning-of-line 1)
779 (delete-region (point) (1+ (point-at-eol)))
780 (setq beg (point))
781 (insert txt)
782 (setq end (point))))
783 (goto-char beg)
784 (if (re-search-forward "%\\?" end t) (replace-match ""))
785 (org-table-align)))
787 (defun org-capture-place-plain-text ()
788 "Place the template plainly."
789 (let* ((txt (org-capture-get :template))
790 beg end)
791 (goto-char (if (org-capture-get :prepend) (point-min) (point-max)))
792 (or (bolp) (newline))
793 (org-capture-empty-lines-before)
794 (setq beg (point))
795 (insert txt)
796 (org-capture-empty-lines-after 1)
797 (setq end (point))
798 (org-capture-mark-kill-region beg (1- end))
799 (org-capture-narrow beg (1- end))
800 (if (re-search-forward "%\\?" end t) (replace-match ""))))
802 (defun org-capture-mark-kill-region (beg end)
803 "Mark the region that will have to be killed when aborting capture."
804 (let ((m1 (move-marker (make-marker) beg))
805 (m2 (move-marker (make-marker) end)))
806 (org-capture-put :begin-marker m1)
807 (org-capture-put :end-marker m2)))
809 (defun org-capture-narrow (beg end)
810 "Narrow, unless configuraion says not to narrow."
811 (unless (org-capture-get :unnarrowed)
812 (narrow-to-region beg end)
813 (goto-char beg)))
815 (defun org-capture-empty-lines-before (&optional n)
816 "Arrange for the correct number of empty lines before the insertion point.
817 Point will be after the empty lines, so insertion can direcetly be done."
818 (setq n (or n (org-capture-get :empty-lines) 0))
819 (let ((pos (point)))
820 (org-back-over-empty-lines)
821 (delete-region (point) pos)
822 (newline n)))
824 (defun org-capture-empty-lines-after (&optional n)
825 "Arrange for the correct number of empty lines after the inserted string.
826 Point will remain at the first line after the inserted text."
827 (setq n (or n (org-capture-get :empty-lines) 0))
828 (org-back-over-empty-lines)
829 (while (looking-at "[ \t]*\n") (replace-match ""))
830 (let ((pos (point)))
831 (newline n)
832 (goto-char pos)))
834 (defvar org-clock-marker) ; Defined in org.el
835 ;;;###autoload
836 (defun org-capture-insert-template-here ()
837 (let* ((template (org-capture-get :template))
838 (type (org-capture-get :type))
839 beg end pp)
840 (or (bolp) (newline))
841 (setq beg (point))
842 (cond
843 ((and (eq type 'entry) (org-mode-p))
844 (org-paste-subtree nil template t))
845 ((and (memq type '(item checkitem))
846 (org-mode-p)
847 (save-excursion (skip-chars-backward " \t\n")
848 (setq pp (point))
849 (org-in-item-p)))
850 (goto-char pp)
851 (org-insert-item)
852 (skip-chars-backward " ")
853 (skip-chars-backward "-+*0123456789).")
854 (delete-region (point) (point-at-eol))
855 (setq beg (point))
856 (org-remove-indentation template)
857 (insert template)
858 (org-capture-empty-lines-after)
859 (goto-char beg)
860 (org-maybe-renumber-ordered-list)
861 (org-end-of-item)
862 (setq end (point)))
863 (t (insert template)))
864 (setq end (point))
865 (goto-char beg)
866 (if (re-search-forward "%\\?" end t)
867 (replace-match ""))))
869 (defun org-capture-set-plist (entry)
870 "Initialize the property list from the template definition."
871 (setq org-capture-plist (copy-sequence (nthcdr 5 entry)))
872 (org-capture-put :key (car entry) :description (nth 1 entry)
873 :target (nth 3 entry))
874 (let ((txt (nth 4 entry)) (type (or (nth 2 entry) 'entry)))
875 (when (or (not txt) (not (string-match "\\S-" txt)))
876 ;; The template may be empty or omitted for special types.
877 ;; Here we insert the default templates for such cases.
878 (cond
879 ((eq type 'item) (setq txt "- %?"))
880 ((eq type 'checkitem) (setq txt "- [ ] %?"))
881 ((eq type 'table-line) (setq txt "| %? |"))
882 ((member type '(nil entry)) (setq txt "* %?\n %a"))))
883 (org-capture-put :template txt :type type)))
885 (defun org-capture-goto-target (&optional template-key)
886 "Go to the target location of a capture template.
887 The user is queried for the template."
888 (interactive)
889 (let* (org-select-template-temp-major-mode
890 (entry (org-capture-select-template template-key)))
891 (unless entry
892 (error "No capture emplate selected"))
893 (org-capture-set-plist entry)
894 (org-capture-set-target-location)
895 (switch-to-buffer (org-capture-get :buffer))
896 (goto-char (org-capture-get :pos))))
898 (defun org-capture-get-indirect-buffer (&optional buffer prefix)
899 "Make an indirect buffer for a capture process.
900 Use PREFIX as a prefix for the name of the indirect buffer."
901 (setq buffer (or buffer (current-buffer)))
902 (let ((n 1) (base (buffer-name buffer)) bname)
903 (setq bname (concat prefix "-" base))
904 (while (buffer-live-p (get-buffer bname))
905 (setq bname (concat prefix "-" (number-to-string (incf n)) "-" base)))
906 (condition-case nil
907 (make-indirect-buffer buffer bname 'clone)
908 (error (make-indirect-buffer buffer bname)))))
911 ;;; The template code
913 (defun org-capture-select-template (&optional keys)
914 "Select a capture template.
915 Lisp programs can force the template by setting KEYS to a string."
916 (when org-capture-templates
917 (if keys
918 (or (assoc keys org-capture-templates)
919 (error "No capture template referred to by \"%s\" keys" keys))
920 (org-mks org-capture-templates
921 "Select a capture template\n========================="
922 "Template key: "
923 '(("C" "Customize org-capture-templates")
924 ("q" "Abort"))))))
926 (defun org-capture-fill-template (&optional template initial annotation)
927 "Fill a template and return the filled template as a string.
928 The template may still contain \"%?\" for cursor positioning."
929 (setq template (or template (org-capture-get :template)))
930 (when (stringp initial)
931 (setq initial (org-no-properties initial))
932 (remove-text-properties 0 (length initial) '(read-only t) initial))
933 (let* ((buffer (org-capture-get :buffer))
934 (file (buffer-file-name (or (buffer-base-buffer buffer) buffer)))
935 (ct (org-capture-get :default-time))
936 (dct (decode-time ct))
937 (ct1
938 (if (< (nth 2 dct) org-extend-today-until)
939 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
940 ct))
941 (plist-p (if org-store-link-plist t nil))
942 (v-c (and (> (length kill-ring) 0) (current-kill 0)))
943 (v-x (or (org-get-x-clipboard 'PRIMARY)
944 (org-get-x-clipboard 'CLIPBOARD)
945 (org-get-x-clipboard 'SECONDARY)))
946 (v-t (format-time-string (car org-time-stamp-formats) ct))
947 (v-T (format-time-string (cdr org-time-stamp-formats) ct))
948 (v-u (concat "[" (substring v-t 1 -1) "]"))
949 (v-U (concat "[" (substring v-T 1 -1) "]"))
950 ;; `initial' and `annotation' might habe been passed.
951 ;; But if the property list has them, we prefer those values
952 (v-i (or (plist-get org-store-link-plist :initial)
953 initial
954 (org-capture-get :initial)
955 ""))
956 (v-a (or (plist-get org-store-link-plist :annotation)
957 annotation
958 (org-capture-get :annotation)
959 ""))
960 ;; Is the link empty? Then we do not want it...
961 (v-a (if (equal v-a "[[]]") "" v-a))
962 (clipboards (remove nil (list v-i
963 (org-get-x-clipboard 'PRIMARY)
964 (org-get-x-clipboard 'CLIPBOARD)
965 (org-get-x-clipboard 'SECONDARY)
966 v-c)))
967 (v-A (if (and v-a
968 (string-match
969 "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
970 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
971 v-a))
972 (v-n user-full-name)
973 (v-k (if (marker-buffer org-clock-marker)
974 (org-substring-no-properties org-clock-heading)))
975 (v-K (if (marker-buffer org-clock-marker)
976 (org-make-link-string
977 (buffer-file-name (marker-buffer org-clock-marker))
978 org-clock-heading)))
980 (org-startup-folded nil)
981 (org-inhibit-startup t)
982 org-time-was-given org-end-time-was-given x
983 prompt completions char time pos default histvar)
985 (setq org-store-link-plist
986 (plist-put org-store-link-plist :annotation v-a)
987 org-store-link-plist
988 (plist-put org-store-link-plist :initial v-i))
990 (unless template (setq template "") (message "No template") (ding)
991 (sit-for 1))
992 (save-window-excursion
993 (delete-other-windows)
994 (switch-to-buffer (get-buffer-create "*Capture*"))
995 (insert template)
996 (goto-char (point-min))
997 (org-capture-steal-local-variables buffer)
998 ;; Simple %-escapes
999 (while (re-search-forward "%\\([tTuUaiAcxkKI]\\)" nil t)
1000 (unless (org-capture-escaped-%)
1001 (when (and initial (equal (match-string 0) "%i"))
1002 (save-match-data
1003 (let* ((lead (buffer-substring
1004 (point-at-bol) (match-beginning 0))))
1005 (setq v-i (mapconcat 'identity
1006 (org-split-string initial "\n")
1007 (concat "\n" lead))))))
1008 (replace-match
1009 (or (eval (intern (concat "v-" (match-string 1)))) "")
1010 t t)))
1012 ;; %[] Insert contents of a file.
1013 (goto-char (point-min))
1014 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
1015 (unless (org-capture-escaped-%)
1016 (let ((start (match-beginning 0))
1017 (end (match-end 0))
1018 (filename (expand-file-name (match-string 1))))
1019 (goto-char start)
1020 (delete-region start end)
1021 (condition-case error
1022 (insert-file-contents filename)
1023 (error (insert (format "%%![Couldn't insert %s: %s]"
1024 filename error)))))))
1025 ;; %() embedded elisp
1026 (goto-char (point-min))
1027 (while (re-search-forward "%\\((.+)\\)" nil t)
1028 (unless (org-capture-escaped-%)
1029 (goto-char (match-beginning 0))
1030 (let ((template-start (point)))
1031 (forward-char 1)
1032 (let ((result
1033 (condition-case error
1034 (eval (read (current-buffer)))
1035 (error (format "%%![Error: %s]" error)))))
1036 (delete-region template-start (point))
1037 (insert result)))))
1039 ;; From the property list
1040 (when plist-p
1041 (goto-char (point-min))
1042 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
1043 (unless (org-capture-escaped-%)
1044 (and (setq x (or (plist-get org-store-link-plist
1045 (intern (match-string 1))) ""))
1046 (replace-match x t t)))))
1048 ;; Turn on org-mode in temp buffer, set local variables
1049 ;; This is to support completion in interactive prompts
1050 (let ((org-inhibit-startup t)) (org-mode))
1051 ;; Interactive template entries
1052 (goto-char (point-min))
1053 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGtTuUCLp]\\)?"
1054 nil t)
1055 (unless (org-capture-escaped-%)
1056 (setq char (if (match-end 3) (match-string 3))
1057 prompt (if (match-end 2) (match-string 2)))
1058 (goto-char (match-beginning 0))
1059 (replace-match "")
1060 (setq completions nil default nil)
1061 (when prompt
1062 (setq completions (org-split-string prompt "|")
1063 prompt (pop completions)
1064 default (car completions)
1065 histvar (intern (concat
1066 "org-capture-template-prompt-history::"
1067 (or prompt "")))
1068 completions (mapcar 'list completions)))
1069 (cond
1070 ((member char '("G" "g"))
1071 (let* ((org-last-tags-completion-table
1072 (org-global-tags-completion-table
1073 (if (equal char "G")
1074 (org-agenda-files)
1075 (and file (list file)))))
1076 (org-add-colon-after-tag-completion t)
1077 (ins (org-icompleting-read
1078 (if prompt (concat prompt ": ") "Tags: ")
1079 'org-tags-completion-function nil nil nil
1080 'org-tags-history)))
1081 (setq ins (mapconcat 'identity
1082 (org-split-string
1083 ins (org-re "[^[:alnum:]_@]+"))
1084 ":"))
1085 (when (string-match "\\S-" ins)
1086 (or (equal (char-before) ?:) (insert ":"))
1087 (insert ins)
1088 (or (equal (char-after) ?:) (insert ":")))))
1089 ((equal char "C")
1090 (cond ((= (length clipboards) 1) (insert (car clipboards)))
1091 ((> (length clipboards) 1)
1092 (insert (read-string "Clipboard/kill value: "
1093 (car clipboards) '(clipboards . 1)
1094 (car clipboards))))))
1095 ((equal char "L")
1096 (cond ((= (length clipboards) 1)
1097 (org-insert-link 0 (car clipboards)))
1098 ((> (length clipboards) 1)
1099 (org-insert-link 0 (read-string "Clipboard/kill value: "
1100 (car clipboards)
1101 '(clipboards . 1)
1102 (car clipboards))))))
1103 ((equal char "p")
1104 (let*
1105 ((prop (org-substring-no-properties prompt))
1106 (pall (concat prop "_ALL"))
1107 (allowed
1108 (with-current-buffer
1109 (get-buffer (file-name-nondirectory file))
1110 (or (cdr (assoc pall org-file-properties))
1111 (cdr (assoc pall org-global-properties))
1112 (cdr (assoc pall org-global-properties-fixed)))))
1113 (existing (with-current-buffer
1114 (get-buffer (file-name-nondirectory file))
1115 (mapcar 'list (org-property-values prop))))
1116 (propprompt (concat "Value for " prop ": "))
1117 (val (if allowed
1118 (org-completing-read
1119 propprompt
1120 (mapcar 'list (org-split-string allowed
1121 "[ \t]+"))
1122 nil 'req-match)
1123 (org-completing-read-no-i propprompt
1124 existing nil nil
1125 "" nil ""))))
1126 (org-set-property prop val)))
1127 (char
1128 ;; These are the date/time related ones
1129 (setq org-time-was-given (equal (upcase char) char))
1130 (setq time (org-read-date (equal (upcase char) "U") t nil
1131 prompt))
1132 (org-insert-time-stamp time org-time-was-given
1133 (member char '("u" "U"))
1134 nil nil (list org-end-time-was-given)))
1136 (let (org-completion-use-ido)
1137 (insert (org-completing-read-no-i
1138 (concat (if prompt prompt "Enter string")
1139 (if default (concat " [" default "]"))
1140 ": ")
1141 completions nil nil nil histvar default)))))))
1142 ;; Make sure there are no empty lines before the text, and that
1143 ;; it ends with a newline character
1144 (goto-char (point-min))
1145 (while (looking-at "[ \t]*\n") (replace-match ""))
1146 (if (re-search-forward "[ \t\n]*\\'" nil t) (replace-match "\n"))
1147 ;; Return the expanded tempate and kill the temporary buffer
1148 (untabify (point-min) (point-max))
1149 (set-buffer-modified-p nil)
1150 (prog1 (buffer-string) (kill-buffer (current-buffer))))))
1152 (defun org-capture-escaped-% ()
1153 "Check if % was escaped - if yes, unescape it now."
1154 (if (equal (char-before (match-beginning 0)) ?\\)
1155 (progn
1156 (delete-region (1- (match-beginning 0)) (match-beginning 0))
1158 nil))
1160 ;;;###autoload
1161 (defun org-capture-import-remember-templates ()
1162 "Set org-capture-templates to be similar to `org-remember-templates'."
1163 (interactive)
1164 (when (and (yes-or-no-p
1165 "Import old remember templates into org-capture-templates? ")
1166 (yes-or-no-p
1167 "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
1168 (require 'org-remember)
1169 (setq org-capture-templates
1170 (mapcar
1171 (lambda (entry)
1172 (let ((desc (car entry))
1173 (key (char-to-string (nth 1 entry)))
1174 (template (nth 2 entry))
1175 (file (or (nth 3 entry) org-default-notes-file))
1176 (position (or (nth 4 entry) org-remember-default-headline))
1177 (type 'entry)
1178 (prepend org-reverse-note-order)
1179 immediate target)
1180 (cond
1181 ((member position '(top bottom))
1182 (setq target (list 'file file)
1183 prepend (eq position 'top)))
1184 ((eq position 'date-tree)
1185 (setq target (list 'file+datetree file)
1186 prepend nil))
1187 (t (setq target (list 'file+headline file position))))
1189 (when (string-match "%!" template)
1190 (setq template (replace-match "" t t template)
1191 immediate t))
1193 (append (list key desc type target template)
1194 (if prepend '(:prepend t))
1195 (if immediate '(:immediate-finish t)))))
1197 org-remember-templates))))
1199 (provide 'org-capture)
1201 ;; arch-tag: 986bf41b-8ada-4e28-bf20-e8388a7205a0
1203 ;;; org-capture.el ends here