What are good custom keybindings in emacs?

Pedro Rolo picture Pedro Rolo · Apr 15, 2011 · Viewed 9.1k times · Source

Emacs seems to have all the possible keyboard combinations already randomly distributed among it's commands. :p

If I am to define new keyboard shortcuts, where should I put them? Which prefixes should I use?

For instance: I want to define shortcuts for the following functions:

  • indent-buffer (C-c i, after I got the answer)
  • comment-or-uncomment-region (C-c C)
  • rdebug (ruby debugger) (C-c R)
  • rsense-complete (ruby autocomplete) (C-c e)

Where would you put these? Why?

Answer

Trey Jackson picture Trey Jackson · Apr 16, 2011

Emacs actually has a very definite pattern to its bindings, this answer shows some.

As far as where you should define keys, if you take a look at the documentation for conventions, you'll see that C-c a (where a is any lower or upper case character) is reserved for users.

Plus, if you're defining a key that really only makes sense in a particular mode, then you should define it in that keymap.

For example, M-/ is bound to dabbrev-expand, which is a handy way of autocompleting the word you're typing. It might very well make sense to use rsense-complete instead, but only when you're in ruby. In which case, you can do this:

(add-hook 'ruby-mode-hook
     (lambda () (define-key ruby-mode-map (kbd "M-/") 'rsense-complete)))

That will override the binding for M-/ only when you're in ruby-mode, and leave it unchanged (or available) for the rest of the modes.