Lesson 21 of 26
Mapping Leaders in Vim
In this lesson
Roy explains that the leader is a placeholder key, backslash by default, that many plugins use so that their mappings don't clash with existing key bindings, and that it can be changed with let mapleader. He maps the leader pressed twice to NERDTreeToggle and shows that, before the leader is set in the vimrc, the mapping works with two backslashes. He then sets the leader to comma in the vimrc, so two commas open NERDTree.
Transcript
[00:08] (external link, opens in new tab) Let's talk about leaders. Leaders in Vim are basically placeholders for any key that you'd like. And the default for a leader is the backslash. Now, you can change it. And many plugins use leader mappings so that they don't clash with existing key bindings that they currently have. If you want to change the leader, you just say let map leader be comma, which is what I usually use. So in Vim, what I would do, I can say let map leader equal
[00:38] (external link, opens in new tab) Comma. And now what do I do? Well, I can set for example visibility of NERDTree just like I did previously. With let's say two map leaders. So I can say no let's say normal no re that's not recursive map
[01:09] (external link, opens in new tab) Leader leader to NERDTreeToggle and of course cr for enter at the Now let's see if that works. Now let me type two commas. Let's do that again.
[01:42] (external link, opens in new tab) Okay. So you can see that by using a map leader I can actually do a very very u powerful and generic thing and I can later change it. So if I don't feel comfortable with comma anymore I can change my leader to any other key that I'm comfortable with. So, I'll go to my vimrc and I'm going to say let's edit that. Let's edit the vimrc file and say here
[02:14] (external link, opens in new tab) Under normal not recursive map leader will be mapped to NERDTreeToggle with cr. So now I'll have two ways to open NERDTree and two leaders. Now, I haven't mapped the leader yet in in the vimrc. So, I just want to show you the default leader in this case. So, I'm going to write
[02:47] (external link, opens in new tab) I'm going to say source the vimrc. So, now if I press two leaders, I think because I mapped it in memory, this will still work. Let me close it down and do vim again. Now if I type two commas, nothing happens. But if I type two backslashes, I get NERDTreeToggle working. So let me go back and edit the vimrc.
[03:22] (external link, opens in new tab) And this time I'm going to say shift g to go all the way to the end. And right before all these mappings, I'm going to say shift O and say let map leader equal comma because that's the way I like to work. Escape O just to have an empty line between there and right quit. If I now open vimrc again, two commas and I have exactly what I need.
[03:53] (external link, opens in new tab) So that's how you use map leaders.