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