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