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