6

I had set up a custom hook for a mode, but I now realize that I want to use the mode without my changes and without my hook. So, I want the mode to behave as if I never set the hook in the first place, and I want to do this without restarting emacs. Is this reasonably doable?

For example, if I was using the following hook:

(add-hook 'my-mode-hook
          (lambda ()
           ;; Do a bunch of stuff...ie:
           (local-set-key (kbd "C-c l")
                          'some-fancy-function)
           )
)

I can achieve my goal by deleting the hook for my-mode from my init.el, restarting emacs, and then using my-mode as a default setup. But can I do this without restarting emacs?

  • It looks like my best bet is to use functions instead of lambda's, and then using the remove-hook command to remove the function from the hook, as outlined in the selected answer here: stackoverflow.com/questions/22671045/… – modulitos Dec 16 '15 at 9:25
  • I am planning to post an answer when I have this figured out... – modulitos Dec 16 '15 at 9:25
9

Using function symbols certainly makes this easier (and this is one of the reasons why I would recommend always using that approach). You can still use remove-hook with the lambda form, though -- it just needs to be the same lambda form as the one you added!

(remove-hook 'my-mode-hook
             (lambda () (local-set-key (kbd "C-c l") 'some-fancy-function)))

If you've edited the original code in the interim, you might find it simpler to inspect the my-mode-hook variable to figure out which value to remove.

2

I've solved it in my config by consistently naming all my hooks. I use eval-defun on a hook function to re-define it, followed possibly by revert-buffer in relevant buffers. This approach also helps with autoloading mode-specific configuration:

hooks.el:
(add-hook 'c++-mode-hook 'ora-c++-hook)

modes/ora-c++.el:
;;;###autoload
(defun ora-c++-hook ()
  (auto-complete-mode 1)
  (c-toggle-auto-newline)
  ;; (hs-minor-mode)
  )

Thanks to the consistent naming, it's possible to define a function that jumps to the hook that corresponds to the current mode - very useful.

1

My solution to this problem is to use defined functions instead of lambdas for my custom config code, and using remove-hook to undo the custom config.

For example, from my hook above, I would make the following changes:

(defun my-mode-config ()
  (local-set-key (kbd "C-c l") 'some-fancy-function))

(add-hook 'my-mode-hook 'my-mode-config)

which provides the same functionality as the above code. But with this new code, I can reset my mode as follows:

(remove-hook 'my-mode-hook 'my-mode-config)

That's it!

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.