8

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?

modulitos
  • 2,432
  • 1
  • 18
  • 36
  • 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: http://stackoverflow.com/questions/22671045/function-that-remove-specific-lambda-from-a-hook-in-emacs – modulitos Dec 16 '15 at 09:25
  • I am planning to post an answer when I have this figured out... – modulitos Dec 16 '15 at 09:25

3 Answers3

12

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.

phils
  • 48,657
  • 3
  • 76
  • 115
3

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.

abo-abo
  • 13,943
  • 1
  • 29
  • 43
2

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!

phils
  • 48,657
  • 3
  • 76
  • 115
modulitos
  • 2,432
  • 1
  • 18
  • 36