vimtricks.wiki Concise Vim tricks, one at a time.

How do I prevent a count prefix or visual range from corrupting an Ex command in a Vim mapping?

Answer

:<C-u>MyCommand<CR>

Explanation

When writing nnoremap or vnoremap mappings that call Ex commands, Vim may silently prepend a count or a visual range ('<,'>) to your command before it runs. Inserting <C-u> immediately after the : erases that automatic prefix, giving you a clean command line every time. This is one of the most important patterns for writing robust, predictable mappings.

How it works

  • In a mapping, after :, Vim may automatically insert things like 5 (a count) or '<,'> (a visual selection range)
  • <C-u> in command-line mode deletes from the cursor back to the beginning of the line, clearing whatever was auto-inserted
  • The mapping then executes the intended command without side effects

Example

A naive mapping that breaks with a count prefix:

nnoremap <leader>w :write<CR>

If the user types 3<leader>w, Vim sends :3write, which writes to file number 3 — not what you want.

The robust version:

nnoremap <leader>w :<C-u>write<CR>

Now 3<leader>w safely runs :write, ignoring the count.

For a visual mode mapping:

xnoremap <leader>s :<C-u>call MySort()<CR>

Without <C-u>, Vim would insert '<,'> before call, calling :'<,'>call MySort() — likely an error. With <C-u>, the function receives a clean command line and can use '<,'> explicitly inside the function if needed.

Tips

  • Always use :<C-u> in nnoremap, xnoremap, and vnoremap mappings that call Ex commands or functions
  • If your command intentionally needs the visual range, pass it explicitly: :<C-u>call MyFunc(line("'<"), line("'>"))<CR>
  • <C-u> in insert mode deletes from cursor to start of line; in command-line mode it clears the line — the behavior differs by mode

Next

How do I encode and decode JSON data in Vimscript for configuration and plugin development?