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