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