Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 7 down vote accepted

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)))
share|improve this answer

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).

share|improve this answer
2  
FYI: 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 Jul 16 '12 at 15:30
    
Also, why defining it in a hook ? –  Nikana Reklawyks Nov 16 '12 at 3:04
    
@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 Nov 19 '12 at 15:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.