How do I create key mappings that only apply to the current buffer?
Answer
:nnoremap <buffer> <leader>r :!python %<CR>
Explanation
How it works
By adding <buffer> to a mapping command, the mapping only applies to the current buffer. This means different buffers can have different mappings for the same key, which is perfect for filetype-specific shortcuts.
Buffer-local mappings take priority over global mappings. When you close the buffer, the mapping is automatically removed. This prevents one file type's shortcuts from interfering with another.
The syntax works with all mapping commands:
:nnoremap <buffer> ...for normal mode:inoremap <buffer> ...for insert mode:vnoremap <buffer> ...for visual mode
To see all buffer-local mappings, use :map <buffer>. To remove one, use :nunmap <buffer> <leader>r.
Example
The most common use is in filetype autocommands in your vimrc:
autocmd FileType python nnoremap <buffer> <leader>r :!python %<CR>
autocmd FileType javascript nnoremap <buffer> <leader>r :!node %<CR>
autocmd FileType go nnoremap <buffer> <leader>r :!go run %<CR>
Now pressing <leader>r runs the current file with the appropriate interpreter, depending on what type of file is open. A Python file runs with python, a JavaScript file with node, and a Go file with go run.
For more organized configuration, you can place these in filetype plugin files at ~/.vim/ftplugin/python.vim:
nnoremap <buffer> <leader>r :!python %<CR>
nnoremap <buffer> <leader>t :!pytest %<CR>
Vim loads these files automatically when a buffer of that filetype is opened, making buffer-local mappings the cleanest way to set up per-language shortcuts.