Search code examples
emacsorg-mode

hook or advice when aborting org-capture before template selection?


I'd like to be able to run some code when aborting an org-capture before selecting a capture template. I am able to run some code when finishing the capture process (whether completed or aborted) using defadvice. For example:

(defadvice org-capture-finalize
  (after delete-capture-frame activate)
  "Advise capture-finalize to close the frame"
  (if (equal "capture" (frame-parameter nil 'name))
      (delete-frame)))

(defadvice org-capture-kill
  (after delete-capture-frame activate)
  "Advise capture-kill to close the frame"
  (if (equal "capture" (frame-parameter nil 'name))
      (delete-frame)))

What I cannot figure out is how to run some code when I abort the capture before I select a template. This is when the Org Select buffer is prompting me to "Select a capture template". I can hit 'q' or 'C-g' to abort the capture but I cannot figure out how to hook into this. For context, what I am trying to accomplish is to be able to delete the org-capture frame when aborting. I have org-capture set to open in a new frame and I am able to delete the frame after the capture is complete or aborted after template selection.

Is it possible to use a hook or some advice to run some code when aborting the capture before template selection?


Solution

  • This appears to work:

    (defadvice org-capture-select-template (around delete-capture-frame activate)
      "Advise org-capture-select-template to close the frame on abort"
      (unless (ignore-errors ad-do-it t)
        (setq ad-return-value "q"))
      (if (and
           (equal "q" ad-return-value)
           (equal "capture" (frame-parameter nil 'name)))
          (delete-frame)))
    

    This checks the return value of org-capture-select-template, which is what org-capture calls to set entry and later call error "Abort" if it returns q, as you've seen. This advice deletes the capture frame if it does indeed return q.

    Note that it does not handle C-g in template selection. Nevermind, fixed that. I set the return value to q on error (ie, on C-g), on the assumption that the resulting behaviour in org-capture is the same. As far as I can tell by reading the source, it is (the only difference is that error gets called in org-capture instead of org-capture-select-template).

    Oh, and org-capture-kill calls org-capture-finalize, so you don't need to advise the former.