Friday, November 21, 2008

Using a Mapleader

As you have probably realized, keyboard real estate in Vim is pretty heavily occupied in normal mode. Specifically, just about every key is already bound to a command. Luckily, Vim provides a facility to define additional mappings on these keys. It's called a mapleader, and it's easy to setup.

First you need to define what key you want your mapleader to be. I prefer comma because it's (in my daily usage) unused, and it's easy to reach. Add the following to your vimrc.

let mapleader = ","

Now that mapleader is defined, you can use it for custom mappings at will.

:map <leader>n :new<cr>

Press `,' then `n' in normal mode, and it splits to a new window.

:map <leader>i I

Press `,' then `i' in normal mode, and it puts you into insert mode on the first character of the current line.

These usage examples are slightly obtuse, so I'll be showing how to incorporate using a mapleader into tab management in an upcoming post.


Anonymous said...

what's the advantage as opposed to just directly incorporating the comma into the definition of the map?

Travis Whitton said...

Change once, change everywhere I suppose since it's a variable. Particularly if you're writing a plugin or something along those lines, you wouldn't want to go through all your mappings across the board. Although Vim's awesome substitution capabilities would make that easier.

graywh said...

Otherwise unused?! Only a vim newbie could say something like that.

Travis Whitton said...

While you're correct in pointing out my mistake, there's no need to be rude.