org-agenda.el: Allow `org-agenda-finalize-hook' to modify the buffer
[org-mode.git] / lisp / org-capture.el
blob79e5a5d3de4d772a53992536ee201baa07512226
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 %i Initial content, copied from the active region. If %i is
229 indented, the entire inserted text will be indented as well.
230 %a Annotation, normally the link created with `org-store-link'.
231 %A Like %a, but prompt for the description part.
232 %l Like %a, but only insert the literal link.
233 %c Current kill ring head.
234 %x Content of the X clipboard.
235 %k Title of currently clocked task.
236 %K Link to currently clocked task.
237 %n User name (taken from `user-full-name').
238 %f File visited by current buffer when org-capture was called.
239 %F Full path of the file or directory visited by current buffer.
240 %:keyword Specific information for certain link types, see below.
241 %^g Prompt for tags, with completion on tags in target file.
242 %^G Prompt for tags, with completion on all tags in all agenda files.
243 %^t Like %t, but prompt for date. Similarly %^T, %^u, %^U.
244 You may define a prompt like %^{Please specify birthday.
245 %^C Interactive selection of which kill or clip to use.
246 %^L Like %^C, but insert as link.
247 %^{prop}p Prompt the user for a value for property `prop'.
248 %^{prompt} Prompt the user for a string and replace this sequence with it.
249 A default value and a completion table ca be specified like this:
250 %^{prompt|default|completion2|completion3|...}.
251 %? After completing the template, position cursor here.
252 %\\n Insert the text entered at the nth %^{prompt}, where `n' is
253 a number, starting from 1.
255 Apart from these general escapes, you can access information specific to
256 the link type that is created. For example, calling `org-capture' in emails
257 or in Gnus will record the author and the subject of the message, which you
258 can access with \"%:from\" and \"%:subject\", respectively. Here is a
259 complete list of what is recorded for each link type.
261 Link type | Available information
262 ------------------------+------------------------------------------------------
263 bbdb | %:type %:name %:company
264 vm, wl, mh, mew, rmail, | %:type %:subject %:message-id
265 gnus | %:from %:fromname %:fromaddress
266 | %:to %:toname %:toaddress
267 | %:fromto (either \"to NAME\" or \"from NAME\")
268 | %:date %: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.3"
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 (defvar org-capture-initial nil)
435 (defvar org-capture-entry nil)
436 (defun org-capture-string (string &optional keys)
437 (interactive "sInitial text: \n")
438 (let ((org-capture-initial string)
439 (org-capture-entry (org-capture-select-template keys)))
440 (org-capture)))
442 (defcustom org-capture-templates-contexts nil
443 "Alist of capture templates and valid contexts.
445 For example, if you have a capture template \"c\" and you want
446 this template to be accessible only from `message-mode' buffers,
447 use this:
449 '((\"c\" (in-mode . \"message-mode\")))
451 Here are the available contexts definitions:
453 in-file: command displayed only in matching files
454 in-mode: command displayed only in matching modes
455 not-in-file: command not displayed in matching files
456 not-in-mode: command not displayed in matching modes
457 [function]: a custom function taking no argument
459 If you define several checks, the agenda command will be
460 accessible if there is at least one valid check.
462 You can also bind a key to another agenda custom command
463 depending on contextual rules.
465 '((\"c\" \"d\" (in-mode . \"message-mode\")))
467 Here it means: in `message-mode buffers', use \"d\" as the
468 key for the capture template otherwise associated with \"d\".
469 \(The template originally associated with \"q\" is not displayed
470 to avoid duplicates.)"
471 ;; :version "24.3"
472 :group 'org-capture
473 :type '(repeat (list :tag "Rule"
474 (string :tag " Capture key")
475 (string :tag "Replace by template")
476 (repeat :tag "Available when"
477 (choice
478 (cons :tag "Condition"
479 (choice
480 (const :tag "In file" in-file)
481 (const :tag "Not in file" not-in-file)
482 (const :tag "In mode" in-mode)
483 (const :tag "Not in mode" not-in-mode))
484 (regexp))
485 (function :tag "Custom function"))))))
487 (defcustom org-capture-use-agenda-date nil
488 "Non-nil means use the date at point when capturing from agendas.
489 When nil, you can still capturing using the date at point with \\[org-agenda-capture]]."
490 :group 'org-capture
491 ;; :version "24.3"
492 :type 'boolean)
494 ;;;###autoload
495 (defun org-capture (&optional goto keys)
496 "Capture something.
497 \\<org-capture-mode-map>
498 This will let you select a template from `org-capture-templates', and then
499 file the newly captured information. The text is immediately inserted
500 at the target location, and an indirect buffer is shown where you can
501 edit it. Pressing \\[org-capture-finalize] brings you back to the previous state
502 of Emacs, so that you can continue your work.
504 When called interactively with a \\[universal-argument] prefix argument GOTO, don't capture
505 anything, just go to the file/headline where the selected template
506 stores its notes. With a double prefix argument \
507 \\[universal-argument] \\[universal-argument], go to the last note
508 stored.
510 When called with a `C-0' (zero) prefix, insert a template at point.
512 Lisp programs can set KEYS to a string associated with a template
513 in `org-capture-templates'. In this case, interactive selection
514 will be bypassed.
516 If `org-capture-use-agenda-date' is non-nil, capturing from the
517 agenda will use the date at point as the default date."
518 (interactive "P")
519 (when (and org-capture-use-agenda-date
520 (eq major-mode 'org-agenda-mode))
521 (setq org-overriding-default-time
522 (org-get-cursor-date)))
523 (cond
524 ((equal goto '(4)) (org-capture-goto-target))
525 ((equal goto '(16)) (org-capture-goto-last-stored))
527 ;; FIXME: Are these needed?
528 (let* ((orig-buf (current-buffer))
529 (annotation (if (and (boundp 'org-capture-link-is-already-stored)
530 org-capture-link-is-already-stored)
531 (plist-get org-store-link-plist :annotation)
532 (ignore-errors (org-store-link nil))))
533 (entry (or org-capture-entry (org-capture-select-template keys)))
534 initial)
535 (setq initial (or org-capture-initial
536 (and (org-region-active-p)
537 (buffer-substring (point) (mark)))))
538 (when (stringp initial)
539 (remove-text-properties 0 (length initial) '(read-only t) initial))
540 (when (stringp annotation)
541 (remove-text-properties 0 (length annotation)
542 '(read-only t) annotation))
543 (cond
544 ((equal entry "C")
545 (customize-variable 'org-capture-templates))
546 ((equal entry "q")
547 (error "Abort"))
549 (org-capture-set-plist entry)
550 (org-capture-get-template)
551 (org-capture-put :original-buffer orig-buf
552 :original-file (or (buffer-file-name orig-buf)
553 (and (featurep 'dired)
554 (car (rassq orig-buf
555 dired-buffers))))
556 :original-file-nondirectory
557 (and (buffer-file-name orig-buf)
558 (file-name-nondirectory
559 (buffer-file-name orig-buf)))
560 :annotation annotation
561 :initial initial)
562 (org-capture-put :default-time
563 (or org-overriding-default-time
564 (org-current-time)))
565 (org-capture-set-target-location)
566 (condition-case error
567 (org-capture-put :template (org-capture-fill-template))
568 ((error quit)
569 (if (get-buffer "*Capture*") (kill-buffer "*Capture*"))
570 (error "Capture abort: %s" error)))
572 (setq org-capture-clock-keep (org-capture-get :clock-keep))
573 (if (equal goto 0)
574 ;;insert at point
575 (org-capture-insert-template-here)
576 (condition-case error
577 (org-capture-place-template)
578 ((error quit)
579 (if (and (buffer-base-buffer (current-buffer))
580 (string-match "\\`CAPTURE-" (buffer-name)))
581 (kill-buffer (current-buffer)))
582 (set-window-configuration (org-capture-get :return-to-wconf))
583 (error "Capture template `%s': %s"
584 (org-capture-get :key)
585 (nth 1 error))))
586 (if (and (derived-mode-p 'org-mode)
587 (org-capture-get :clock-in))
588 (condition-case nil
589 (progn
590 (if (org-clock-is-active)
591 (org-capture-put :interrupted-clock
592 (copy-marker org-clock-marker)))
593 (org-clock-in)
594 (org-set-local 'org-capture-clock-was-started t))
595 (error
596 "Could not start the clock in this capture buffer")))
597 (if (org-capture-get :immediate-finish)
598 (org-capture-finalize nil)))))))))
600 (defun org-capture-get-template ()
601 "Get the template from a file or a function if necessary."
602 (let ((txt (org-capture-get :template)) file)
603 (cond
604 ((and (listp txt) (eq (car txt) 'file))
605 (if (file-exists-p
606 (setq file (expand-file-name (nth 1 txt) org-directory)))
607 (setq txt (org-file-contents file))
608 (setq txt (format "* Template file %s not found" (nth 1 txt)))))
609 ((and (listp txt) (eq (car txt) 'function))
610 (if (fboundp (nth 1 txt))
611 (setq txt (funcall (nth 1 txt)))
612 (setq txt (format "* Template function %s not found" (nth 1 txt)))))
613 ((not txt) (setq txt ""))
614 ((stringp txt))
615 (t (setq txt "* Invalid capture template")))
616 (org-capture-put :template txt)))
618 (defun org-capture-finalize (&optional stay-with-capture)
619 "Finalize the capture process.
620 With prefix argument STAY-WITH-CAPTURE, jump to the location of the
621 captured item after finalizing."
622 (interactive "P")
623 (unless (and org-capture-mode
624 (buffer-base-buffer (current-buffer)))
625 (error "This does not seem to be a capture buffer for Org-mode"))
627 (run-hooks 'org-capture-prepare-finalize-hook)
629 ;; Did we start the clock in this capture buffer?
630 (when (and org-capture-clock-was-started
631 org-clock-marker (marker-buffer org-clock-marker)
632 (equal (marker-buffer org-clock-marker) (buffer-base-buffer))
633 (> org-clock-marker (point-min))
634 (< org-clock-marker (point-max)))
635 ;; Looks like the clock we started is still running. Clock out.
636 (when (not org-capture-clock-keep) (let (org-log-note-clock-out) (org-clock-out)))
637 (when (and (not org-capture-clock-keep)
638 (org-capture-get :clock-resume 'local)
639 (markerp (org-capture-get :interrupted-clock 'local))
640 (buffer-live-p (marker-buffer
641 (org-capture-get :interrupted-clock 'local))))
642 (let ((clock-in-task (org-capture-get :interrupted-clock 'local)))
643 (org-with-point-at clock-in-task
644 (org-clock-in)))
645 (message "Interrupted clock has been resumed")))
647 (let ((beg (point-min))
648 (end (point-max))
649 (abort-note nil))
650 ;; Store the size of the capture buffer
651 (org-capture-put :captured-entry-size (- (point-max) (point-min)))
652 (widen)
653 ;; Store the insertion point in the target buffer
654 (org-capture-put :insertion-point (point))
656 (if org-note-abort
657 (let ((m1 (org-capture-get :begin-marker 'local))
658 (m2 (org-capture-get :end-marker 'local)))
659 (if (and m1 m2 (= m1 beg) (= m2 end))
660 (progn
661 (setq m2 (if (cdr (assoc 'heading org-blank-before-new-entry))
662 m2 (1+ m2))
663 m2 (if (< (point-max) m2) (point-max) m2))
664 (setq abort-note 'clean)
665 (kill-region m1 m2))
666 (setq abort-note 'dirty)))
668 ;; Make sure that the empty lines after are correct
669 (when (and (> (point-max) end) ; indeed, the buffer was still narrowed
670 (member (org-capture-get :type 'local)
671 '(entry item checkitem plain)))
672 (save-excursion
673 (goto-char end)
674 (or (bolp) (newline))
675 (org-capture-empty-lines-after
676 (or (org-capture-get :empty-lines-after 'local)
677 (org-capture-get :empty-lines 'local) 0))))
678 ;; Postprocessing: Update Statistics cookies, do the sorting
679 (when (derived-mode-p 'org-mode)
680 (save-excursion
681 (when (ignore-errors (org-back-to-heading))
682 (org-update-parent-todo-statistics)
683 (org-update-checkbox-count)))
684 ;; FIXME Here we should do the sorting
685 ;; If we have added a table line, maybe recompute?
686 (when (and (eq (org-capture-get :type 'local) 'table-line)
687 (org-at-table-p))
688 (if (org-table-get-stored-formulas)
689 (org-table-recalculate 'all) ;; FIXME: Should we iterate???
690 (org-table-align))))
691 ;; Store this place as the last one where we stored something
692 ;; Do the marking in the base buffer, so that it makes sense after
693 ;; the indirect buffer has been killed.
694 (when org-capture-bookmark
695 (org-capture-bookmark-last-stored-position))
697 ;; Run the hook
698 (run-hooks 'org-capture-before-finalize-hook))
700 ;; Kill the indirect buffer
701 (save-buffer)
702 (let ((return-wconf (org-capture-get :return-to-wconf 'local))
703 (new-buffer (org-capture-get :new-buffer 'local))
704 (kill-buffer (org-capture-get :kill-buffer 'local))
705 (base-buffer (buffer-base-buffer (current-buffer))))
707 ;; Kill the indirect buffer
708 (kill-buffer (current-buffer))
710 ;; Narrow back the target buffer to its previous state
711 (with-current-buffer (org-capture-get :buffer)
712 (let ((reg (org-capture-get :initial-target-region))
713 (pos (org-capture-get :initial-target-position))
714 (ipt (org-capture-get :insertion-point))
715 (size (org-capture-get :captured-entry-size)))
716 (when reg
717 (cond ((< ipt (car reg))
718 ;; insertion point is before the narrowed region
719 (narrow-to-region (+ size (car reg)) (+ size (cdr reg))))
720 ((> ipt (cdr reg))
721 ;; insertion point is after the narrowed region
722 (narrow-to-region (car reg) (cdr reg)))
724 ;; insertion point is within the narrowed region
725 (narrow-to-region (car reg) (+ size (cdr reg)))))
726 ;; now place back the point at its original position
727 (if (< ipt (car reg))
728 (goto-char (+ size pos))
729 (goto-char (if (< ipt pos) (+ size pos) pos))))))
731 ;; Kill the target buffer if that is desired
732 (when (and base-buffer new-buffer kill-buffer)
733 (with-current-buffer base-buffer (save-buffer))
734 (kill-buffer base-buffer))
736 ;; Restore the window configuration before capture
737 (set-window-configuration return-wconf))
739 (run-hooks 'org-capture-after-finalize-hook)
740 ;; Special cases
741 (cond
742 (abort-note
743 (cond
744 ((equal abort-note 'clean)
745 (message "Capture process aborted and target buffer cleaned up"))
746 ((equal abort-note 'dirty)
747 (error "Capture process aborted, but target buffer could not be cleaned up correctly"))))
748 (stay-with-capture
749 (org-capture-goto-last-stored)))
750 ;; Return if we did store something
751 (not abort-note)))
753 (defun org-capture-refile ()
754 "Finalize the current capture and then refile the entry.
755 Refiling is done from the base buffer, because the indirect buffer is then
756 already gone. Any prefix argument will be passed to the refile command."
757 (interactive)
758 (unless (eq (org-capture-get :type 'local) 'entry)
759 (error
760 "Refiling from a capture buffer makes only sense for `entry'-type templates"))
761 (let ((pos (point))
762 (base (buffer-base-buffer (current-buffer)))
763 (org-refile-for-capture t))
764 (org-capture-finalize)
765 (save-window-excursion
766 (with-current-buffer (or base (current-buffer))
767 (save-excursion
768 (save-restriction
769 (widen)
770 (goto-char pos)
771 (call-interactively 'org-refile)))))))
773 (defun org-capture-kill ()
774 "Abort the current capture process."
775 (interactive)
776 ;; FIXME: This does not do the right thing, we need to remove the
777 ;; new stuff by hand it is easy: undo, then kill the buffer
778 (let ((org-note-abort t)
779 (org-capture-before-finalize-hook nil))
780 (org-capture-finalize)))
782 (defun org-capture-goto-last-stored ()
783 "Go to the location where the last capture note was stored."
784 (interactive)
785 (org-goto-marker-or-bmk org-capture-last-stored-marker
786 "org-capture-last-stored")
787 (message "This is the last note stored by a capture process"))
789 ;;; Supporting functions for handling the process
791 (defun org-capture-put-target-region-and-position ()
792 "Store the initial region with `org-capture-put'."
793 (org-capture-put
794 :initial-target-region
795 ;; Check if the buffer is currently narrowed
796 (when (/= (buffer-size) (- (point-max) (point-min)))
797 (cons (point-min) (point-max))))
798 ;; store the current point
799 (org-capture-put :initial-target-position (point)))
801 (defun org-capture-set-target-location (&optional target)
802 "Find target buffer and position and store then in the property list."
803 (let ((target-entry-p t))
804 (setq target (or target (org-capture-get :target)))
805 (save-excursion
806 (cond
807 ((eq (car target) 'file)
808 (set-buffer (org-capture-target-buffer (nth 1 target)))
809 (org-capture-put-target-region-and-position)
810 (widen)
811 (setq target-entry-p nil))
813 ((eq (car target) 'id)
814 (let ((loc (org-id-find (nth 1 target))))
815 (if (not loc)
816 (error "Cannot find target ID \"%s\"" (nth 1 target))
817 (set-buffer (org-capture-target-buffer (car loc)))
818 (widen)
819 (org-capture-put-target-region-and-position)
820 (goto-char (cdr loc)))))
822 ((eq (car target) 'file+headline)
823 (set-buffer (org-capture-target-buffer (nth 1 target)))
824 (org-capture-put-target-region-and-position)
825 (widen)
826 (let ((hd (nth 2 target)))
827 (goto-char (point-min))
828 (unless (derived-mode-p 'org-mode)
829 (error
830 "Target buffer \"%s\" for file+headline should be in Org mode"
831 (current-buffer)))
832 (if (re-search-forward
833 (format org-complex-heading-regexp-format (regexp-quote hd))
834 nil t)
835 (goto-char (point-at-bol))
836 (goto-char (point-max))
837 (or (bolp) (insert "\n"))
838 (insert "* " hd "\n")
839 (beginning-of-line 0))))
841 ((eq (car target) 'file+olp)
842 (let ((m (org-find-olp
843 (cons (org-capture-expand-file (nth 1 target))
844 (cddr target)))))
845 (set-buffer (marker-buffer m))
846 (org-capture-put-target-region-and-position)
847 (widen)
848 (goto-char m)))
850 ((eq (car target) 'file+regexp)
851 (set-buffer (org-capture-target-buffer (nth 1 target)))
852 (org-capture-put-target-region-and-position)
853 (widen)
854 (goto-char (point-min))
855 (if (re-search-forward (nth 2 target) nil t)
856 (progn
857 (goto-char (if (org-capture-get :prepend)
858 (match-beginning 0) (match-end 0)))
859 (org-capture-put :exact-position (point))
860 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
861 (error "No match for target regexp in file %s" (nth 1 target))))
863 ((memq (car target) '(file+datetree file+datetree+prompt))
864 (require 'org-datetree)
865 (set-buffer (org-capture-target-buffer (nth 1 target)))
866 (org-capture-put-target-region-and-position)
867 (widen)
868 ;; Make a date tree entry, with the current date (or yesterday,
869 ;; if we are extending dates for a couple of hours)
870 (org-datetree-find-date-create
871 (calendar-gregorian-from-absolute
872 (cond
873 (org-overriding-default-time
874 ;; use the overriding default time
875 (time-to-days org-overriding-default-time))
877 ((eq (car target) 'file+datetree+prompt)
878 ;; prompt for date
879 (let ((prompt-time (org-read-date
880 nil t nil "Date for tree entry:"
881 (current-time))))
882 (org-capture-put :prompt-time prompt-time
883 :default-time prompt-time)
884 (time-to-days prompt-time)))
886 ;; current date, possible corrected for late night workers
887 (org-today))))))
889 ((eq (car target) 'file+function)
890 (set-buffer (org-capture-target-buffer (nth 1 target)))
891 (org-capture-put-target-region-and-position)
892 (widen)
893 (funcall (nth 2 target))
894 (org-capture-put :exact-position (point))
895 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
897 ((eq (car target) 'function)
898 (funcall (nth 1 target))
899 (org-capture-put :exact-position (point))
900 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
902 ((eq (car target) 'clock)
903 (if (and (markerp org-clock-hd-marker)
904 (marker-buffer org-clock-hd-marker))
905 (progn (set-buffer (marker-buffer org-clock-hd-marker))
906 (org-capture-put-target-region-and-position)
907 (widen)
908 (goto-char org-clock-hd-marker))
909 (error "No running clock that could be used as capture target")))
911 (t (error "Invalid capture target specification")))
913 (org-capture-put :buffer (current-buffer) :pos (point)
914 :target-entry-p target-entry-p))))
916 (defun org-capture-expand-file (file)
917 "Expand functions and symbols for FILE.
918 When FILE is a function, call it. When it is a form, evaluate
919 it. When it is a variable, retrieve the value. Return whatever we get."
920 (cond
921 ((org-string-nw-p file) file)
922 ((functionp file) (funcall file))
923 ((and (symbolp file) (boundp file)) (symbol-value file))
924 ((and file (consp file)) (eval file))
925 (t file)))
927 (defun org-capture-target-buffer (file)
928 "Get a buffer for FILE."
929 (setq file (org-capture-expand-file file))
930 (setq file (or (org-string-nw-p file)
931 org-default-notes-file
932 (error "No notes file specified, and no default available")))
933 (or (org-find-base-buffer-visiting file)
934 (progn (org-capture-put :new-buffer t)
935 (find-file-noselect (expand-file-name file org-directory)))))
937 (defun org-capture-steal-local-variables (buffer)
938 "Install Org-mode local variables."
939 (mapc (lambda (v)
940 (ignore-errors (org-set-local (car v) (cdr v))))
941 (buffer-local-variables buffer)))
943 (defun org-capture-place-template ()
944 "Insert the template at the target location, and display the buffer."
945 (org-capture-put :return-to-wconf (current-window-configuration))
946 (delete-other-windows)
947 (org-switch-to-buffer-other-window
948 (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE"))
949 (widen)
950 (show-all)
951 (goto-char (org-capture-get :pos))
952 (org-set-local 'org-capture-target-marker
953 (move-marker (make-marker) (point)))
954 (org-set-local 'outline-level 'org-outline-level)
955 (let* ((template (org-capture-get :template))
956 (type (org-capture-get :type)))
957 (case type
958 ((nil entry) (org-capture-place-entry))
959 (table-line (org-capture-place-table-line))
960 (plain (org-capture-place-plain-text))
961 (item (org-capture-place-item))
962 (checkitem (org-capture-place-item))))
963 (org-capture-mode 1)
964 (org-set-local 'org-capture-current-plist org-capture-plist))
966 (defun org-capture-place-entry ()
967 "Place the template as a new Org entry."
968 (let* ((txt (org-capture-get :template))
969 (reversed (org-capture-get :prepend))
970 (target-entry-p (org-capture-get :target-entry-p))
971 level beg end file)
973 (cond
974 ((org-capture-get :exact-position)
975 (goto-char (org-capture-get :exact-position)))
976 ((not target-entry-p)
977 ;; Insert as top-level entry, either at beginning or at end of file
978 (setq level 1)
979 (if reversed
980 (progn (goto-char (point-min))
981 (or (org-at-heading-p)
982 (outline-next-heading)))
983 (goto-char (point-max))
984 (or (bolp) (insert "\n"))))
986 ;; Insert as a child of the current entry
987 (and (looking-at "\\*+")
988 (setq level (- (match-end 0) (match-beginning 0))))
989 (setq level (org-get-valid-level (or level 1) 1))
990 (if reversed
991 (progn
992 (outline-next-heading)
993 (or (bolp) (insert "\n")))
994 (org-end-of-subtree t nil)
995 (or (bolp) (insert "\n")))))
996 (org-capture-empty-lines-before)
997 (setq beg (point))
998 (org-capture-verify-tree txt)
999 (org-paste-subtree level txt 'for-yank)
1000 (org-capture-empty-lines-after 1)
1001 (org-capture-position-for-last-stored beg)
1002 (outline-next-heading)
1003 (setq end (point))
1004 (org-capture-mark-kill-region beg (1- end))
1005 (org-capture-narrow beg (1- end))
1006 (if (or (re-search-backward "%\\?" beg t)
1007 (re-search-forward "%\\?" end t))
1008 (replace-match ""))))
1010 (defun org-capture-place-item ()
1011 "Place the template as a new plain list item."
1012 (let* ((txt (org-capture-get :template))
1013 (target-entry-p (org-capture-get :target-entry-p))
1014 (ind 0)
1015 beg end)
1016 (if (org-capture-get :exact-position)
1017 (goto-char (org-capture-get :exact-position))
1018 (cond
1019 ((not target-entry-p)
1020 ;; Insert as top-level entry, either at beginning or at end of file
1021 (setq beg (point-min) end (point-max)))
1023 (setq beg (1+ (point-at-eol))
1024 end (save-excursion (outline-next-heading) (point)))))
1025 (if (org-capture-get :prepend)
1026 (progn
1027 (goto-char beg)
1028 (if (org-list-search-forward (org-item-beginning-re) end t)
1029 (progn
1030 (goto-char (match-beginning 0))
1031 (setq ind (org-get-indentation)))
1032 (goto-char end)
1033 (setq ind 0)))
1034 (goto-char end)
1035 (if (org-list-search-backward (org-item-beginning-re) beg t)
1036 (progn
1037 (setq ind (org-get-indentation))
1038 (org-end-of-item))
1039 (setq ind 0))))
1040 ;; Remove common indentation
1041 (setq txt (org-remove-indentation txt))
1042 ;; Make sure this is indeed an item
1043 (unless (string-match (concat "\\`" (org-item-re)) txt)
1044 (setq txt (concat "- "
1045 (mapconcat 'identity (split-string txt "\n")
1046 "\n "))))
1047 ;; Set the correct indentation, depending on context
1048 (setq ind (make-string ind ?\ ))
1049 (setq txt (concat ind
1050 (mapconcat 'identity (split-string txt "\n")
1051 (concat "\n" ind))
1052 "\n"))
1053 ;; Insert, with surrounding empty lines
1054 (org-capture-empty-lines-before)
1055 (setq beg (point))
1056 (insert txt)
1057 (or (bolp) (insert "\n"))
1058 (org-capture-empty-lines-after 1)
1059 (org-capture-position-for-last-stored beg)
1060 (forward-char 1)
1061 (setq end (point))
1062 (org-capture-mark-kill-region beg (1- end))
1063 (org-capture-narrow beg (1- end))
1064 (if (or (re-search-backward "%\\?" beg t)
1065 (re-search-forward "%\\?" end t))
1066 (replace-match ""))))
1068 (defun org-capture-place-table-line ()
1069 "Place the template as a table line."
1070 (require 'org-table)
1071 (let* ((txt (org-capture-get :template))
1072 (target-entry-p (org-capture-get :target-entry-p))
1073 (table-line-pos (org-capture-get :table-line-pos))
1074 ind beg end)
1075 (cond
1076 ((org-capture-get :exact-position)
1077 (goto-char (org-capture-get :exact-position)))
1078 ((not target-entry-p)
1079 ;; Table is not necessarily under a heading
1080 (setq beg (point-min) end (point-max)))
1082 ;; WE are at a heading, limit search to the body
1083 (setq beg (1+ (point-at-eol))
1084 end (save-excursion (outline-next-heading) (point)))))
1085 (if (re-search-forward org-table-dataline-regexp end t)
1086 (let ((b (org-table-begin)) (e (org-table-end)) (case-fold-search t))
1087 (goto-char e)
1088 (if (looking-at "[ \t]*#\\+tblfm:")
1089 (forward-line 1))
1090 (narrow-to-region b (point)))
1091 (goto-char end)
1092 (insert "\n| |\n|----|\n| |\n")
1093 (narrow-to-region (1+ end) (point)))
1094 ;; We are narrowed to the table, or to an empty line if there was no table
1096 ;; Check if the template is good
1097 (if (not (string-match org-table-dataline-regexp txt))
1098 (setq txt "| %?Bad template |\n"))
1099 (cond
1100 ((and table-line-pos
1101 (string-match "\\(I+\\)\\([-+][0-9]\\)" table-line-pos))
1102 ;; we have a complex line specification
1103 (goto-char (point-min))
1104 (let ((nh (- (match-end 1) (match-beginning 1)))
1105 (delta (string-to-number (match-string 2 table-line-pos)))
1107 ;; The user wants a special position in the table
1108 (org-table-get-specials)
1109 (setq ll (ignore-errors (aref org-table-hlines nh)))
1110 (unless ll (error "Invalid table line specification \"%s\""
1111 table-line-pos))
1112 (setq ll (+ ll delta (if (< delta 0) 0 -1)))
1113 (org-goto-line ll)
1114 (org-table-insert-row 'below)
1115 (beginning-of-line 1)
1116 (delete-region (point) (1+ (point-at-eol)))
1117 (setq beg (point))
1118 (insert txt)
1119 (setq end (point))))
1120 ((org-capture-get :prepend)
1121 (goto-char (point-min))
1122 (re-search-forward org-table-hline-regexp nil t)
1123 (beginning-of-line 1)
1124 (re-search-forward org-table-dataline-regexp nil t)
1125 (beginning-of-line 1)
1126 (setq beg (point))
1127 (org-table-insert-row)
1128 (beginning-of-line 1)
1129 (delete-region (point) (1+ (point-at-eol)))
1130 (insert txt)
1131 (setq end (point)))
1133 (goto-char (point-max))
1134 (re-search-backward org-table-dataline-regexp nil t)
1135 (beginning-of-line 1)
1136 (org-table-insert-row 'below)
1137 (beginning-of-line 1)
1138 (delete-region (point) (1+ (point-at-eol)))
1139 (setq beg (point))
1140 (insert txt)
1141 (setq end (point))))
1142 (goto-char beg)
1143 (org-capture-position-for-last-stored 'table-line)
1144 (if (or (re-search-backward "%\\?" beg t)
1145 (re-search-forward "%\\?" end t))
1146 (replace-match ""))
1147 (org-table-align)))
1149 (defun org-capture-place-plain-text ()
1150 "Place the template plainly.
1151 If the target locator points at an Org node, place the template into
1152 the text of the entry, before the first child. If not, place the
1153 template at the beginning or end of the file.
1154 Of course, if exact position has been required, just put it there."
1155 (let* ((txt (org-capture-get :template))
1156 beg end)
1157 (cond
1158 ((org-capture-get :exact-position)
1159 (goto-char (org-capture-get :exact-position)))
1160 ((and (org-capture-get :target-entry-p)
1161 (bolp)
1162 (looking-at org-outline-regexp))
1163 ;; we should place the text into this entry
1164 (if (org-capture-get :prepend)
1165 ;; Skip meta data and drawers
1166 (org-end-of-meta-data-and-drawers)
1167 ;; go to ent of the entry text, before the next headline
1168 (outline-next-heading)))
1170 ;; beginning or end of file
1171 (goto-char (if (org-capture-get :prepend) (point-min) (point-max)))))
1172 (or (bolp) (newline))
1173 (org-capture-empty-lines-before)
1174 (setq beg (point))
1175 (insert txt)
1176 (org-capture-empty-lines-after 1)
1177 (org-capture-position-for-last-stored beg)
1178 (setq end (point))
1179 (org-capture-mark-kill-region beg (1- end))
1180 (org-capture-narrow beg (1- end))
1181 (if (or (re-search-backward "%\\?" beg t)
1182 (re-search-forward "%\\?" end t))
1183 (replace-match ""))))
1185 (defun org-capture-mark-kill-region (beg end)
1186 "Mark the region that will have to be killed when aborting capture."
1187 (let ((m1 (move-marker (make-marker) beg))
1188 (m2 (move-marker (make-marker) end)))
1189 (org-capture-put :begin-marker m1)
1190 (org-capture-put :end-marker m2)))
1192 (defun org-capture-position-for-last-stored (where)
1193 "Memorize the position that should later become the position of last capture."
1194 (cond
1195 ((integerp where)
1196 (org-capture-put :position-for-last-stored
1197 (move-marker (make-marker) where
1198 (or (buffer-base-buffer (current-buffer))
1199 (current-buffer)))))
1200 ((eq where 'table-line)
1201 (org-capture-put :position-for-last-stored
1202 (list 'table-line
1203 (org-table-current-dline))))
1204 (t (error "This should not happen"))))
1206 (defun org-capture-bookmark-last-stored-position ()
1207 "Bookmark the last-captured position."
1208 (let* ((where (org-capture-get :position-for-last-stored 'local))
1209 (pos (cond
1210 ((markerp where)
1211 (prog1 (marker-position where)
1212 (move-marker where nil)))
1213 ((and (listp where) (eq (car where) 'table-line))
1214 (if (org-at-table-p)
1215 (save-excursion
1216 (org-table-goto-line (nth 1 where))
1217 (point-at-bol))
1218 (point))))))
1219 (with-current-buffer (buffer-base-buffer (current-buffer))
1220 (save-excursion
1221 (save-restriction
1222 (widen)
1223 (goto-char pos)
1224 (bookmark-set "org-capture-last-stored")
1225 (move-marker org-capture-last-stored-marker (point)))))))
1227 (defun org-capture-narrow (beg end)
1228 "Narrow, unless configuration says not to narrow."
1229 (unless (org-capture-get :unnarrowed)
1230 (narrow-to-region beg end)
1231 (goto-char beg)))
1233 (defun org-capture-empty-lines-before (&optional n)
1234 "Arrange for the correct number of empty lines before the insertion point.
1235 Point will be after the empty lines, so insertion can directly be done."
1236 (setq n (or n (org-capture-get :empty-lines-before)
1237 (org-capture-get :empty-lines) 0))
1238 (let ((pos (point)))
1239 (org-back-over-empty-lines)
1240 (delete-region (point) pos)
1241 (if (> n 0) (newline n))))
1243 (defun org-capture-empty-lines-after (&optional n)
1244 "Arrange for the correct number of empty lines after the inserted string.
1245 Point will remain at the first line after the inserted text."
1246 (setq n (or n (org-capture-get :empty-lines-after)
1247 (org-capture-get :empty-lines) 0))
1248 (org-back-over-empty-lines)
1249 (while (looking-at "[ \t]*\n") (replace-match ""))
1250 (let ((pos (point)))
1251 (if (> n 0) (newline n))
1252 (goto-char pos)))
1254 (defvar org-clock-marker) ; Defined in org.el
1255 ;;;###autoload
1256 (defun org-capture-insert-template-here ()
1257 (let* ((template (org-capture-get :template))
1258 (type (org-capture-get :type))
1259 beg end pp)
1260 (or (bolp) (newline))
1261 (setq beg (point))
1262 (cond
1263 ((and (eq type 'entry) (derived-mode-p 'org-mode))
1264 (org-capture-verify-tree (org-capture-get :template))
1265 (org-paste-subtree nil template t))
1266 ((and (memq type '(item checkitem))
1267 (derived-mode-p 'org-mode)
1268 (save-excursion (skip-chars-backward " \t\n")
1269 (setq pp (point))
1270 (org-in-item-p)))
1271 (goto-char pp)
1272 (org-insert-item)
1273 (skip-chars-backward " ")
1274 (skip-chars-backward "-+*0123456789).")
1275 (delete-region (point) (point-at-eol))
1276 (setq beg (point))
1277 (org-remove-indentation template)
1278 (insert template)
1279 (org-capture-empty-lines-after)
1280 (goto-char beg)
1281 (org-list-repair)
1282 (org-end-of-item)
1283 (setq end (point)))
1284 (t (insert template)))
1285 (setq end (point))
1286 (goto-char beg)
1287 (if (re-search-forward "%\\?" end t)
1288 (replace-match ""))))
1290 (defun org-capture-set-plist (entry)
1291 "Initialize the property list from the template definition."
1292 (setq org-capture-plist (copy-sequence (nthcdr 5 entry)))
1293 (org-capture-put :key (car entry) :description (nth 1 entry)
1294 :target (nth 3 entry))
1295 (let ((txt (nth 4 entry)) (type (or (nth 2 entry) 'entry)))
1296 (when (or (not txt) (and (stringp txt) (not (string-match "\\S-" txt))))
1297 ;; The template may be empty or omitted for special types.
1298 ;; Here we insert the default templates for such cases.
1299 (cond
1300 ((eq type 'item) (setq txt "- %?"))
1301 ((eq type 'checkitem) (setq txt "- [ ] %?"))
1302 ((eq type 'table-line) (setq txt "| %? |"))
1303 ((member type '(nil entry)) (setq txt "* %?\n %a"))))
1304 (org-capture-put :template txt :type type)))
1306 (defun org-capture-goto-target (&optional template-key)
1307 "Go to the target location of a capture template.
1308 The user is queried for the template."
1309 (interactive)
1310 (let* (org-select-template-temp-major-mode
1311 (entry (org-capture-select-template template-key)))
1312 (unless entry
1313 (error "No capture template selected"))
1314 (org-capture-set-plist entry)
1315 (org-capture-set-target-location)
1316 (org-pop-to-buffer-same-window (org-capture-get :buffer))
1317 (goto-char (org-capture-get :pos))))
1319 (defun org-capture-get-indirect-buffer (&optional buffer prefix)
1320 "Make an indirect buffer for a capture process.
1321 Use PREFIX as a prefix for the name of the indirect buffer."
1322 (setq buffer (or buffer (current-buffer)))
1323 (let ((n 1) (base (buffer-name buffer)) bname)
1324 (setq bname (concat prefix "-" base))
1325 (while (buffer-live-p (get-buffer bname))
1326 (setq bname (concat prefix "-" (number-to-string (incf n)) "-" base)))
1327 (condition-case nil
1328 (make-indirect-buffer buffer bname 'clone)
1329 (error
1330 (let ((buf (make-indirect-buffer buffer bname)))
1331 (with-current-buffer buf (org-mode))
1332 buf)))))
1334 (defun org-capture-verify-tree (tree)
1335 "Throw error if TREE is not a valid tree."
1336 (unless (org-kill-is-subtree-p tree)
1337 (error "Template is not a valid Org entry or tree")))
1339 ;;; The template code
1341 (defun org-capture-select-template (&optional keys)
1342 "Select a capture template.
1343 Lisp programs can force the template by setting KEYS to a string."
1344 (let ((org-capture-templates
1345 (or (org-contextualize-keys
1346 org-capture-templates org-capture-templates-contexts)
1347 '(("t" "Task" entry (file+headline "" "Tasks")
1348 "* TODO %?\n %u\n %a")))))
1349 (if keys
1350 (or (assoc keys org-capture-templates)
1351 (error "No capture template referred to by \"%s\" keys" keys))
1352 (org-mks org-capture-templates
1353 "Select a capture template\n========================="
1354 "Template key: "
1355 '(("C" "Customize org-capture-templates")
1356 ("q" "Abort"))))))
1358 (defun org-capture-fill-template (&optional template initial annotation)
1359 "Fill a template and return the filled template as a string.
1360 The template may still contain \"%?\" for cursor positioning."
1361 (setq template (or template (org-capture-get :template)))
1362 (when (stringp initial)
1363 (setq initial (org-no-properties initial)))
1364 (let* ((buffer (org-capture-get :buffer))
1365 (file (buffer-file-name (or (buffer-base-buffer buffer) buffer)))
1366 (ct (org-capture-get :default-time))
1367 (dct (decode-time ct))
1368 (ct1
1369 (if (< (nth 2 dct) org-extend-today-until)
1370 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
1371 ct))
1372 (plist-p (if org-store-link-plist t nil))
1373 (v-c (and (> (length kill-ring) 0) (current-kill 0)))
1374 (v-x (or (org-get-x-clipboard 'PRIMARY)
1375 (org-get-x-clipboard 'CLIPBOARD)
1376 (org-get-x-clipboard 'SECONDARY)))
1377 (v-t (format-time-string (car org-time-stamp-formats) ct))
1378 (v-T (format-time-string (cdr org-time-stamp-formats) ct))
1379 (v-u (concat "[" (substring v-t 1 -1) "]"))
1380 (v-U (concat "[" (substring v-T 1 -1) "]"))
1381 ;; `initial' and `annotation' might habe been passed.
1382 ;; But if the property list has them, we prefer those values
1383 (v-i (or (plist-get org-store-link-plist :initial)
1384 initial
1385 (org-capture-get :initial)
1386 ""))
1387 (v-a (or (plist-get org-store-link-plist :annotation)
1388 annotation
1389 (org-capture-get :annotation)
1390 ""))
1391 ;; Is the link empty? Then we do not want it...
1392 (v-a (if (equal v-a "[[]]") "" v-a))
1393 (clipboards (remove nil (list v-i
1394 (org-get-x-clipboard 'PRIMARY)
1395 (org-get-x-clipboard 'CLIPBOARD)
1396 (org-get-x-clipboard 'SECONDARY)
1397 v-c)))
1398 (l-re "\\[\\[\\(.*?\\)\\]\\(\\[.*?\\]\\)?\\]")
1399 (v-A (if (and v-a (string-match l-re v-a))
1400 (replace-match "[[\\1][%^{Link description}]]" nil nil v-a)
1401 v-a))
1402 (v-l (if (and v-a (string-match l-re v-a))
1403 (replace-match "\\1" nil nil v-a)
1404 v-a))
1405 (v-n user-full-name)
1406 (v-k (if (marker-buffer org-clock-marker)
1407 (org-no-properties org-clock-heading)))
1408 (v-K (if (marker-buffer org-clock-marker)
1409 (org-make-link-string
1410 (buffer-file-name (marker-buffer org-clock-marker))
1411 org-clock-heading)))
1412 (v-f (or (org-capture-get :original-file-nondirectory) ""))
1413 (v-F (or (org-capture-get :original-file) ""))
1415 (org-startup-folded nil)
1416 (org-inhibit-startup t)
1417 org-time-was-given org-end-time-was-given x
1418 prompt completions char time pos default histvar strings)
1420 (setq org-store-link-plist
1421 (plist-put org-store-link-plist :annotation v-a)
1422 org-store-link-plist
1423 (plist-put org-store-link-plist :initial v-i))
1424 (setq initial v-i)
1426 (unless template (setq template "") (message "No template") (ding)
1427 (sit-for 1))
1428 (save-window-excursion
1429 (delete-other-windows)
1430 (org-pop-to-buffer-same-window (get-buffer-create "*Capture*"))
1431 (erase-buffer)
1432 (insert template)
1433 (goto-char (point-min))
1434 (org-capture-steal-local-variables buffer)
1435 (setq buffer-file-name nil)
1437 ;; %[] Insert contents of a file.
1438 (goto-char (point-min))
1439 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
1440 (unless (org-capture-escaped-%)
1441 (let ((start (match-beginning 0))
1442 (end (match-end 0))
1443 (filename (expand-file-name (match-string 1))))
1444 (goto-char start)
1445 (delete-region start end)
1446 (condition-case error
1447 (insert-file-contents filename)
1448 (error (insert (format "%%![Couldn't insert %s: %s]"
1449 filename error)))))))
1450 ;; %() embedded elisp
1451 (org-capture-expand-embedded-elisp)
1453 ;; The current time
1454 (goto-char (point-min))
1455 (while (re-search-forward "%<\\([^>\n]+\\)>" nil t)
1456 (replace-match (format-time-string (match-string 1)) t t))
1458 ;; Simple %-escapes
1459 (goto-char (point-min))
1460 (while (re-search-forward "%\\([tTuUaliAcxkKInfF]\\)" nil t)
1461 (unless (org-capture-escaped-%)
1462 (when (and initial (equal (match-string 0) "%i"))
1463 (save-match-data
1464 (let* ((lead (buffer-substring
1465 (point-at-bol) (match-beginning 0))))
1466 (setq v-i (mapconcat 'identity
1467 (org-split-string initial "\n")
1468 (concat "\n" lead))))))
1469 (replace-match
1470 (or (org-add-props (eval (intern (concat "v-" (match-string 1))))
1471 '(org-protected t)) "")
1472 t t)))
1474 ;; From the property list
1475 (when plist-p
1476 (goto-char (point-min))
1477 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
1478 (unless (org-capture-escaped-%)
1479 (and (setq x (or (plist-get org-store-link-plist
1480 (intern (match-string 1))) ""))
1481 (replace-match x t t)))))
1483 ;; Turn on org-mode in temp buffer, set local variables
1484 ;; This is to support completion in interactive prompts
1485 (let ((org-inhibit-startup t)) (org-mode))
1486 ;; Interactive template entries
1487 (goto-char (point-min))
1488 (while (and (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGtTuUCLp]\\)?" nil t)
1489 (not (get-text-property (point) 'org-protected)))
1490 (unless (org-capture-escaped-%)
1491 (setq char (if (match-end 3) (match-string-no-properties 3))
1492 prompt (if (match-end 2) (match-string-no-properties 2)))
1493 (goto-char (match-beginning 0))
1494 (replace-match "")
1495 (setq completions nil default nil)
1496 (when prompt
1497 (setq completions (org-split-string prompt "|")
1498 prompt (pop completions)
1499 default (car completions)
1500 histvar (intern (concat
1501 "org-capture-template-prompt-history::"
1502 (or prompt "")))
1503 completions (mapcar 'list completions)))
1504 (unless (boundp histvar) (set histvar nil))
1505 (cond
1506 ((member char '("G" "g"))
1507 (let* ((org-last-tags-completion-table
1508 (org-global-tags-completion-table
1509 (if (equal char "G")
1510 (org-agenda-files)
1511 (and file (list file)))))
1512 (org-add-colon-after-tag-completion t)
1513 (ins (org-icompleting-read
1514 (if prompt (concat prompt ": ") "Tags: ")
1515 'org-tags-completion-function nil nil nil
1516 'org-tags-history)))
1517 (setq ins (mapconcat 'identity
1518 (org-split-string
1519 ins (org-re "[^[:alnum:]_@#%]+"))
1520 ":"))
1521 (when (string-match "\\S-" ins)
1522 (or (equal (char-before) ?:) (insert ":"))
1523 (insert ins)
1524 (or (equal (char-after) ?:) (insert ":"))
1525 (and (org-at-heading-p) (org-set-tags nil 'align)))))
1526 ((equal char "C")
1527 (cond ((= (length clipboards) 1) (insert (car clipboards)))
1528 ((> (length clipboards) 1)
1529 (insert (read-string "Clipboard/kill value: "
1530 (car clipboards) '(clipboards . 1)
1531 (car clipboards))))))
1532 ((equal char "L")
1533 (cond ((= (length clipboards) 1)
1534 (org-insert-link 0 (car clipboards)))
1535 ((> (length clipboards) 1)
1536 (org-insert-link 0 (read-string "Clipboard/kill value: "
1537 (car clipboards)
1538 '(clipboards . 1)
1539 (car clipboards))))))
1540 ((equal char "p")
1541 (org-set-property (org-no-properties prompt) nil))
1542 (char
1543 ;; These are the date/time related ones
1544 (setq org-time-was-given (equal (upcase char) char))
1545 (setq time (org-read-date (equal (upcase char) char) t nil
1546 prompt))
1547 (if (equal (upcase char) char) (setq org-time-was-given t))
1548 (org-insert-time-stamp time org-time-was-given
1549 (member char '("u" "U"))
1550 nil nil (list org-end-time-was-given)))
1552 (let (org-completion-use-ido)
1553 (push (org-completing-read-no-i
1554 (concat (if prompt prompt "Enter string")
1555 (if default (concat " [" default "]"))
1556 ": ")
1557 completions nil nil nil histvar default)
1558 strings)
1559 (insert (car strings)))))))
1560 ;; Replace %n escapes with nth %^{...} string
1561 (setq strings (nreverse strings))
1562 (goto-char (point-min))
1563 (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t)
1564 (unless (org-capture-escaped-%)
1565 (replace-match
1566 (nth (1- (string-to-number (match-string 1))) strings)
1567 nil t)))
1568 ;; Make sure there are no empty lines before the text, and that
1569 ;; it ends with a newline character
1570 (goto-char (point-min))
1571 (while (looking-at "[ \t]*\n") (replace-match ""))
1572 (if (re-search-forward "[ \t\n]*\\'" nil t) (replace-match "\n"))
1573 ;; Return the expanded template and kill the temporary buffer
1574 (untabify (point-min) (point-max))
1575 (set-buffer-modified-p nil)
1576 (prog1 (buffer-string) (kill-buffer (current-buffer))))))
1578 (defun org-capture-escaped-% ()
1579 "Check if % was escaped - if yes, unescape it now."
1580 (if (equal (char-before (match-beginning 0)) ?\\)
1581 (progn
1582 (delete-region (1- (match-beginning 0)) (match-beginning 0))
1584 nil))
1586 (defun org-capture-expand-embedded-elisp ()
1587 "Evaluate embedded elisp %(sexp) and replace with the result."
1588 (goto-char (point-min))
1589 (while (re-search-forward "%(" nil t)
1590 (unless (org-capture-escaped-%)
1591 (goto-char (match-beginning 0))
1592 (let ((template-start (point)))
1593 (forward-char 1)
1594 (let ((result (org-eval (read (current-buffer)))))
1595 (delete-region template-start (point))
1596 (insert result))))))
1598 (defun org-capture-inside-embedded-elisp-p ()
1599 "Return non-nil if point is inside of embedded elisp %(sexp)."
1600 (let (beg end)
1601 (with-syntax-table emacs-lisp-mode-syntax-table
1602 (save-excursion
1603 ;; `looking-at' and `search-backward' below do not match the "%(" if
1604 ;; point is in its middle
1605 (when (equal (char-before) ?%)
1606 (backward-char))
1607 (save-match-data
1608 (when (or (looking-at "%(") (search-backward "%(" nil t))
1609 (setq beg (point))
1610 (setq end (progn (forward-char) (forward-sexp) (1- (point)))))))
1611 (when (and beg end)
1612 (and (<= (point) end) (>= (point) beg))))))
1614 ;;;###autoload
1615 (defun org-capture-import-remember-templates ()
1616 "Set org-capture-templates to be similar to `org-remember-templates'."
1617 (interactive)
1618 (when (and (yes-or-no-p
1619 "Import old remember templates into org-capture-templates? ")
1620 (yes-or-no-p
1621 "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
1622 (require 'org-remember)
1623 (setq org-capture-templates
1624 (mapcar
1625 (lambda (entry)
1626 (let ((desc (car entry))
1627 (key (char-to-string (nth 1 entry)))
1628 (template (nth 2 entry))
1629 (file (or (nth 3 entry) org-default-notes-file))
1630 (position (or (nth 4 entry) org-remember-default-headline))
1631 (type 'entry)
1632 (prepend org-reverse-note-order)
1633 immediate target)
1634 (cond
1635 ((member position '(top bottom))
1636 (setq target (list 'file file)
1637 prepend (eq position 'top)))
1638 ((eq position 'date-tree)
1639 (setq target (list 'file+datetree file)
1640 prepend nil))
1641 (t (setq target (list 'file+headline file position))))
1643 (when (string-match "%!" template)
1644 (setq template (replace-match "" t t template)
1645 immediate t))
1647 (append (list key desc type target template)
1648 (if prepend '(:prepend t))
1649 (if immediate '(:immediate-finish t)))))
1651 org-remember-templates))))
1653 (provide 'org-capture)
1655 ;;; org-capture.el ends here