Vim-like Leader Keys In Emacs

➲  Date: Wed, 04 May 2011 13:18:02 +0200; Tags: [hack_of_the_day; emacs].

The Problem

We want an equivalent of Vim's Leader keys (c.f. this stackoverflow question) for our own key-bindings. In other words, we want to prefix all the defined shortcuts with a given key-binding in order not to mess too much with Emacs or with modes implemented by other people. We also want to make it easy to define new keys, for functions or for any piece of code, and we want to be able to easily change the Leader key.

The Current Solution

In your .emacs file, before all the nasty hacks that you want to prefix, the idea is first to define a new “keymap” for your bindings. It is called dkeys for no particular reason here:
(setq dkeys-map (make-sparse-keymap))
Then we choose one arbitrary leading key, here Ctrl-D(I use the ErgoEmacs' and CUA modes, so Ctrl-D is unused in my setup.), but any combination of keystrokes may be used. The global-unset-key should be applied only to the first of the string:
(setq dkeys-leading-key "\C-d")
(global-unset-key "\C-d")
To be “clean”, we define a minor mode, and activate it(the minor mode is actually not mandatory but this way you can define many different ones, and activate them on-demand.):
(define-minor-mode dkeys-mode
  "C-d-Keys mode"
  :lighter " Dkey"
  :global t
  :keymap dkeys-map)
(dkeys-mode 1)
To simplify key-bindings we create a function to bind a key-sequence to a function:
(defun set-dkey(key function)
  (define-key dkeys-map 
              (concat dkeys-leading-key key)
              function))
The function just adds the Leader, and defines the key-binding in the minor mode.
As we are lazy, we define a macro(When hacking macros you might want to use the macroexpand function to solve some headaches.) which defines interactive functions, and binds them to the keys at once:
(defmacro dkeys-funkey (key name function)
  (list
   'progn
   (list 'defun name '()
     '(interactive) function)
   (list 'define-key 'dkeys-map 
     (list 'concat 'dkeys-leading-key key) 
     (list 'quote name))))
Finally, each definition can be simply added to that minor mode. For example, this key-bound-function, inserts some text when "C-d o o" is typed:
(dkeys-funkey "oo" express-astonishment
            (progn
              (insert "oooooohhhh!!!")))
That's it. Happy Emacs Hacking!

blog comments powered by Disqus

Sebastien Mondet


Menu:




Site generated thanks to bracetax, camlmix, sebib, and more …
Updated on Sat, 10 Dec 2011 12:46:34 -0500.
Sebastien Mondet

Powered by Caml