vimtricks.wiki Concise Vim tricks, one at a time.

How do I use the leader key to create my own keyboard shortcuts?

Answer

let mapleader = ' ' then nnoremap <leader>key command

Explanation

The leader key is a configurable prefix for your custom key mappings. By convention, it's set to Space or comma, giving you a whole namespace of shortcuts that don't conflict with Vim's built-in commands.

Setup

" Set leader to Space (most popular choice)
let mapleader = ' '

" Or set it to comma
let mapleader = ','

Essential leader mappings

" File operations
nnoremap <leader>w :w<CR>          " Save file
nnoremap <leader>q :q<CR>          " Quit
nnoremap <leader>x :x<CR>          " Save and quit

" Search
nnoremap <leader>h :nohlsearch<CR> " Clear search highlight

" Buffer navigation
nnoremap <leader>b :ls<CR>:b<Space> " List and switch buffers
nnoremap <leader>n :bnext<CR>       " Next buffer
nnoremap <leader>p :bprev<CR>       " Previous buffer

" Window management
nnoremap <leader>v :vsplit<CR>      " Vertical split
nnoremap <leader>s :split<CR>       " Horizontal split

" Editing helpers
nnoremap <leader>y "+y             " Yank to system clipboard
nnoremap <leader>p "+p             " Paste from system clipboard
nnoremap <leader>d "_d             " Delete to black hole register

Local leader

let maplocalleader = '\\'

" Local leader is for filetype-specific mappings
autocmd FileType python nnoremap <localleader>r :!python3 %<CR>
autocmd FileType go nnoremap <localleader>r :!go run %<CR>

Tips

  • Space as leader is popular because it's the largest key and has no normal-mode function
  • Set mapleader before any <leader> mappings in your vimrc
  • :map <leader> shows all leader mappings
  • Use :verbose nmap <leader>w to check if a mapping conflicts
  • <leader> has a 1-second timeout by default (:set timeoutlen=500 to shorten)
  • Keep your leader mappings organized — group them by purpose
  • Documented under :help mapleader

Next

How do I run the same command across all windows, buffers, or tabs?