Vim command typos

I very often “fat-finger” some of the most common commands in Vim by holding down Shift too long after typing a colon. This means that instead of typing :w I end up typing :W, or :Qa instead of :qa, and because I use these commands so often, I type them so rapidly and reflexively that mistakes become quite common.

Since the uppercase versions of these oft-mistyped commands don’t actually correspond to any other valid command, I considered it safe to map them so that it would quietly accept this common mistake from me and understand what I actually meant to do. I did this with the following lines in my .vimrc:

if has("user_commands")
    command! -bang -nargs=? -complete=file E e<bang> <args>
    command! -bang -nargs=? -complete=file W w<bang> <args>
    command! -bang -nargs=? -complete=file Wq wq<bang> <args>
    command! -bang -nargs=? -complete=file WQ wq<bang> <args>
    command! -bang Wa wa<bang>
    command! -bang WA wa<bang>
    command! -bang Q q<bang>
    command! -bang QA qa<bang>
    command! -bang Qa qa<bang>
endif

Note the -bang and <bang> parts of each line; this allows me to include an exclamation mark in my mistyped command to force the command if a buffer is unsaved, which otherwise wouldn’t work. Additionally, I use command! with an exclamation mark to prevent errors if I reload my .vimrc file having already loaded it once. Finally, the first four commands, which can optionally take an argument, are set up to do that in their capitalised form as well.

You can list these commands and any others you or your plugins have defined by typing just :command by itself. Check out :help command for a bit more information on mapping commands in this manner.

The wrong way

This is quite different from the approach I often see recommended to work around this problem, which is using cnoreabbrev like so:

cnoreabbrev W w
cnoreabbrev Q q

I think this is a pretty bad idea because if I wanted to search for a single uppercase Q or W, it gets automatically mapped back to its lowercase equivalent in the search window. When I tried these mappings out I noticed this very quickly, and because I use case-sensitive search it rapidly got very frustrating. I am much happier with the solution I describe above, and particularly recommend it if like myself you prefer to keep ignorecase off.

Remapping for a different approach

If you don’t mind a slightly more drastic remapping, you could use another character that doesn’t require holding Shift to initiate commands, such as a semicolon, which means you won’t accidentally capitalise these common commands anymore:

nnoremap ; :

I don’t like this solution either, because the semicolon already has a function in repeating the linewise character searches you can do with f, t, F, and T, but I have seen it in several other people’s .vimrc files.