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