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

How do I use a count prefix in a custom Vim mapping where no count defaults to 1?

Answer

v:count1

Explanation

The v:count1 variable holds the count typed before a command, defaulting to 1 if no count was given. This makes it ideal for mappings and functions where the action should happen at least once — unlike v:count, which returns 0 when no count is typed.

How it works

  • v:count — count typed before the command; 0 if no count was given
  • v:count1 — count typed before the command; 1 if no count was given

Both are only valid inside a mapping's right-hand side or inside a function called from a mapping. When passing the count to an Ex command, use :<C-u> in the mapping to clear the range that Vim would otherwise insert automatically.

Example

A mapping to scroll down N half-pages, defaulting to 1:

nnoremap <silent> <leader>d :<C-u>execute v:count1 . "\<C-d>"<CR>

With no count, <leader>d scrolls one half-page. Pressing 3<leader>d scrolls three.

Contrast with v:count, which breaks when no count is given:

" Broken: multiplies by 0 when no count typed
nnoremap <leader>x :<C-u>call DoThing(v:count)<CR>

" Correct: always does the action at least once
nnoremap <leader>x :<C-u>call DoThing(v:count1)<CR>

Tips

  • Always prefer v:count1 over v:count when your action should happen at least once by default
  • v:count is useful when you want to detect whether a count was explicitly given (0 = none)
  • Use :<C-u> in the mapping RHS to clear any count Vim auto-inserts into the command line

Next

How do I run a macro on every line in the file silently, ignoring errors on lines where the macro fails?