After a few years customizing my .emacs
file, I find I used two different
kinds of constructs to setup major-mode-specific key bindings:
1. using a hook and local-set-key
. For example:
(defun my/bindkey-recompile ()
"Bind <F5> to `recompile'."
(local-set-key (kbd "<f5>") 'recompile))
(add-hook 'c-mode-common-hook 'my/bindkey-recompile)
I would say this construct makes it easy to use the same key bindings for different major-modes by adding the same function to all relevant major-mode hooks (in other words, the "which keybindings do I want" is clearly separated from the "for which modes do I want them"). However, I'm not comfortable with the fact that such customizations are done at the buffer level, whereas I would think they belong to the major mode.
2. using define-key
(often combined with eval-after-load
to delay
evaluation until the relevant keymap is loaded). For example:
(eval-after-load "cc-mode"
'(progn
(define-key c-mode-map (kbd "C-c o") 'ff-find-other-file)
(define-key c++-mode-map (kbd "C-c o") 'ff-find-other-file)))
By contrast, this construct customizes the major-mode itself, but is less
flexible: if I want to use the same key bindings for another mode, I will have
to find the correct file and keymap names for this mode, and almost duplicate
the eval-after-load
expression (although this could probably be automated with
a function/macro).
Question: although both construct types work well and produce the result I want, they are technically very different, setting-up the key bindings in different keymaps at different times. So my question is: among these two constructs, is there a "preferred/better" way to do things? (Or maybe the "best" construct is a third one which I'm not aware of?)
By "preferred/better", I mean such things as:
- less prone to break with new emacs versions
- less prone to disturb/be disturbed by active minor-modes
- more idiomatic / readable / shareable with others