M-x all-things-emacs

Quick Tip: Defining Mode Specific Key Bindings

February 10th, 2007 by Rob Christie · 3 Comments

Many times I use global key mappings for commands that I use every day. For example, I build java projects daily using ant, so I have the following in my .emacs:

(global-set-key [f5] 'jde-build)

Less frequently, I use the C-c C-v C-. which is the default key binding for the command jde-complete. Both commands are in the Java Development Environment For Emacs. The jde-complete command displays completions for the symbol at point. Sometimes it is nice to have some of your key bindings be mode specific.

Last year I started toying with Ruby on Rails. I have been using the excellent emacs-rails package and I just started using the Ri for (X)emacs package. The ri for emacs package provides you the ability to look up ruby info for methods and classes within emacs. It also provides for symbol completion for the symbol at point. My brain is already mapped to use C-c C-v C-. in java, so I wanted to map this functionality to the same keystroke.

(add-hook 'ruby-mode-hook
          '(lambda ()
             (define-key ruby-mode-map [?\C-c ?\C-v ?\C-.]
               'ri-ruby-complete-symbol)))

If you are interested in learning more, Emacs Keymaps and the SLIME scratch buffer gives some nice background on the precedence of key maps in emacs. I found this article when I started writing the post. The Emacs Lisp Reference Manual is also a great resource.

Tags: elisp · java · quick · ruby · tips

3 responses so far ↓

  • 1 Todd Larason // Feb 10, 2007 at 8:49 am

    I find the (kbd “C-c C-v C-.”) syntax a lot easier to get right than the [?\C-c ?\C-v ?\C-.] syntax, especially when functino keys and moust buttons get involved.

  • 2 Ryan McGeary // Feb 11, 2007 at 3:04 pm

    Funny, I’ve always preferred this syntax:

    [(control c)(control v)(control .)]

    I like it because it’s the most readable and explicit, but I wasn’t aware of the kbd function until now.

  • 3 Nikolaj Schumacher // Mar 13, 2007 at 10:07 am

    I’m a sucker for efficiency …
    I’d use the following:

    (eval-after-load 'ruby-mode '(define-key ruby-mode-map ... ))