0

I want to run some function f after adding a hook to a mode and after running f remove the hook that I added, returning the result of f if there is one.

Here is a non-working version that I hope makes the intent clear:

(defun run-function-with-hook (mode-hook hook-fn fn)
  (add-hook mode-hook hook-fn)
  (message (concat "mode hooks before running: " (prin1-to-string (symbol-value mode-to-slowdown))))
  (funcall fn)
  (remove-hook mode-hook hook-fn))

  (run-function-with-hook 'org-mode-hook (message "opening org file") (message "opened org file"))

Is this a better fit for a macro? If so, perhaps the right answer to this is an answer using a macro instead.

  • That's the usual way to do it, AFAIK: add-hook followed by remove-hook. – Drew Sep 9 '19 at 13:51
0

It looks like I had things mostly correct besides a variable I forgot to rename. The issue was that I needed to wrap the functions in lambda calls:

(defun run-function-with-hook (mode-hook hook-fn fn)
  (add-hook mode-hook hook-fn)
  (message (concat "mode hooks before running: " (prin1-to-string (symbol-value mode-hook))))
  (funcall fn)
  (remove-hook mode-hook hook-fn))

(run-function-with-hook 'org-mode-hook (lambda () (message "opening org file")) (lambda () (message "opened org file")))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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