How do I define a mapping that only takes effect if the key is not already mapped?
Answer
:map <unique> {key} {rhs}
Explanation
The <unique> modifier causes Vim to fail with an error if you try to create a mapping for a key that is already mapped in that mode. Instead of silently overriding an existing binding, Vim surfaces the conflict so you can resolve it deliberately.
This is most valuable in plugin scripts and modular vimrc setups where you want protection against accidental collisions.
How it works
:nnoremap <unique> <leader>f :Files<CR>
If <leader>f is already mapped, Vim prints:
E227: mapping already exists for \f
And the mapping is NOT created. Without <unique>, the new mapping silently replaces the old one.
Example
" In a plugin's autoload file — guard mappings defensively
if !hasmapto('<Plug>MyPlugin')
nnoremap <unique> <Leader>mp <Plug>MyPlugin
endif
Combining <unique> with hasmapto() lets you provide a default binding while still respecting user overrides.
Tips
- Combine with
<silent>and<buffer>::nnoremap <unique> <buffer> <silent> ... - To check if a key has a mapping:
:nmap {key}or usemaparg('{key}', 'n')in Vimscript - Plugin authors should use
<Plug>mappings and let users bind them —<unique>is a secondary defense - In Neovim Lua,
vim.keymap.sethas no built-inuniqueflag; usevim.fn.hasmapto()for the same guard pattern