Setting major-mode specific keybindings in emacs

9

2

In my .emacs file, I want to add a key binding for a specific major mode (setting coffee-compile-file to C-c C-c in coffee-mode).

I've found a lot of instructions on using local-set-key and global-set-key, so I can easily add this binding once I've opened a file in coffee-mode, but it would be nice for this to be handled by .emacs.

Jeff

Posted 2011-03-27T03:35:47.373

Reputation: 93

Answers

8

Use the mode hook. C-h m shows information about the major mode, usually including what hook(s) it supports; then you do something like

(add-hook 'coffee-mode-hook ;; guessing
    '(lambda ()
       (local-set-key "\C-cc" 'coffee-compile-file)))

geekosaur

Posted 2011-03-27T03:35:47.373

Reputation: 10 195

6

You can define the key in the mode specific map, something like:

(add-hook 'coffee-mode-hook
    (lambda ()
        (define-key coffee-mode-map (kbd "C-c c") 'coffee-compile-file)))

Or, more cleanly:

(eval-after-load "coffee-mode"
    '(define-key coffee-mode-map (kbd "C-c c") 'coffee-compile-file))

The second statement causes the key definition to only happen once, whereas the first causes the definition to happen every time coffee-mode is enabled (which is overkill).

Trey Jackson

Posted 2011-03-27T03:35:47.373

Reputation: 3 731

2FYI: these parens are in the wrong place. This add-hook should read:

(add-hook 'coffee-mode-hook (lambda () (define-key coffee-mode-map (kbd "C-c c") 'coffee-compile-file))) – owenmarshall – 2012-07-16T15:30:34.243

Also, why defining it in a hook ? – Nikana Reklawyks – 2012-11-16T03:04:46.500

@NikanaReklawyks You're right, defining it in a hook is not as clean as using an eval-after-load statement in this case. I'll update the answer appropriately. – Trey Jackson – 2012-11-19T15:04:44.993

3

Emacs 24.4 superseded eval-after-load with with-eval-after-load:

** New macro `with-eval-after-load'.
This is like the old `eval-after-load', but better behaved.

So the answer should be

(with-eval-after-load 'coffee-mode
  (define-key coffee-mode-map (kbd "C-c C-c") 'coffee-compile-file)
  (define-key erlang-mode-map (kbd "C-c C-m") 'coffee-make-coffee)
  ;; Add other coffee commands
)

Blaz

Posted 2011-03-27T03:35:47.373

Reputation: 683