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