Set an individual key binding for a specific Emacs mode

Although I know how to set up global key bindings in Emacs, it’s hard for me even for Google to infer code for local (tied to secondary) key bindings. For example, I have this code in my .emacs :

 ;; PDFLaTeX from AucTeX (global-set-key (kbd "Cc Mp") (lambda () (interactive) (shell-command (concat "pdflatex " buffer-file-name)))) 

I do not want to install it globally. Is there a function like local-set-key ?

+45
emacs key-bindings
Mar 31 '11 at 12:45
source share
4 answers

To associate a key in mode, you need to wait for the mode to load before defining the key. You can require a mode or use eval-after-load

  (eval-after-load 'latex '(define-key LaTeX-mode-map [(tab)] 'outline-cycle))) 

Remember that ' - eval-after-load not a macro, so it needs them.

+43
Mar 31 '11 at 20:24
source share

I am using the following:

 (add-hook 'LaTeX-mode-hook (lambda () (local-set-key (kbd "C-0") #'run-latexmk))) 

have a binding defined only for LaTeX mode.

+34
Jan 09 '13 at 8:03
source share

You need to identify the key map for this mode (for example, LaTeX-mode-map ) and use the define-key function. As an example, along with activating outline-minor-mode in LaTeX mode, I have:

  (define-key LaTeX-mode-map [(tab)] 'outline-cycle)) 

In this case, the main mode (LaTeX) contains a key binding, but there is also outline-minor-mode-map .

+5
Mar 31 '11 at 12:58
source share

None of the answers met my needs. So it can help other people. I wanted Tab jump to the beginning of the line if I'm in the normal Evil mode (basically: this means everywhere in Emacs), but instead I wanted it to switch between the org item states if I had an org-mode document.

One option was to combine with individual bindings and a constant binding binding when I switched buffers (because evil allows only one binding on a 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 the main mode that uses the current buffer. Therefore, if I am in the org buffer, this code runs org-cycle , and otherwise it runs evil-first-non-blank (go to the first evil-first-non-blank character in the string).

The technique used here can also be used by calling your user-defined 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 a true action, and the line after that is a false action. Therefore, if major-mode is equal to org-mode , we run org-cycle , otherwise we run evil-first-non-blank in all other modes:

  (defun my/tab-jump-or-org-cycle () "jumps to beginning of line in all modes except org mode, where it cycles" (interactive) (if (equal major-mode 'org-mode) (org-cycle) (evil-first-non-blank)) ) (define-key evil-normal-state-map (kbd "<tab>") 'my/tab-jump-or-org-cycle) 
+1
Dec 10 '16 at 20:31
source share



All Articles