Though I know how to set a global key-binding in Emacs, I find it hard to even Google out the code for a local (minor-mode specific) key-binding. For instance, I have this code in my .emacs
:
;; PDFLaTeX from AucTeX
(global-set-key (kbd "C-c M-p")
(lambda ()
(interactive)
(shell-command (concat "pdflatex " buffer-file-name))))
I don't want to set it globally. Is there a function like local-set-key
?
To bind a key in a mode, you need to wait for the mode to be loaded before defining the key. One could require the mode, or use
eval-after-load
Don't forget either
'
—eval-after-load
is not a macro, so it needs them.I use the following:
to have a bind defined for LaTeX mode alone.
None of the other answers satisfied my needs. So this may help other people. I wanted
Tab
to jump to the beginning of the line if I'm in Evil's normal mode (basically: this means everywhere in Emacs), but I instead wanted it to cycle between org item states if I am in an org-mode document.One option was to mess around with separate bindings and constant binding-rebinding whenever I switched buffers (because evil allows only one binding per key in its normal state).
But a more efficient option was to make
Tab
run my own code which runs the required function based on which major mode the current buffer uses. So if I am in a org buffer, this code runsorg-cycle
, and otherwise it runsevil-first-non-blank
(go to the first non-whitespace character on the line).The technique I used here can also be used by calling your custom function via
global-set-key
instead, for people who use regular non-evil Emacs.For those who don't know Emacs lisp, the first line after the "if" statement is the true-action, and the line after that is the false-action. So if
major-mode
equalsorg-mode
, we runorg-cycle
, otherwise we runevil-first-non-blank
in all other modes:You need to identify the key map for that mode (for example,
LaTeX-mode-map
) and use the functiondefine-key
. As an example, along with activatingoutline-minor-mode
within LaTeX mode, I have:In this case the major mode (LaTeX) holds the key binding, but there is also an
outline-minor-mode-map
.