Vim is a keyboard driven text editor which means there are a lot of keyboard shortcuts and commands. The <leader> key is a vim tool that can be used to create personalized shortcuts. Let’s discuss a few different ways to create our own shortcuts.
Custom <leader> key
The <leader> key defaults to the “/” key but it is very simple to change. A custom <leader> key can be set by adding the following line to your vimrc file.
:let mapleader = ","
The leader key can be whatever key you choose. I map mine to the comma key. Used keys will be replaced if you set them to the <leader> key so only use empty keys (such as “-“, “,”, or “;” instead of “u”, “h” or “j”).
Mapping vim commands
Vim search has one small feature that is useful but cumbersome. All search terms found are highlighted until your next search. You can type
This can be a little verbose, however. With the power of the <leader> key, it takes only two keystrokes instead of four (including the colon). Add this to your vimrc
:map <leader>h :noh<CR>
Now highlights can be hidden by typing “,h” in normal mode. If you have “set hlsearch” in your vimrc your next search will be highlighted.
Mapping Custom Functions
The <leader> key can also be used with custom methods. Create a function in your vimrc to toggle both relative and normal line numbers but not relative when using versions before vim 7.4.
function! ToggleLineNumber() if v:version > 703 set norelativenumber! endif set nonumber! endfunction
You can type “:ToggleLineNumber()” to toggle the line numbers or you can add this to your vimrc
nnoremap <leader>r :call ToggleLineNumber()<CR>
Type “,r” and the line numbers toggle for every version of vim without errors for unknown functions.
Mapping Plugin Functions
The <leader> key can also be used for plugin functions. For example, NERDTree is an alternative file browser for vim. The NERDTree docs suggest you add
map <C-n> :NERDTreeToggle<CR>
to your vimrc to toggle the NERDTree buffer. To use a <leader> shortcut add this to your vimrc.
nnoremap <leader>t :NERDTreeToggle<CR>
Now, “,t” toggles the NERDTree buffer and you can browse the file structure and open files as normal.
" Automatically close NERDTree when you open a file let NERDTreeQuitOnOpen=1
Bonus tip: Use multiple leader keys
If you run out of key combinations or you want to separate different function types you can have multiple <leader> keys.
let mapleader="," nnoremap <leader>n :set number<CR> let mapleader="-" nnoremap <leader>n :set nonumber<CR>
Now “,n” will display line numbers and “-n” will hide line numbers.
There are many more uses of the <leader> key. What kind of shortcuts can you come up with?