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