How do I create abbreviations for the Vim command line to fix typos like W and Q?
Answer
:cnoreabbrev {lhs} {rhs}
Explanation
:cnoreabbrev defines a non-recursive command-line abbreviation — like noremap but for Ex commands. The most practical use is silently correcting capital-letter typos (:W, :Q, :Wq) that Vim would otherwise reject as unknown commands.
How it works
:cabbrevexpands abbreviations recursively (like:map), which can cause unexpected behavior if the expansion also matches an abbreviation:cnoreabbrevexpands non-recursively and is the safer choice- Abbreviations are matched only at the start of a command and only when followed by a space, newline, or
|
Example
Add these to your vimrc:
cnoreabbrev W w
cnoreabbrev Q q
cnoreabbrev Wq wq
cnoreabbrev WQ wq
cnoreabbrev Wa wa
cnoreabbrev QA qa
Now :W<CR> silently saves without an error, and :Wq<CR> saves and quits.
You can also create convenient shortcuts:
cnoreabbrev tn tabnew
cnoreabbrev th tabprev
cnoreabbrev tl tabnext
Tips
- Unlike
iabbrev, command-line abbreviations only expand when the cursor is right after the abbreviation followed by a non-keyword character — no unintended mid-word expansion - Check existing abbreviations with
:cabbrev(no arguments) to list all defined ones - To delete an abbreviation:
:cunabbrev {lhs}