Mode-specific emacs keybindings

emacs

I'm trying to get emacs (23.3 on Arch Linux) to map Ctrl+F12 to the built-in "compile" function when in C-mode (actually CC-mode, which comes built-in as well). So far I've tried the following:

(defun my-c-mode-common-hook (define-key c-mode-map (kbd "C-<f12>") 'compile))
(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

and:

(eval-after-load 'c-mode
  '(define-key c-mode-map (kbd "C-<f12>") 'compile))

But neither works; I get <C-f12> is undefined. Based on what I've read here, here, and here, I can't see why it isn't working. Any thoughts?

Best Answer

C mode (and specifically the c-mode-map variable) is provided by a package called cc-mode, not c-mode.

(eval-after-load 'cc-mode
  '(define-key c-mode-map (kbd "C-<f12>") 'compile))

For your other method, as vschum has already answered, you're missing the argument list in your defun. Furthermore, c-mode-common-hook isn't the right place for this: it's executed each time you enter C mode. The right time to add your binding is when C mode loads; you can do that either through the general eval-after-load mechanism as above, or through c-initialization-hook:

(defun my-c-mode-common-hook ()
  (define-key c-mode-map (kbd "C-<f12>") 'compile))
(add-hook 'c-initialization-hook 'my-c-mode-common-hook)
Related Question