Update copyright years again.
[org-mode.git] / lisp / org-capture.el
blob8eaa313b28a758f0e3a4b05d6634a0e9b36ae73c
1 ;;; org-capture.el --- Fast note taking in Org-mode
3 ;; Copyright (C) 2010-2014 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 functionality
28 ;; that used to be 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 anymore
34 ;; for this 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)
54 (declare-function org-datetree-find-date-create "org-datetree"
55 (date &optional keep-restriction))
56 (declare-function org-table-get-specials "org-table" ())
57 (declare-function org-table-goto-line "org-table" (N))
58 (declare-function org-pop-to-buffer-same-window "org-compat"
59 (&optional buffer-or-name norecord label))
60 (declare-function org-at-encrypted-entry-p "org-crypt" ())
61 (declare-function org-encrypt-entry "org-crypt" ())
62 (declare-function org-decrypt-entry "org-crypt" ())
64 (defvar org-remember-default-headline)
65 (defvar org-remember-templates)
66 (defvar org-table-hlines)
67 (defvar dired-buffers)
69 (defvar org-capture-clock-was-started nil
70 "Internal flag, noting if the clock was started.")
72 (defvar org-capture-last-stored-marker (make-marker)
73 "Marker pointing to the entry most recently stored with `org-capture'.")
75 ;; The following variable is scoped dynamically by org-protocol
76 ;; to indicate that the link properties have already been stored
77 (defvar org-capture-link-is-already-stored nil)
79 (defgroup org-capture nil
80 "Options concerning capturing new entries."
81 :tag "Org Capture"
82 :group 'org)
84 (defcustom org-capture-templates nil
85 "Templates for the creation of new entries.
87 Each entry is a list with the following items:
89 keys The keys that will select the template, as a string, characters
90 only, for example \"a\" for a template to be selected with a
91 single key, or \"bt\" for selection with two keys. When using
92 several keys, keys using the same prefix key must be together
93 in the list and preceded by a 2-element entry explaining the
94 prefix key, for example
96 (\"b\" \"Templates for marking stuff to buy\")
98 The \"C\" key is used by default for quick access to the
99 customization of the template variable. But if you want to use
100 that key for a template, you can.
102 description A short string describing the template, will be shown during
103 selection.
105 type The type of entry. Valid types are:
106 entry an Org-mode node, with a headline. Will be
107 filed as the child of the target entry or as
108 a top-level entry.
109 item a plain list item, will be placed in the
110 first plain list at the target
111 location.
112 checkitem a checkbox item. This differs from the
113 plain list item only is so far as it uses a
114 different default template.
115 table-line a new line in the first table at target location.
116 plain text to be inserted as it is.
118 target Specification of where the captured item should be placed.
119 In Org-mode files, targets usually define a node. Entries will
120 become children of this node, other types will be added to the
121 table or list in the body of this node.
123 Most target specifications contain a file name. If that file
124 name is the empty string, it defaults to `org-default-notes-file'.
125 A file can also be given as a variable, function, or Emacs Lisp
126 form.
128 Valid values are:
130 (file \"path/to/file\")
131 Text will be placed at the beginning or end of that file
133 (id \"id of existing org entry\")
134 File as child of this entry, or in the body of the entry
136 (file+headline \"path/to/file\" \"node headline\")
137 Fast configuration if the target heading is unique in the file
139 (file+olp \"path/to/file\" \"Level 1 heading\" \"Level 2\" ...)
140 For non-unique headings, the full path is safer
142 (file+regexp \"path/to/file\" \"regexp to find location\")
143 File to the entry matching regexp
145 (file+datetree \"path/to/file\")
146 Will create a heading in a date tree for today's date
148 (file+datetree+prompt \"path/to/file\")
149 Will create a heading in a date tree, prompts for date
151 (file+function \"path/to/file\" function-finding-location)
152 A function to find the right location in the file
154 (clock)
155 File to the entry that is currently being clocked
157 (function function-finding-location)
158 Most general way, write your own function to find both
159 file and location
161 template The template for creating the capture item. If you leave this
162 empty, an appropriate default template will be used. See below
163 for more details. Instead of a string, this may also be one of
165 (file \"/path/to/template-file\")
166 (function function-returning-the-template)
168 in order to get a template from a file, or dynamically
169 from a function.
171 The rest of the entry is a property list of additional options. Recognized
172 properties are:
174 :prepend Normally newly captured information will be appended at
175 the target location (last child, last table line,
176 last list item...). Setting this property will
177 change that.
179 :immediate-finish When set, do not offer to edit the information, just
180 file it away immediately. This makes sense if the
181 template only needs information that can be added
182 automatically.
184 :jump-to-captured When set, jump to the captured entry when finished.
186 :empty-lines Set this to the number of lines the should be inserted
187 before and after the new item. Default 0, only common
188 other value is 1.
190 :empty-lines-before Set this to the number of lines the should be inserted
191 before the new item. Overrides :empty-lines for the
192 number lines inserted before.
194 :empty-lines-after Set this to the number of lines the should be inserted
195 after the new item. Overrides :empty-lines for the
196 number of lines inserted after.
198 :clock-in Start the clock in this item.
200 :clock-keep Keep the clock running when filing the captured entry.
202 :clock-resume Start the interrupted clock when finishing the capture.
203 Note that :clock-keep has precedence over :clock-resume.
204 When setting both to `t', the current clock will run and
205 the previous one will not be resumed.
207 :unnarrowed Do not narrow the target buffer, simply show the
208 full buffer. Default is to narrow it so that you
209 only see the new stuff.
211 :table-line-pos Specification of the location in the table where the
212 new line should be inserted. It should be a string like
213 \"II-3\", meaning that the new line should become the
214 third line before the second horizontal separator line.
216 :kill-buffer If the target file was not yet visited by a buffer when
217 capture was invoked, kill the buffer again after capture
218 is finalized.
220 The template defines the text to be inserted. Often this is an
221 org-mode entry (so the first line should start with a star) that
222 will be filed as a child of the target headline. It can also be
223 freely formatted text. Furthermore, the following %-escapes will
224 be replaced with content and expanded in this order:
226 %[pathname] Insert the contents of the file given by `pathname'.
227 %(sexp) Evaluate elisp `(sexp)' and replace it with the results.
228 For convenience, %:keyword (see below) placeholders within
229 the expression will be expanded prior to this.
230 %<...> The result of format-time-string on the ... format specification.
231 %t Time stamp, date only.
232 %T Time stamp with date and time.
233 %u, %U Like the above, but inactive time stamps.
234 %i Initial content, copied from the active region. If %i is
235 indented, the entire inserted text will be indented as well.
236 %a Annotation, normally the link created with `org-store-link'.
237 %A Like %a, but prompt for the description part.
238 %l Like %a, but only insert the literal link.
239 %c Current kill ring head.
240 %x Content of the X clipboard.
241 %k Title of currently clocked task.
242 %K Link to currently clocked task.
243 %n User name (taken from the variable `user-full-name').
244 %f File visited by current buffer when org-capture was called.
245 %F Full path of the file or directory visited by current buffer.
246 %:keyword Specific information for certain link types, see below.
247 %^g Prompt for tags, with completion on tags in target file.
248 %^G Prompt for tags, with completion on all tags in all agenda files.
249 %^t Like %t, but prompt for date. Similarly %^T, %^u, %^U.
250 You may define a prompt like: %^{Please specify birthday}t
251 %^C Interactive selection of which kill or clip to use.
252 %^L Like %^C, but insert as link.
253 %^{prop}p Prompt the user for a value for property `prop'.
254 %^{prompt} Prompt the user for a string and replace this sequence with it.
255 A default value and a completion table ca be specified like this:
256 %^{prompt|default|completion2|completion3|...}.
257 %? After completing the template, position cursor here.
258 %\\n Insert the text entered at the nth %^{prompt}, where `n' is
259 a number, starting from 1.
261 Apart from these general escapes, you can access information specific to
262 the link type that is created. For example, calling `org-capture' in emails
263 or in Gnus will record the author and the subject of the message, which you
264 can access with \"%:from\" and \"%:subject\", respectively. Here is a
265 complete list of what is recorded for each link type.
267 Link type | Available information
268 ------------------------+------------------------------------------------------
269 bbdb | %:type %:name %:company
270 vm, wl, mh, mew, rmail, | %:type %:subject %:message-id
271 gnus | %:from %:fromname %:fromaddress
272 | %:to %:toname %:toaddress
273 | %:fromto (either \"to NAME\" or \"from NAME\")
274 | %:date %:date-timestamp (as active timestamp)
275 | %:date-timestamp-inactive (as inactive timestamp)
276 gnus | %:group, for messages also all email fields
277 w3, w3m | %:type %:url
278 info | %:type %:file %:node
279 calendar | %:type %:date"
280 :group 'org-capture
281 :version "24.1"
282 :type
283 '(repeat
284 (choice :value ("" "" entry (file "~/org/notes.org") "")
285 (list :tag "Multikey description"
286 (string :tag "Keys ")
287 (string :tag "Description"))
288 (list :tag "Template entry"
289 (string :tag "Keys ")
290 (string :tag "Description ")
291 (choice :tag "Capture Type " :value entry
292 (const :tag "Org entry" entry)
293 (const :tag "Plain list item" item)
294 (const :tag "Checkbox item" checkitem)
295 (const :tag "Plain text" plain)
296 (const :tag "Table line" table-line))
297 (choice :tag "Target location"
298 (list :tag "File"
299 (const :format "" file)
300 (file :tag " File"))
301 (list :tag "ID"
302 (const :format "" id)
303 (string :tag " ID"))
304 (list :tag "File & Headline"
305 (const :format "" file+headline)
306 (file :tag " File ")
307 (string :tag " Headline"))
308 (list :tag "File & Outline path"
309 (const :format "" file+olp)
310 (file :tag " File ")
311 (repeat :tag "Outline path" :inline t
312 (string :tag "Headline")))
313 (list :tag "File & Regexp"
314 (const :format "" file+regexp)
315 (file :tag " File ")
316 (regexp :tag " Regexp"))
317 (list :tag "File & Date tree"
318 (const :format "" file+datetree)
319 (file :tag " File"))
320 (list :tag "File & Date tree, prompt for date"
321 (const :format "" file+datetree+prompt)
322 (file :tag " File"))
323 (list :tag "File & function"
324 (const :format "" file+function)
325 (file :tag " File ")
326 (sexp :tag " Function"))
327 (list :tag "Current clocking task"
328 (const :format "" clock))
329 (list :tag "Function"
330 (const :format "" function)
331 (sexp :tag " Function")))
332 (choice :tag "Template"
333 (string)
334 (list :tag "File"
335 (const :format "" file)
336 (file :tag "Template file"))
337 (list :tag "Function"
338 (const :format "" function)
339 (function :tag "Template function")))
340 (plist :inline t
341 ;; Give the most common options as checkboxes
342 :options (((const :format "%v " :prepend) (const t))
343 ((const :format "%v " :immediate-finish) (const t))
344 ((const :format "%v " :jump-to-captured) (const t))
345 ((const :format "%v " :empty-lines) (const 1))
346 ((const :format "%v " :empty-lines-before) (const 1))
347 ((const :format "%v " :empty-lines-after) (const 1))
348 ((const :format "%v " :clock-in) (const t))
349 ((const :format "%v " :clock-keep) (const t))
350 ((const :format "%v " :clock-resume) (const t))
351 ((const :format "%v " :unnarrowed) (const t))
352 ((const :format "%v " :table-line-pos) (const t))
353 ((const :format "%v " :kill-buffer) (const t))))))))
355 (defcustom org-capture-before-finalize-hook nil
356 "Hook that is run right before a capture process is finalized.
357 The capture buffer is still current when this hook runs and it is
358 widened to the entire buffer."
359 :group 'org-capture
360 :version "24.1"
361 :type 'hook)
363 (defcustom org-capture-after-finalize-hook nil
364 "Hook that is run right after a capture process is finalized.
365 Suitable for window cleanup."
366 :group 'org-capture
367 :version "24.1"
368 :type 'hook)
370 (defcustom org-capture-prepare-finalize-hook nil
371 "Hook that is run before the finalization starts.
372 The capture buffer is current and still narrowed."
373 :group 'org-capture
374 :version "24.1"
375 :type 'hook)
377 (defcustom org-capture-bookmark t
378 "When non-nil, add a bookmark pointing at the last stored
379 position when capturing."
380 :group 'org-capture
381 :version "24.3"
382 :type 'boolean)
384 ;;; The property list for keeping information about the capture process
386 (defvar org-capture-plist nil
387 "Plist for the current capture process, global, to avoid having to pass it.")
389 (defvar org-capture-current-plist nil
390 "Local variable holding the plist in a capture buffer.
391 This is used to store the plist for use when finishing a capture process
392 because another such process might have changed the global variable by then.
394 Each time a new capture buffer has been set up, the global `org-capture-plist'
395 is copied to this variable, which is local in the indirect buffer.")
397 (defvar org-capture-clock-keep nil
398 "Local variable to store the value of the :clock-keep parameter.
399 This is needed in case org-capture-finalize is called interactively.")
401 (defun org-capture-put (&rest stuff)
402 "Add properties to the capture property list `org-capture-plist'."
403 (while stuff
404 (setq org-capture-plist (plist-put org-capture-plist
405 (pop stuff) (pop stuff)))))
406 (defun org-capture-get (prop &optional local)
407 "Get properties from the capture property list `org-capture-plist'.
408 When LOCAL is set, use the local variable `org-capture-current-plist',
409 this is necessary after initialization of the capture process,
410 to avoid conflicts with other active capture processes."
411 (plist-get (if local org-capture-current-plist org-capture-plist) prop))
413 (defun org-capture-member (prop &optional local)
414 "Is PROP a property in `org-capture-plist'.
415 When LOCAL is set, use the local variable `org-capture-current-plist',
416 this is necessary after initialization of the capture process,
417 to avoid conflicts with other active capture processes."
418 (plist-get (if local org-capture-current-plist org-capture-plist) prop))
420 ;;; The minor mode
422 (defvar org-capture-mode-map (make-sparse-keymap)
423 "Keymap for `org-capture-mode', a minor mode.
424 Use this map to set additional keybindings for when Org-mode is used
425 for a capture buffer.")
427 (defvar org-capture-mode-hook nil
428 "Hook for the minor `org-capture-mode'.")
430 (define-minor-mode org-capture-mode
431 "Minor mode for special key bindings in a capture buffer.
433 Turning on this mode runs the normal hook `org-capture-mode-hook'."
434 nil " Rem" org-capture-mode-map
435 (org-set-local
436 'header-line-format
437 "Capture buffer. Finish `C-c C-c', refile `C-c C-w', abort `C-c C-k'."))
438 (define-key org-capture-mode-map "\C-c\C-c" 'org-capture-finalize)
439 (define-key org-capture-mode-map "\C-c\C-k" 'org-capture-kill)
440 (define-key org-capture-mode-map "\C-c\C-w" 'org-capture-refile)
442 ;;; The main commands
444 (defvar org-capture-initial nil)
445 (defvar org-capture-entry nil)
447 ;;;###autoload
448 (defun org-capture-string (string &optional keys)
449 "Capture STRING with the template selected by KEYS."
450 (interactive "sInitial text: \n")
451 (let ((org-capture-initial string)
452 (org-capture-entry (org-capture-select-template keys)))
453 (org-capture)))
455 (defcustom org-capture-templates-contexts nil
456 "Alist of capture templates and valid contexts.
458 For example, if you have a capture template \"c\" and you want
459 this template to be accessible only from `message-mode' buffers,
460 use this:
462 '((\"c\" ((in-mode . \"message-mode\"))))
464 Here are the available contexts definitions:
466 in-file: command displayed only in matching files
467 in-mode: command displayed only in matching modes
468 not-in-file: command not displayed in matching files
469 not-in-mode: command not displayed in matching modes
470 in-buffer: command displayed only in matching buffers
471 not-in-buffer: command not displayed in matching buffers
472 [function]: a custom function taking no argument
474 If you define several checks, the agenda command will be
475 accessible if there is at least one valid check.
477 You can also bind a key to another agenda custom command
478 depending on contextual rules.
480 '((\"c\" \"d\" ((in-mode . \"message-mode\"))))
482 Here it means: in `message-mode buffers', use \"c\" as the
483 key for the capture template otherwise associated with \"d\".
484 \(The template originally associated with \"d\" is not displayed
485 to avoid duplicates.)"
486 :version "24.3"
487 :group 'org-capture
488 :type '(repeat (list :tag "Rule"
489 (string :tag " Capture key")
490 (string :tag "Replace by template")
491 (repeat :tag "Available when"
492 (choice
493 (cons :tag "Condition"
494 (choice
495 (const :tag "In file" in-file)
496 (const :tag "Not in file" not-in-file)
497 (const :tag "In buffer" in-buffer)
498 (const :tag "Not in buffer" not-in-buffer)
499 (const :tag "In mode" in-mode)
500 (const :tag "Not in mode" not-in-mode))
501 (regexp))
502 (function :tag "Custom function"))))))
504 (defcustom org-capture-use-agenda-date nil
505 "Non-nil means use the date at point when capturing from agendas.
506 When nil, you can still capture using the date at point with \\[org-agenda-capture]."
507 :group 'org-capture
508 :version "24.3"
509 :type 'boolean)
511 ;;;###autoload
512 (defun org-capture (&optional goto keys)
513 "Capture something.
514 \\<org-capture-mode-map>
515 This will let you select a template from `org-capture-templates', and then
516 file the newly captured information. The text is immediately inserted
517 at the target location, and an indirect buffer is shown where you can
518 edit it. Pressing \\[org-capture-finalize] brings you back to the previous state
519 of Emacs, so that you can continue your work.
521 When called interactively with a \\[universal-argument] prefix argument GOTO, don't capture
522 anything, just go to the file/headline where the selected template
523 stores its notes. With a double prefix argument \
524 \\[universal-argument] \\[universal-argument], go to the last note
525 stored.
527 When called with a `C-0' (zero) prefix, insert a template at point.
529 ELisp programs can set KEYS to a string associated with a template
530 in `org-capture-templates'. In this case, interactive selection
531 will be bypassed.
533 If `org-capture-use-agenda-date' is non-nil, capturing from the
534 agenda will use the date at point as the default date. Then, a
535 `C-1' prefix will tell the capture process to use the HH:MM time
536 of the day at point (if any) or the current HH:MM time."
537 (interactive "P")
538 (when (and org-capture-use-agenda-date
539 (eq major-mode 'org-agenda-mode))
540 (setq org-overriding-default-time
541 (org-get-cursor-date (equal goto 1))))
542 (cond
543 ((equal goto '(4)) (org-capture-goto-target))
544 ((equal goto '(16)) (org-capture-goto-last-stored))
546 ;; FIXME: Are these needed?
547 (let* ((orig-buf (current-buffer))
548 (annotation (if (and (boundp 'org-capture-link-is-already-stored)
549 org-capture-link-is-already-stored)
550 (plist-get org-store-link-plist :annotation)
551 (ignore-errors (org-store-link nil))))
552 (entry (or org-capture-entry (org-capture-select-template keys)))
553 initial)
554 (setq initial (or org-capture-initial
555 (and (org-region-active-p)
556 (buffer-substring (point) (mark)))))
557 (when (stringp initial)
558 (remove-text-properties 0 (length initial) '(read-only t) initial))
559 (when (stringp annotation)
560 (remove-text-properties 0 (length annotation)
561 '(read-only t) annotation))
562 (cond
563 ((equal entry "C")
564 (customize-variable 'org-capture-templates))
565 ((equal entry "q")
566 (error "Abort"))
568 (org-capture-set-plist entry)
569 (org-capture-get-template)
570 (org-capture-put :original-buffer orig-buf
571 :original-file (or (buffer-file-name orig-buf)
572 (and (featurep 'dired)
573 (car (rassq orig-buf
574 dired-buffers))))
575 :original-file-nondirectory
576 (and (buffer-file-name orig-buf)
577 (file-name-nondirectory
578 (buffer-file-name orig-buf)))
579 :annotation annotation
580 :initial initial
581 :return-to-wconf (current-window-configuration)
582 :default-time
583 (or org-overriding-default-time
584 (org-current-time)))
585 (org-capture-set-target-location)
586 (condition-case error
587 (org-capture-put :template (org-capture-fill-template))
588 ((error quit)
589 (if (get-buffer "*Capture*") (kill-buffer "*Capture*"))
590 (error "Capture abort: %s" error)))
592 (setq org-capture-clock-keep (org-capture-get :clock-keep))
593 (if (equal goto 0)
594 ;;insert at point
595 (org-capture-insert-template-here)
596 (condition-case error
597 (org-capture-place-template
598 (equal (car (org-capture-get :target)) 'function))
599 ((error quit)
600 (if (and (buffer-base-buffer (current-buffer))
601 (string-match "\\`CAPTURE-" (buffer-name)))
602 (kill-buffer (current-buffer)))
603 (set-window-configuration (org-capture-get :return-to-wconf))
604 (error "Capture template `%s': %s"
605 (org-capture-get :key)
606 (nth 1 error))))
607 (if (and (derived-mode-p 'org-mode)
608 (org-capture-get :clock-in))
609 (condition-case nil
610 (progn
611 (if (org-clock-is-active)
612 (org-capture-put :interrupted-clock
613 (copy-marker org-clock-marker)))
614 (org-clock-in)
615 (org-set-local 'org-capture-clock-was-started t))
616 (error
617 "Could not start the clock in this capture buffer")))
618 (if (org-capture-get :immediate-finish)
619 (org-capture-finalize)))))))))
621 (defun org-capture-get-template ()
622 "Get the template from a file or a function if necessary."
623 (let ((txt (org-capture-get :template)) file)
624 (cond
625 ((and (listp txt) (eq (car txt) 'file))
626 (if (file-exists-p
627 (setq file (expand-file-name (nth 1 txt) org-directory)))
628 (setq txt (org-file-contents file))
629 (setq txt (format "* Template file %s not found" (nth 1 txt)))))
630 ((and (listp txt) (eq (car txt) 'function))
631 (if (fboundp (nth 1 txt))
632 (setq txt (funcall (nth 1 txt)))
633 (setq txt (format "* Template function %s not found" (nth 1 txt)))))
634 ((not txt) (setq txt ""))
635 ((stringp txt))
636 (t (setq txt "* Invalid capture template")))
637 (org-capture-put :template txt)))
639 (defun org-capture-finalize (&optional stay-with-capture)
640 "Finalize the capture process.
641 With prefix argument STAY-WITH-CAPTURE, jump to the location of the
642 captured item after finalizing."
643 (interactive "P")
644 (when (org-capture-get :jump-to-captured)
645 (setq stay-with-capture t))
646 (unless (and org-capture-mode
647 (buffer-base-buffer (current-buffer)))
648 (error "This does not seem to be a capture buffer for Org-mode"))
650 (run-hooks 'org-capture-prepare-finalize-hook)
652 ;; Did we start the clock in this capture buffer?
653 (when (and org-capture-clock-was-started
654 org-clock-marker (marker-buffer org-clock-marker)
655 (equal (marker-buffer org-clock-marker) (buffer-base-buffer))
656 (> org-clock-marker (point-min))
657 (< org-clock-marker (point-max)))
658 ;; Looks like the clock we started is still running. Clock out.
659 (when (not org-capture-clock-keep) (let (org-log-note-clock-out) (org-clock-out)))
660 (when (and (not org-capture-clock-keep)
661 (org-capture-get :clock-resume 'local)
662 (markerp (org-capture-get :interrupted-clock 'local))
663 (buffer-live-p (marker-buffer
664 (org-capture-get :interrupted-clock 'local))))
665 (let ((clock-in-task (org-capture-get :interrupted-clock 'local)))
666 (org-with-point-at clock-in-task
667 (org-clock-in)))
668 (message "Interrupted clock has been resumed")))
670 (let ((beg (point-min))
671 (end (point-max))
672 (abort-note nil))
673 ;; Store the size of the capture buffer
674 (org-capture-put :captured-entry-size (- (point-max) (point-min)))
675 (widen)
676 ;; Store the insertion point in the target buffer
677 (org-capture-put :insertion-point (point))
679 (if org-note-abort
680 (let ((m1 (org-capture-get :begin-marker 'local))
681 (m2 (org-capture-get :end-marker 'local)))
682 (if (and m1 m2 (= m1 beg) (= m2 end))
683 (progn
684 (setq m2 (if (cdr (assoc 'heading org-blank-before-new-entry))
685 m2 (1+ m2))
686 m2 (if (< (point-max) m2) (point-max) m2))
687 (setq abort-note 'clean)
688 (kill-region m1 m2))
689 (setq abort-note 'dirty)))
691 ;; Make sure that the empty lines after are correct
692 (when (and (> (point-max) end) ; indeed, the buffer was still narrowed
693 (member (org-capture-get :type 'local)
694 '(entry item checkitem plain)))
695 (save-excursion
696 (goto-char end)
697 (or (bolp) (newline))
698 (org-capture-empty-lines-after
699 (or (org-capture-get :empty-lines-after 'local)
700 (org-capture-get :empty-lines 'local) 0))))
701 ;; Postprocessing: Update Statistics cookies, do the sorting
702 (when (derived-mode-p 'org-mode)
703 (save-excursion
704 (when (ignore-errors (org-back-to-heading))
705 (org-update-parent-todo-statistics)
706 (org-update-checkbox-count)))
707 ;; FIXME Here we should do the sorting
708 ;; If we have added a table line, maybe recompute?
709 (when (and (eq (org-capture-get :type 'local) 'table-line)
710 (org-at-table-p))
711 (if (org-table-get-stored-formulas)
712 (org-table-recalculate 'all) ;; FIXME: Should we iterate???
713 (org-table-align))))
714 ;; Store this place as the last one where we stored something
715 ;; Do the marking in the base buffer, so that it makes sense after
716 ;; the indirect buffer has been killed.
717 (when org-capture-bookmark
718 (org-capture-bookmark-last-stored-position))
720 ;; Run the hook
721 (run-hooks 'org-capture-before-finalize-hook))
723 (when (org-capture-get :decrypted)
724 (save-excursion
725 (goto-char (org-capture-get :decrypted))
726 (org-encrypt-entry)))
728 ;; Kill the indirect buffer
729 (save-buffer)
730 (let ((return-wconf (org-capture-get :return-to-wconf 'local))
731 (new-buffer (org-capture-get :new-buffer 'local))
732 (kill-buffer (org-capture-get :kill-buffer 'local))
733 (base-buffer (buffer-base-buffer (current-buffer))))
735 ;; Kill the indirect buffer
736 (kill-buffer (current-buffer))
738 ;; Narrow back the target buffer to its previous state
739 (with-current-buffer (org-capture-get :buffer)
740 (let ((reg (org-capture-get :initial-target-region))
741 (pos (org-capture-get :initial-target-position))
742 (ipt (org-capture-get :insertion-point))
743 (size (org-capture-get :captured-entry-size)))
744 (when reg
745 (cond ((< ipt (car reg))
746 ;; insertion point is before the narrowed region
747 (narrow-to-region (+ size (car reg)) (+ size (cdr reg))))
748 ((> ipt (cdr reg))
749 ;; insertion point is after the narrowed region
750 (narrow-to-region (car reg) (cdr reg)))
752 ;; insertion point is within the narrowed region
753 (narrow-to-region (car reg) (+ size (cdr reg)))))
754 ;; now place back the point at its original position
755 (if (< ipt (car reg))
756 (goto-char (+ size pos))
757 (goto-char (if (< ipt pos) (+ size pos) pos))))))
759 ;; Kill the target buffer if that is desired
760 (when (and base-buffer new-buffer kill-buffer)
761 (with-current-buffer base-buffer (save-buffer))
762 (kill-buffer base-buffer))
764 ;; Restore the window configuration before capture
765 (set-window-configuration return-wconf))
767 (run-hooks 'org-capture-after-finalize-hook)
768 ;; Special cases
769 (cond
770 (abort-note
771 (cond
772 ((equal abort-note 'clean)
773 (message "Capture process aborted and target buffer cleaned up"))
774 ((equal abort-note 'dirty)
775 (error "Capture process aborted, but target buffer could not be cleaned up correctly"))))
776 (stay-with-capture
777 (org-capture-goto-last-stored)))
778 ;; Return if we did store something
779 (not abort-note)))
781 (defun org-capture-refile ()
782 "Finalize the current capture and then refile the entry.
783 Refiling is done from the base buffer, because the indirect buffer is then
784 already gone. Any prefix argument will be passed to the refile command."
785 (interactive)
786 (unless (eq (org-capture-get :type 'local) 'entry)
787 (error
788 "Refiling from a capture buffer makes only sense for `entry'-type templates"))
789 (let ((pos (point))
790 (base (buffer-base-buffer (current-buffer)))
791 (org-refile-for-capture t))
792 (save-window-excursion
793 (with-current-buffer (or base (current-buffer))
794 (save-excursion
795 (save-restriction
796 (widen)
797 (goto-char pos)
798 (call-interactively 'org-refile)))))
799 (org-capture-finalize)))
801 (defun org-capture-kill ()
802 "Abort the current capture process."
803 (interactive)
804 ;; FIXME: This does not do the right thing, we need to remove the
805 ;; new stuff by hand it is easy: undo, then kill the buffer
806 (let ((org-note-abort t)
807 (org-capture-before-finalize-hook nil))
808 (org-capture-finalize)))
810 (defun org-capture-goto-last-stored ()
811 "Go to the location where the last capture note was stored."
812 (interactive)
813 (org-goto-marker-or-bmk org-capture-last-stored-marker
814 "org-capture-last-stored")
815 (message "This is the last note stored by a capture process"))
817 ;;; Supporting functions for handling the process
819 (defun org-capture-put-target-region-and-position ()
820 "Store the initial region with `org-capture-put'."
821 (org-capture-put
822 :initial-target-region
823 ;; Check if the buffer is currently narrowed
824 (when (/= (buffer-size) (- (point-max) (point-min)))
825 (cons (point-min) (point-max))))
826 ;; store the current point
827 (org-capture-put :initial-target-position (point)))
829 (defvar org-time-was-given) ; dynamically scoped parameter
830 (defun org-capture-set-target-location (&optional target)
831 "Find TARGET buffer and position.
832 Store them in the capture property list."
833 (let ((target-entry-p t) decrypted-hl-pos)
834 (setq target (or target (org-capture-get :target)))
835 (save-excursion
836 (cond
837 ((eq (car target) 'file)
838 (set-buffer (org-capture-target-buffer (nth 1 target)))
839 (org-capture-put-target-region-and-position)
840 (widen)
841 (setq target-entry-p nil))
843 ((eq (car target) 'id)
844 (let ((loc (org-id-find (nth 1 target))))
845 (if (not loc)
846 (error "Cannot find target ID \"%s\"" (nth 1 target))
847 (set-buffer (org-capture-target-buffer (car loc)))
848 (widen)
849 (org-capture-put-target-region-and-position)
850 (goto-char (cdr loc)))))
852 ((eq (car target) 'file+headline)
853 (set-buffer (org-capture-target-buffer (nth 1 target)))
854 (org-capture-put-target-region-and-position)
855 (widen)
856 (let ((hd (nth 2 target)))
857 (goto-char (point-min))
858 (unless (derived-mode-p 'org-mode)
859 (error
860 "Target buffer \"%s\" for file+headline should be in Org mode"
861 (current-buffer)))
862 (if (re-search-forward
863 (format org-complex-heading-regexp-format (regexp-quote hd))
864 nil t)
865 (goto-char (point-at-bol))
866 (goto-char (point-max))
867 (or (bolp) (insert "\n"))
868 (insert "* " hd "\n")
869 (beginning-of-line 0))))
871 ((eq (car target) 'file+olp)
872 (let ((m (org-find-olp
873 (cons (org-capture-expand-file (nth 1 target))
874 (cddr target)))))
875 (set-buffer (marker-buffer m))
876 (org-capture-put-target-region-and-position)
877 (widen)
878 (goto-char m)))
880 ((eq (car target) 'file+regexp)
881 (set-buffer (org-capture-target-buffer (nth 1 target)))
882 (org-capture-put-target-region-and-position)
883 (widen)
884 (goto-char (point-min))
885 (if (re-search-forward (nth 2 target) nil t)
886 (progn
887 (goto-char (if (org-capture-get :prepend)
888 (match-beginning 0) (match-end 0)))
889 (org-capture-put :exact-position (point))
890 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
891 (error "No match for target regexp in file %s" (nth 1 target))))
893 ((memq (car target) '(file+datetree file+datetree+prompt))
894 (require 'org-datetree)
895 (set-buffer (org-capture-target-buffer (nth 1 target)))
896 (org-capture-put-target-region-and-position)
897 (widen)
898 ;; Make a date tree entry, with the current date (or yesterday,
899 ;; if we are extending dates for a couple of hours)
900 (org-datetree-find-date-create
901 (calendar-gregorian-from-absolute
902 (cond
903 (org-overriding-default-time
904 ;; use the overriding default time
905 (time-to-days org-overriding-default-time))
907 ((eq (car target) 'file+datetree+prompt)
908 ;; prompt for date
909 (let ((prompt-time (org-read-date
910 nil t nil "Date for tree entry:"
911 (current-time))))
912 (org-capture-put
913 :default-time
914 (cond ((and (or (not (boundp 'org-time-was-given))
915 (not org-time-was-given))
916 (not (= (time-to-days prompt-time) (org-today))))
917 ;; Use 00:00 when no time is given for another date than today?
918 (apply 'encode-time (append '(0 0 0) (cdddr (decode-time prompt-time)))))
919 ((string-match "\\([^ ]+\\)--?[^ ]+[ ]+\\(.*\\)" org-read-date-final-answer)
920 ;; Replace any time range by its start
921 (apply 'encode-time
922 (org-read-date-analyze
923 (replace-match "\\1 \\2" nil nil org-read-date-final-answer)
924 prompt-time (decode-time prompt-time))))
925 (t prompt-time)))
926 (time-to-days prompt-time)))
928 ;; current date, possibly corrected for late night workers
929 (org-today))))))
931 ((eq (car target) 'file+function)
932 (set-buffer (org-capture-target-buffer (nth 1 target)))
933 (org-capture-put-target-region-and-position)
934 (widen)
935 (funcall (nth 2 target))
936 (org-capture-put :exact-position (point))
937 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
939 ((eq (car target) 'function)
940 (funcall (nth 1 target))
941 (org-capture-put :exact-position (point))
942 (setq target-entry-p (and (derived-mode-p 'org-mode) (org-at-heading-p))))
944 ((eq (car target) 'clock)
945 (if (and (markerp org-clock-hd-marker)
946 (marker-buffer org-clock-hd-marker))
947 (progn (set-buffer (marker-buffer org-clock-hd-marker))
948 (org-capture-put-target-region-and-position)
949 (widen)
950 (goto-char org-clock-hd-marker))
951 (error "No running clock that could be used as capture target")))
953 (t (error "Invalid capture target specification")))
955 (when (and (featurep 'org-crypt) (org-at-encrypted-entry-p))
956 (org-decrypt-entry)
957 (setq decrypted-hl-pos
958 (save-excursion (and (org-back-to-heading t) (point)))))
960 (org-capture-put :buffer (current-buffer) :pos (point)
961 :target-entry-p target-entry-p
962 :decrypted decrypted-hl-pos))))
964 (defun org-capture-expand-file (file)
965 "Expand functions and symbols for FILE.
966 When FILE is a function, call it. When it is a form, evaluate
967 it. When it is a variable, retrieve the value. Return whatever we get."
968 (cond
969 ((org-string-nw-p file) file)
970 ((functionp file) (funcall file))
971 ((and (symbolp file) (boundp file)) (symbol-value file))
972 ((and file (consp file)) (eval file))
973 (t file)))
975 (defun org-capture-target-buffer (file)
976 "Get a buffer for FILE."
977 (setq file (org-capture-expand-file file))
978 (setq file (or (org-string-nw-p file)
979 org-default-notes-file
980 (error "No notes file specified, and no default available")))
981 (or (org-find-base-buffer-visiting file)
982 (progn (org-capture-put :new-buffer t)
983 (find-file-noselect (expand-file-name file org-directory)))))
985 (defun org-capture-steal-local-variables (buffer)
986 "Install Org-mode local variables of BUFFER."
987 (mapc (lambda (v)
988 (ignore-errors (org-set-local (car v) (cdr v))))
989 (buffer-local-variables buffer)))
991 (defun org-capture-place-template (&optional inhibit-wconf-store)
992 "Insert the template at the target location, and display the buffer.
993 When `inhibit-wconf-store', don't store the window configuration, as it
994 may have been stored before."
995 (unless inhibit-wconf-store
996 (org-capture-put :return-to-wconf (current-window-configuration)))
997 (delete-other-windows)
998 (org-switch-to-buffer-other-window
999 (org-capture-get-indirect-buffer (org-capture-get :buffer) "CAPTURE"))
1000 (widen)
1001 (show-all)
1002 (goto-char (org-capture-get :pos))
1003 (org-set-local 'org-capture-target-marker
1004 (point-marker))
1005 (org-set-local 'outline-level 'org-outline-level)
1006 (let* ((template (org-capture-get :template))
1007 (type (org-capture-get :type)))
1008 (case type
1009 ((nil entry) (org-capture-place-entry))
1010 (table-line (org-capture-place-table-line))
1011 (plain (org-capture-place-plain-text))
1012 (item (org-capture-place-item))
1013 (checkitem (org-capture-place-item))))
1014 (org-capture-mode 1)
1015 (org-set-local 'org-capture-current-plist org-capture-plist))
1017 (defun org-capture-place-entry ()
1018 "Place the template as a new Org entry."
1019 (let* ((txt (org-capture-get :template))
1020 (reversed (org-capture-get :prepend))
1021 (target-entry-p (org-capture-get :target-entry-p))
1022 level beg end file)
1024 (cond
1025 ((org-capture-get :exact-position)
1026 (goto-char (org-capture-get :exact-position)))
1027 ((not target-entry-p)
1028 ;; Insert as top-level entry, either at beginning or at end of file
1029 (setq level 1)
1030 (if reversed
1031 (progn (goto-char (point-min))
1032 (or (org-at-heading-p)
1033 (outline-next-heading)))
1034 (goto-char (point-max))
1035 (or (bolp) (insert "\n"))))
1037 ;; Insert as a child of the current entry
1038 (and (looking-at "\\*+")
1039 (setq level (- (match-end 0) (match-beginning 0))))
1040 (setq level (org-get-valid-level (or level 1) 1))
1041 (if reversed
1042 (progn
1043 (outline-next-heading)
1044 (or (bolp) (insert "\n")))
1045 (org-end-of-subtree t nil)
1046 (or (bolp) (insert "\n")))))
1047 (org-capture-empty-lines-before)
1048 (setq beg (point))
1049 (org-capture-verify-tree txt)
1050 (org-paste-subtree level txt 'for-yank)
1051 (org-capture-empty-lines-after 1)
1052 (org-capture-position-for-last-stored beg)
1053 (outline-next-heading)
1054 (setq end (point))
1055 (org-capture-mark-kill-region beg (1- end))
1056 (org-capture-narrow beg (1- end))
1057 (if (or (re-search-backward "%\\?" beg t)
1058 (re-search-forward "%\\?" end t))
1059 (replace-match ""))))
1061 (defun org-capture-place-item ()
1062 "Place the template as a new plain list item."
1063 (let* ((txt (org-capture-get :template))
1064 (target-entry-p (org-capture-get :target-entry-p))
1065 (ind 0)
1066 beg end)
1067 (if (org-capture-get :exact-position)
1068 (goto-char (org-capture-get :exact-position))
1069 (cond
1070 ((not target-entry-p)
1071 ;; Insert as top-level entry, either at beginning or at end of file
1072 (setq beg (point-min) end (point-max)))
1074 (setq beg (1+ (point-at-eol))
1075 end (save-excursion (outline-next-heading) (point)))))
1076 (if (org-capture-get :prepend)
1077 (progn
1078 (goto-char beg)
1079 (if (org-list-search-forward (org-item-beginning-re) end t)
1080 (progn
1081 (goto-char (match-beginning 0))
1082 (setq ind (org-get-indentation)))
1083 (goto-char end)
1084 (setq ind 0)))
1085 (goto-char end)
1086 (if (org-list-search-backward (org-item-beginning-re) beg t)
1087 (progn
1088 (setq ind (org-get-indentation))
1089 (org-end-of-item))
1090 (setq ind 0))))
1091 ;; Remove common indentation
1092 (setq txt (org-remove-indentation txt))
1093 ;; Make sure this is indeed an item
1094 (unless (string-match (concat "\\`" (org-item-re)) txt)
1095 (setq txt (concat "- "
1096 (mapconcat 'identity (split-string txt "\n")
1097 "\n "))))
1098 ;; Set the correct indentation, depending on context
1099 (setq ind (make-string ind ?\ ))
1100 (setq txt (concat ind
1101 (mapconcat 'identity (split-string txt "\n")
1102 (concat "\n" ind))
1103 "\n"))
1104 ;; Insert, with surrounding empty lines
1105 (org-capture-empty-lines-before)
1106 (setq beg (point))
1107 (insert txt)
1108 (or (bolp) (insert "\n"))
1109 (org-capture-empty-lines-after 1)
1110 (org-capture-position-for-last-stored beg)
1111 (forward-char 1)
1112 (setq end (point))
1113 (org-capture-mark-kill-region beg (1- end))
1114 (org-capture-narrow beg (1- end))
1115 (if (or (re-search-backward "%\\?" beg t)
1116 (re-search-forward "%\\?" end t))
1117 (replace-match ""))))
1119 (defun org-capture-place-table-line ()
1120 "Place the template as a table line."
1121 (require 'org-table)
1122 (let* ((txt (org-capture-get :template))
1123 (target-entry-p (org-capture-get :target-entry-p))
1124 (table-line-pos (org-capture-get :table-line-pos))
1125 ind beg end)
1126 (cond
1127 ((org-capture-get :exact-position)
1128 (goto-char (org-capture-get :exact-position)))
1129 ((not target-entry-p)
1130 ;; Table is not necessarily under a heading
1131 (setq beg (point-min) end (point-max)))
1133 ;; WE are at a heading, limit search to the body
1134 (setq beg (1+ (point-at-eol))
1135 end (save-excursion (outline-next-heading) (point)))))
1136 (if (re-search-forward org-table-dataline-regexp end t)
1137 (let ((b (org-table-begin)) (e (org-table-end)) (case-fold-search t))
1138 (goto-char e)
1139 (if (looking-at "[ \t]*#\\+tblfm:")
1140 (forward-line 1))
1141 (narrow-to-region b (point)))
1142 (goto-char end)
1143 (insert "\n| |\n|----|\n| |\n")
1144 (narrow-to-region (1+ end) (point)))
1145 ;; We are narrowed to the table, or to an empty line if there was no table
1147 ;; Check if the template is good
1148 (if (not (string-match org-table-dataline-regexp txt))
1149 (setq txt "| %?Bad template |\n"))
1150 (cond
1151 ((and table-line-pos
1152 (string-match "\\(I+\\)\\([-+][0-9]\\)" table-line-pos))
1153 ;; we have a complex line specification
1154 (goto-char (point-min))
1155 (let ((nh (- (match-end 1) (match-beginning 1)))
1156 (delta (string-to-number (match-string 2 table-line-pos)))
1158 ;; The user wants a special position in the table
1159 (org-table-get-specials)
1160 (setq ll (ignore-errors (aref org-table-hlines nh)))
1161 (unless ll (error "Invalid table line specification \"%s\""
1162 table-line-pos))
1163 (setq ll (+ ll delta (if (< delta 0) 0 -1)))
1164 (org-goto-line ll)
1165 (org-table-insert-row 'below)
1166 (beginning-of-line 1)
1167 (delete-region (point) (1+ (point-at-eol)))
1168 (setq beg (point))
1169 (insert txt)
1170 (setq end (point))))
1171 ((org-capture-get :prepend)
1172 (goto-char (point-min))
1173 (re-search-forward org-table-hline-regexp nil t)
1174 (beginning-of-line 1)
1175 (re-search-forward org-table-dataline-regexp nil t)
1176 (beginning-of-line 1)
1177 (setq beg (point))
1178 (org-table-insert-row)
1179 (beginning-of-line 1)
1180 (delete-region (point) (1+ (point-at-eol)))
1181 (insert txt)
1182 (setq end (point)))
1184 (goto-char (point-max))
1185 (re-search-backward org-table-dataline-regexp nil t)
1186 (beginning-of-line 1)
1187 (org-table-insert-row 'below)
1188 (beginning-of-line 1)
1189 (delete-region (point) (1+ (point-at-eol)))
1190 (setq beg (point))
1191 (insert txt)
1192 (setq end (point))))
1193 (goto-char beg)
1194 (org-capture-position-for-last-stored 'table-line)
1195 (if (or (re-search-backward "%\\?" beg t)
1196 (re-search-forward "%\\?" end t))
1197 (replace-match ""))
1198 (org-table-align)))
1200 (defun org-capture-place-plain-text ()
1201 "Place the template plainly.
1202 If the target locator points at an Org node, place the template into
1203 the text of the entry, before the first child. If not, place the
1204 template at the beginning or end of the file.
1205 Of course, if exact position has been required, just put it there."
1206 (let* ((txt (org-capture-get :template))
1207 beg end)
1208 (cond
1209 ((org-capture-get :exact-position)
1210 (goto-char (org-capture-get :exact-position)))
1211 ((and (org-capture-get :target-entry-p)
1212 (bolp)
1213 (looking-at org-outline-regexp))
1214 ;; we should place the text into this entry
1215 (if (org-capture-get :prepend)
1216 ;; Skip meta data and drawers
1217 (org-end-of-meta-data-and-drawers)
1218 ;; go to ent of the entry text, before the next headline
1219 (outline-next-heading)))
1221 ;; beginning or end of file
1222 (goto-char (if (org-capture-get :prepend) (point-min) (point-max)))))
1223 (or (bolp) (newline))
1224 (org-capture-empty-lines-before)
1225 (setq beg (point))
1226 (insert txt)
1227 (org-capture-empty-lines-after 1)
1228 (org-capture-position-for-last-stored beg)
1229 (setq end (point))
1230 (org-capture-mark-kill-region beg (1- end))
1231 (org-capture-narrow beg (1- end))
1232 (if (or (re-search-backward "%\\?" beg t)
1233 (re-search-forward "%\\?" end t))
1234 (replace-match ""))))
1236 (defun org-capture-mark-kill-region (beg end)
1237 "Mark the region that will have to be killed when aborting capture."
1238 (let ((m1 (move-marker (make-marker) beg))
1239 (m2 (move-marker (make-marker) end)))
1240 (org-capture-put :begin-marker m1)
1241 (org-capture-put :end-marker m2)))
1243 (defun org-capture-position-for-last-stored (where)
1244 "Memorize the position that should later become the position of last capture."
1245 (cond
1246 ((integerp where)
1247 (org-capture-put :position-for-last-stored
1248 (move-marker (make-marker) where
1249 (or (buffer-base-buffer (current-buffer))
1250 (current-buffer)))))
1251 ((eq where 'table-line)
1252 (org-capture-put :position-for-last-stored
1253 (list 'table-line
1254 (org-table-current-dline))))
1255 (t (error "This should not happen"))))
1257 (defun org-capture-bookmark-last-stored-position ()
1258 "Bookmark the last-captured position."
1259 (let* ((where (org-capture-get :position-for-last-stored 'local))
1260 (pos (cond
1261 ((markerp where)
1262 (prog1 (marker-position where)
1263 (move-marker where nil)))
1264 ((and (listp where) (eq (car where) 'table-line))
1265 (if (org-at-table-p)
1266 (save-excursion
1267 (org-table-goto-line (nth 1 where))
1268 (point-at-bol))
1269 (point))))))
1270 (with-current-buffer (buffer-base-buffer (current-buffer))
1271 (save-excursion
1272 (save-restriction
1273 (widen)
1274 (goto-char pos)
1275 (let ((bookmark-name (plist-get org-bookmark-names-plist
1276 :last-capture)))
1277 (when bookmark-name
1278 (with-demoted-errors
1279 (bookmark-set bookmark-name))))
1280 (move-marker org-capture-last-stored-marker (point)))))))
1282 (defun org-capture-narrow (beg end)
1283 "Narrow, unless configuration says not to narrow."
1284 (unless (org-capture-get :unnarrowed)
1285 (narrow-to-region beg end)
1286 (goto-char beg)))
1288 (defun org-capture-empty-lines-before (&optional n)
1289 "Set the correct number of empty lines before the insertion point.
1290 Point will be after the empty lines, so insertion can directly be done."
1291 (setq n (or n (org-capture-get :empty-lines-before)
1292 (org-capture-get :empty-lines) 0))
1293 (let ((pos (point)))
1294 (org-back-over-empty-lines)
1295 (delete-region (point) pos)
1296 (if (> n 0) (newline n))))
1298 (defun org-capture-empty-lines-after (&optional n)
1299 "Set the correct number of empty lines after the inserted string.
1300 Point will remain at the first line after the inserted text."
1301 (setq n (or n (org-capture-get :empty-lines-after)
1302 (org-capture-get :empty-lines) 0))
1303 (org-back-over-empty-lines)
1304 (while (looking-at "[ \t]*\n") (replace-match ""))
1305 (let ((pos (point)))
1306 (if (> n 0) (newline n))
1307 (goto-char pos)))
1309 (defvar org-clock-marker) ; Defined in org.el
1311 (defun org-capture-insert-template-here ()
1312 "Insert the capture template at point."
1313 (let* ((template (org-capture-get :template))
1314 (type (org-capture-get :type))
1315 beg end pp)
1316 (or (bolp) (newline))
1317 (setq beg (point))
1318 (cond
1319 ((and (eq type 'entry) (derived-mode-p 'org-mode))
1320 (org-capture-verify-tree (org-capture-get :template))
1321 (org-paste-subtree nil template t))
1322 ((and (memq type '(item checkitem))
1323 (derived-mode-p 'org-mode)
1324 (save-excursion (skip-chars-backward " \t\n")
1325 (setq pp (point))
1326 (org-in-item-p)))
1327 (goto-char pp)
1328 (org-insert-item)
1329 (skip-chars-backward " ")
1330 (skip-chars-backward "-+*0123456789).")
1331 (delete-region (point) (point-at-eol))
1332 (setq beg (point))
1333 (org-remove-indentation template)
1334 (insert template)
1335 (org-capture-empty-lines-after)
1336 (goto-char beg)
1337 (org-list-repair)
1338 (org-end-of-item)
1339 (setq end (point)))
1340 (t (insert template)))
1341 (setq end (point))
1342 (goto-char beg)
1343 (if (re-search-forward "%\\?" end t)
1344 (replace-match ""))))
1346 (defun org-capture-set-plist (entry)
1347 "Initialize the property list from the template definition."
1348 (setq org-capture-plist (copy-sequence (nthcdr 5 entry)))
1349 (org-capture-put :key (car entry) :description (nth 1 entry)
1350 :target (nth 3 entry))
1351 (let ((txt (nth 4 entry)) (type (or (nth 2 entry) 'entry)))
1352 (when (or (not txt) (and (stringp txt) (not (string-match "\\S-" txt))))
1353 ;; The template may be empty or omitted for special types.
1354 ;; Here we insert the default templates for such cases.
1355 (cond
1356 ((eq type 'item) (setq txt "- %?"))
1357 ((eq type 'checkitem) (setq txt "- [ ] %?"))
1358 ((eq type 'table-line) (setq txt "| %? |"))
1359 ((member type '(nil entry)) (setq txt "* %?\n %a"))))
1360 (org-capture-put :template txt :type type)))
1362 (defun org-capture-goto-target (&optional template-key)
1363 "Go to the target location of a capture template.
1364 The user is queried for the template."
1365 (interactive)
1366 (let* (org-select-template-temp-major-mode
1367 (entry (org-capture-select-template template-key)))
1368 (unless entry
1369 (error "No capture template selected"))
1370 (org-capture-set-plist entry)
1371 (org-capture-set-target-location)
1372 (org-pop-to-buffer-same-window (org-capture-get :buffer))
1373 (goto-char (org-capture-get :pos))))
1375 (defun org-capture-get-indirect-buffer (&optional buffer prefix)
1376 "Make an indirect buffer for a capture process.
1377 Use PREFIX as a prefix for the name of the indirect buffer."
1378 (setq buffer (or buffer (current-buffer)))
1379 (let ((n 1) (base (buffer-name buffer)) bname)
1380 (setq bname (concat prefix "-" base))
1381 (while (buffer-live-p (get-buffer bname))
1382 (setq bname (concat prefix "-" (number-to-string (incf n)) "-" base)))
1383 (condition-case nil
1384 (make-indirect-buffer buffer bname 'clone)
1385 (error
1386 (let ((buf (make-indirect-buffer buffer bname)))
1387 (with-current-buffer buf (org-mode))
1388 buf)))))
1390 (defun org-capture-verify-tree (tree)
1391 "Throw error if TREE is not a valid tree."
1392 (unless (org-kill-is-subtree-p tree)
1393 (error "Template is not a valid Org entry or tree")))
1395 (defun org-mks (table title &optional prompt specials)
1396 "Select a member of an alist with multiple keys.
1397 TABLE is the alist which should contain entries where the car is a string.
1398 There should be two types of entries.
1400 1. prefix descriptions like (\"a\" \"Description\")
1401 This indicates that `a' is a prefix key for multi-letter selection, and
1402 that there are entries following with keys like \"ab\", \"ax\"...
1404 2. Selectable members must have more than two elements, with the first
1405 being the string of keys that lead to selecting it, and the second a
1406 short description string of the item.
1408 The command will then make a temporary buffer listing all entries
1409 that can be selected with a single key, and all the single key
1410 prefixes. When you press the key for a single-letter entry, it is selected.
1411 When you press a prefix key, the commands (and maybe further prefixes)
1412 under this key will be shown and offered for selection.
1414 TITLE will be placed over the selection in the temporary buffer,
1415 PROMPT will be used when prompting for a key. SPECIAL is an alist with
1416 also (\"key\" \"description\") entries. When one of these is selection,
1417 only the bare key is returned."
1418 (setq prompt (or prompt "Select: "))
1419 (let (tbl orig-table dkey ddesc des-keys allowed-keys
1420 current prefix rtn re pressed buffer (inhibit-quit t))
1421 (save-window-excursion
1422 (setq buffer (org-switch-to-buffer-other-window "*Org Select*"))
1423 (setq orig-table table)
1424 (catch 'exit
1425 (while t
1426 (erase-buffer)
1427 (insert title "\n\n")
1428 (setq tbl table
1429 des-keys nil
1430 allowed-keys nil
1431 cursor-type nil)
1432 (setq prefix (if current (concat current " ") ""))
1433 (while tbl
1434 (cond
1435 ((and (= 2 (length (car tbl))) (= (length (caar tbl)) 1))
1436 ;; This is a description on this level
1437 (setq dkey (caar tbl) ddesc (cadar tbl))
1438 (pop tbl)
1439 (push dkey des-keys)
1440 (push dkey allowed-keys)
1441 (insert prefix "[" dkey "]" "..." " " ddesc "..." "\n")
1442 ;; Skip keys which are below this prefix
1443 (setq re (concat "\\`" (regexp-quote dkey)))
1444 (let (case-fold-search)
1445 (while (and tbl (string-match re (caar tbl))) (pop tbl))))
1446 ((= 2 (length (car tbl)))
1447 ;; Not yet a usable description, skip it
1450 ;; usable entry on this level
1451 (insert prefix "[" (caar tbl) "]" " " (nth 1 (car tbl)) "\n")
1452 (push (caar tbl) allowed-keys)
1453 (pop tbl))))
1454 (when specials
1455 (insert "-------------------------------------------------------------------------------\n")
1456 (let ((sp specials))
1457 (while sp
1458 (insert (format "[%s] %s\n"
1459 (caar sp) (nth 1 (car sp))))
1460 (push (caar sp) allowed-keys)
1461 (pop sp))))
1462 (push "\C-g" allowed-keys)
1463 (goto-char (point-min))
1464 (if (not (pos-visible-in-window-p (point-max)))
1465 (org-fit-window-to-buffer))
1466 (message prompt)
1467 (setq pressed (char-to-string (read-char-exclusive)))
1468 (while (not (member pressed allowed-keys))
1469 (message "Invalid key `%s'" pressed) (sit-for 1)
1470 (message prompt)
1471 (setq pressed (char-to-string (read-char-exclusive))))
1472 (when (equal pressed "\C-g")
1473 (kill-buffer buffer)
1474 (error "Abort"))
1475 (when (and (not (assoc pressed table))
1476 (not (member pressed des-keys))
1477 (assoc pressed specials))
1478 (throw 'exit (setq rtn pressed)))
1479 (unless (member pressed des-keys)
1480 (throw 'exit (setq rtn (rassoc (cdr (assoc pressed table))
1481 orig-table))))
1482 (setq current (concat current pressed))
1483 (setq table (mapcar
1484 (lambda (x)
1485 (if (and (> (length (car x)) 1)
1486 (equal (substring (car x) 0 1) pressed))
1487 (cons (substring (car x) 1) (cdr x))
1488 nil))
1489 table))
1490 (setq table (remove nil table)))))
1491 (when buffer (kill-buffer buffer))
1492 rtn))
1494 ;;; The template code
1495 (defun org-capture-select-template (&optional keys)
1496 "Select a capture template.
1497 Lisp programs can force the template by setting KEYS to a string."
1498 (let ((org-capture-templates
1499 (or (org-contextualize-keys
1500 org-capture-templates org-capture-templates-contexts)
1501 '(("t" "Task" entry (file+headline "" "Tasks")
1502 "* TODO %?\n %u\n %a")))))
1503 (if keys
1504 (or (assoc keys org-capture-templates)
1505 (error "No capture template referred to by \"%s\" keys" keys))
1506 (org-mks org-capture-templates
1507 "Select a capture template\n========================="
1508 "Template key: "
1509 '(("C" "Customize org-capture-templates")
1510 ("q" "Abort"))))))
1512 (defun org-capture-fill-template (&optional template initial annotation)
1513 "Fill a template and return the filled template as a string.
1514 The template may still contain \"%?\" for cursor positioning."
1515 (setq template (or template (org-capture-get :template)))
1516 (when (stringp initial)
1517 (setq initial (org-no-properties initial)))
1518 (let* ((buffer (org-capture-get :buffer))
1519 (file (buffer-file-name (or (buffer-base-buffer buffer) buffer)))
1520 (ct (org-capture-get :default-time))
1521 (dct (decode-time ct))
1522 (ct1
1523 (if (< (nth 2 dct) org-extend-today-until)
1524 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct))
1525 ct))
1526 (plist-p (if org-store-link-plist t nil))
1527 (v-c (and (> (length kill-ring) 0) (current-kill 0)))
1528 (v-x (or (org-get-x-clipboard 'PRIMARY)
1529 (org-get-x-clipboard 'CLIPBOARD)
1530 (org-get-x-clipboard 'SECONDARY)))
1531 (v-t (format-time-string (car org-time-stamp-formats) ct))
1532 (v-T (format-time-string (cdr org-time-stamp-formats) ct))
1533 (v-u (concat "[" (substring v-t 1 -1) "]"))
1534 (v-U (concat "[" (substring v-T 1 -1) "]"))
1535 ;; `initial' and `annotation' might habe been passed.
1536 ;; But if the property list has them, we prefer those values
1537 (v-i (or (plist-get org-store-link-plist :initial)
1538 initial
1539 (org-capture-get :initial)
1540 ""))
1541 (v-a (or (plist-get org-store-link-plist :annotation)
1542 annotation
1543 (org-capture-get :annotation)
1544 ""))
1545 ;; Is the link empty? Then we do not want it...
1546 (v-a (if (equal v-a "[[]]") "" v-a))
1547 (clipboards (remove nil (list v-i
1548 (org-get-x-clipboard 'PRIMARY)
1549 (org-get-x-clipboard 'CLIPBOARD)
1550 (org-get-x-clipboard 'SECONDARY)
1551 v-c)))
1552 (l-re "\\[\\[\\(.*?\\)\\]\\(\\[.*?\\]\\)?\\]")
1553 (v-A (if (and v-a (string-match l-re v-a))
1554 (replace-match "[[\\1][%^{Link description}]]" nil nil v-a)
1555 v-a))
1556 (v-l (if (and v-a (string-match l-re v-a))
1557 (replace-match "\\1" nil nil v-a)
1558 v-a))
1559 (v-n user-full-name)
1560 (v-k (if (marker-buffer org-clock-marker)
1561 (org-no-properties org-clock-heading)))
1562 (v-K (if (marker-buffer org-clock-marker)
1563 (org-make-link-string
1564 (buffer-file-name (marker-buffer org-clock-marker))
1565 org-clock-heading)))
1566 (v-f (or (org-capture-get :original-file-nondirectory) ""))
1567 (v-F (or (org-capture-get :original-file) ""))
1569 (org-startup-folded nil)
1570 (org-inhibit-startup t)
1571 org-time-was-given org-end-time-was-given x
1572 prompt completions char time pos default histvar strings)
1574 (setq org-store-link-plist
1575 (plist-put org-store-link-plist :annotation v-a)
1576 org-store-link-plist
1577 (plist-put org-store-link-plist :initial v-i))
1578 (setq initial v-i)
1580 (unless template (setq template "") (message "No template") (ding)
1581 (sit-for 1))
1582 (save-window-excursion
1583 (delete-other-windows)
1584 (org-pop-to-buffer-same-window (get-buffer-create "*Capture*"))
1585 (erase-buffer)
1586 (insert template)
1587 (goto-char (point-min))
1588 (org-capture-steal-local-variables buffer)
1589 (setq buffer-file-name nil)
1591 ;; %[] Insert contents of a file.
1592 (goto-char (point-min))
1593 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
1594 (unless (org-capture-escaped-%)
1595 (let ((start (match-beginning 0))
1596 (end (match-end 0))
1597 (filename (expand-file-name (match-string 1))))
1598 (goto-char start)
1599 (delete-region start end)
1600 (condition-case error
1601 (insert-file-contents filename)
1602 (error (insert (format "%%![Couldn't insert %s: %s]"
1603 filename error)))))))
1604 ;; %() embedded elisp
1605 (org-capture-expand-embedded-elisp)
1607 ;; The current time
1608 (goto-char (point-min))
1609 (while (re-search-forward "%<\\([^>\n]+\\)>" nil t)
1610 (replace-match (format-time-string (match-string 1)) t t))
1612 ;; Simple %-escapes
1613 (goto-char (point-min))
1614 (while (re-search-forward "%\\([tTuUaliAcxkKInfF]\\)" nil t)
1615 (unless (org-capture-escaped-%)
1616 (when (and initial (equal (match-string 0) "%i"))
1617 (save-match-data
1618 (let* ((lead (buffer-substring
1619 (point-at-bol) (match-beginning 0))))
1620 (setq v-i (mapconcat 'identity
1621 (org-split-string initial "\n")
1622 (concat "\n" lead))))))
1623 (replace-match (or (eval (intern (concat "v-" (match-string 1)))) "")
1624 t t)))
1626 ;; From the property list
1627 (when plist-p
1628 (goto-char (point-min))
1629 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
1630 (unless (org-capture-escaped-%)
1631 (and (setq x (or (plist-get org-store-link-plist
1632 (intern (match-string 1))) ""))
1633 (replace-match x t t)))))
1635 ;; Turn on org-mode in temp buffer, set local variables
1636 ;; This is to support completion in interactive prompts
1637 (let ((org-inhibit-startup t)) (org-mode))
1638 ;; Interactive template entries
1639 (goto-char (point-min))
1640 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGtTuUCLp]\\)?" nil t)
1641 (unless (org-capture-escaped-%)
1642 (setq char (if (match-end 3) (match-string-no-properties 3))
1643 prompt (if (match-end 2) (match-string-no-properties 2)))
1644 (goto-char (match-beginning 0))
1645 (replace-match "")
1646 (setq completions nil default nil)
1647 (when prompt
1648 (setq completions (org-split-string prompt "|")
1649 prompt (pop completions)
1650 default (car completions)
1651 histvar (intern (concat
1652 "org-capture-template-prompt-history::"
1653 (or prompt "")))
1654 completions (mapcar 'list completions)))
1655 (unless (boundp histvar) (set histvar nil))
1656 (cond
1657 ((member char '("G" "g"))
1658 (let* ((org-last-tags-completion-table
1659 (org-global-tags-completion-table
1660 (if (equal char "G")
1661 (org-agenda-files)
1662 (and file (list file)))))
1663 (org-add-colon-after-tag-completion t)
1664 (ins (org-icompleting-read
1665 (if prompt (concat prompt ": ") "Tags: ")
1666 'org-tags-completion-function nil nil nil
1667 'org-tags-history)))
1668 (setq ins (mapconcat 'identity
1669 (org-split-string
1670 ins (org-re "[^[:alnum:]_@#%]+"))
1671 ":"))
1672 (when (string-match "\\S-" ins)
1673 (or (equal (char-before) ?:) (insert ":"))
1674 (insert ins)
1675 (or (equal (char-after) ?:) (insert ":"))
1676 (and (org-at-heading-p) (org-set-tags nil 'align)))))
1677 ((equal char "C")
1678 (cond ((= (length clipboards) 1) (insert (car clipboards)))
1679 ((> (length clipboards) 1)
1680 (insert (read-string "Clipboard/kill value: "
1681 (car clipboards) '(clipboards . 1)
1682 (car clipboards))))))
1683 ((equal char "L")
1684 (cond ((= (length clipboards) 1)
1685 (org-insert-link 0 (car clipboards)))
1686 ((> (length clipboards) 1)
1687 (org-insert-link 0 (read-string "Clipboard/kill value: "
1688 (car clipboards)
1689 '(clipboards . 1)
1690 (car clipboards))))))
1691 ((equal char "p")
1692 (org-set-property (org-no-properties prompt) nil))
1693 (char
1694 ;; These are the date/time related ones
1695 (setq org-time-was-given (equal (upcase char) char))
1696 (setq time (org-read-date (equal (upcase char) char) t nil
1697 prompt))
1698 (if (equal (upcase char) char) (setq org-time-was-given t))
1699 (org-insert-time-stamp time org-time-was-given
1700 (member char '("u" "U"))
1701 nil nil (list org-end-time-was-given)))
1703 (let (org-completion-use-ido)
1704 (push (org-completing-read-no-i
1705 (concat (if prompt prompt "Enter string")
1706 (if default (concat " [" default "]"))
1707 ": ")
1708 completions nil nil nil histvar default)
1709 strings)
1710 (insert (car strings)))))))
1711 ;; Replace %n escapes with nth %^{...} string
1712 (setq strings (nreverse strings))
1713 (goto-char (point-min))
1714 (while (re-search-forward "%\\\\\\([1-9][0-9]*\\)" nil t)
1715 (unless (org-capture-escaped-%)
1716 (replace-match
1717 (nth (1- (string-to-number (match-string 1))) strings)
1718 nil t)))
1719 ;; Make sure there are no empty lines before the text, and that
1720 ;; it ends with a newline character
1721 (goto-char (point-min))
1722 (while (looking-at "[ \t]*\n") (replace-match ""))
1723 (if (re-search-forward "[ \t\n]*\\'" nil t) (replace-match "\n"))
1724 ;; Return the expanded template and kill the temporary buffer
1725 (untabify (point-min) (point-max))
1726 (set-buffer-modified-p nil)
1727 (prog1 (buffer-string) (kill-buffer (current-buffer))))))
1729 (defun org-capture-escaped-% ()
1730 "Check if % was escaped - if yes, unescape it now."
1731 (if (equal (char-before (match-beginning 0)) ?\\)
1732 (progn
1733 (delete-region (1- (match-beginning 0)) (match-beginning 0))
1735 nil))
1737 (defun org-capture-expand-embedded-elisp ()
1738 "Evaluate embedded elisp %(sexp) and replace with the result."
1739 (goto-char (point-min))
1740 (while (re-search-forward "%(" nil t)
1741 (unless (org-capture-escaped-%)
1742 (goto-char (match-beginning 0))
1743 (let ((template-start (point)))
1744 (forward-char 1)
1745 (let* ((sexp (read (current-buffer)))
1746 (result (org-eval
1747 (org-capture--expand-keyword-in-embedded-elisp sexp))))
1748 (delete-region template-start (point))
1749 (when result
1750 (if (stringp result)
1751 (insert result)
1752 (error "Capture template sexp `%s' must evaluate to string or nil"
1753 sexp))))))))
1755 (defun org-capture--expand-keyword-in-embedded-elisp (attr)
1756 "Recursively replace capture link keywords in ATTR sexp.
1757 Such keywords are prefixed with \"%:\". See
1758 `org-capture-template' for more information."
1759 (cond ((consp attr)
1760 (mapcar 'org-capture--expand-keyword-in-embedded-elisp attr))
1761 ((symbolp attr)
1762 (let* ((attr-symbol (symbol-name attr))
1763 (key (and (string-match "%\\(:.*\\)" attr-symbol)
1764 (intern (match-string 1 attr-symbol)))))
1765 (or (plist-get org-store-link-plist key)
1766 attr)))
1767 (t attr)))
1769 (defun org-capture-inside-embedded-elisp-p ()
1770 "Return non-nil if point is inside of embedded elisp %(sexp)."
1771 (let (beg end)
1772 (with-syntax-table emacs-lisp-mode-syntax-table
1773 (save-excursion
1774 ;; `looking-at' and `search-backward' below do not match the "%(" if
1775 ;; point is in its middle
1776 (when (equal (char-before) ?%)
1777 (backward-char))
1778 (save-match-data
1779 (when (or (looking-at "%(") (search-backward "%(" nil t))
1780 (setq beg (point))
1781 (setq end (progn (forward-char) (forward-sexp) (1- (point)))))))
1782 (when (and beg end)
1783 (and (<= (point) end) (>= (point) beg))))))
1785 ;;;###autoload
1786 (defun org-capture-import-remember-templates ()
1787 "Set `org-capture-templates' to be similar to `org-remember-templates'."
1788 (interactive)
1789 (when (and (yes-or-no-p
1790 "Import old remember templates into org-capture-templates? ")
1791 (yes-or-no-p
1792 "Note that this will remove any templates currently defined in `org-capture-templates'. Do you still want to go ahead? "))
1793 (require 'org-remember)
1794 (setq org-capture-templates
1795 (mapcar
1796 (lambda (entry)
1797 (let ((desc (car entry))
1798 (key (char-to-string (nth 1 entry)))
1799 (template (nth 2 entry))
1800 (file (or (nth 3 entry) org-default-notes-file))
1801 (position (or (nth 4 entry) org-remember-default-headline))
1802 (type 'entry)
1803 (prepend org-reverse-note-order)
1804 immediate target jump-to-captured)
1805 (cond
1806 ((member position '(top bottom))
1807 (setq target (list 'file file)
1808 prepend (eq position 'top)))
1809 ((eq position 'date-tree)
1810 (setq target (list 'file+datetree file)
1811 prepend nil))
1812 (t (setq target (list 'file+headline file position))))
1814 (when (string-match "%!" template)
1815 (setq template (replace-match "" t t template)
1816 immediate t))
1818 (when (string-match "%&" template)
1819 (setq jump-to-captured t))
1821 (append (list key desc type target template)
1822 (if prepend '(:prepend t))
1823 (if immediate '(:immediate-finish t))
1824 (if jump-to-captured '(:jump-to-captured t)))))
1826 org-remember-templates))))
1828 (provide 'org-capture)
1830 ;;; org-capture.el ends here