6

I have several capture templates. With one of them, I want an Elisp function to transform the contents before saving it. I know of org-capture-prepare-finalize-hook, but this will run for every template. Is there a way to ensure a hook runs only for a given capture template?

In case people are interested, the transformation I want to do is this:

The capture template will have a long list of checkbox items (all unchecked). I want to check one or two of these every time I use that template. Then I want to store only the items that were checked - so my function would delete all unchecked items (declutter).

4 Answers 4

6

See my answer here: https://emacs.stackexchange.com/a/48566/18296

Here’s the example code from it:

(defun tina/test-finalize ()
  (let ((key  (plist-get org-capture-plist :key))
        (desc (plist-get org-capture-plist :description)))
    (if org-note-abort
        (message "Template with key %s and description “%s” aborted" key desc)
      (message "Template with key %s and description “%s” run successfully" key desc))))

(add-hook 'org-capture-after-finalize-hook 'tina/test-finalize)

So, wrapping your function in a test like (when (and (not org-note-abort) (equal (plist-get org-capture-plist :key) "g")) … ) should do the trick!

3

The solution by Tina Russell is probably the way to go (did not try it). I solved it using the code below.

  (defun clean-up-template ()
    "Remove all unchecked items in the checklist"
    (if (org-entry-get (point-min) "EntryKey")
    (let* ((lines (split-string
               (buffer-substring-no-properties (point-min) (point-max))
               "\n" nil nil))
           (cleaned-lines (seq-remove (lambda (x) (string-match-p "- \\[ \\]" x)) lines))
           (final-string (mapconcat 'identity cleaned-lines "\n")))
      (save-excursion
        (save-restriction
          (delete-region (point-min) (point-max))
          (insert final-string))))))

  (add-hook 'org-capture-prepare-finalize-hook 'clean-up-nvc-template)
1

org-capture-prepare-finalize-hook worked for me, not org-capture-after-finalize-hook.

0

Not sure when this was added but if anyone's looking at this in 2023 capture templates can themselves specify individual hooks to run

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.