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