How do I set up a local leader key for file-type-specific mappings that don't conflict with global mappings?
Answer
:let maplocalleader = ','
Explanation
Vim provides two separate leader keys: <Leader> (global) and <LocalLeader> (local to the current buffer). By defining maplocalleader, you get a dedicated namespace for file-type-specific key mappings — typically placed in ftplugin/ files — that won't collide with your global mapleader bindings.
How it works
mapleader— the global leader, used in<Leader>mappings (commonly set to<Space>or\)maplocalleader— the local leader, used in<LocalLeader>mappings inftplugin/orafter/ftplugin/<buffer>flag on a mapping — makes it active only in the current buffer (essential in ftplugins)- The two leaders can be the same character but are logically distinct
Example
In your vimrc:
let mapleader = ' '
let maplocalleader = ','
In ~/.vim/ftplugin/python.vim:
" Run the current file with Python
nnoremap <buffer> <LocalLeader>r :!python3 %<CR>
" Insert a breakpoint
nnoremap <buffer> <LocalLeader>b Oimport pdb; pdb.set_trace()<Esc>
Now ,r runs Python files, but only inside .py buffers. The global <Space>r mapping is untouched.
Tips
- Always use
<buffer>alongside<LocalLeader>in ftplugin files to prevent leaking mappings to other buffers - Choose a
maplocalleadercharacter that differs frommapleaderto keep namespaces distinct - In Neovim Lua, use
vim.keymap.set('n', '<LocalLeader>r', ..., { buffer = true })for the same effect - List active buffer-local mappings with
:nmap <buffer>