Vim Tip #6: Map Leader and Normal mode mappings

2018-11-17(Sat)

tags: Vim

Vim Tips

"mapleader" is the command you use to set the key that starts off all (or at least most) of your normal mode mappings. Put this in your ~/.config/init.vim (that's NeoVim, if you're still using Vim use the ~/.vimrc):

let g:mapleader = '/'

Other possible map leaders include things like the dash (great for Dvorak users like myself, not so hot for Scholes typists), the semi-colon, the comma ... things which aren't already a command in Vim. Which rules out pretty much all the letters.

Now you can add a mapping using your leader:

nnoremap <leader>- :split<cr>

That means: "when I type /- in normal mode, it should be the same as me typing :split followed by a carriage return." (You could use just 'nmap', which means "normal mapping," but don't - trust me on this one, or go read http://learnvimscriptthehardway.stevelosh.com/chapters/05.html - really, you should).

I tried to use <leader>| for a vertical split, but that does weird things and I don't know why (probably because it's a special character). So let's do this:

nnoremap <leader>v :vsplit<cr>

If you want the splits to be more consistent, you could use <leader>h (horizontal, vertical) for the first one.