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;0if no count was givenv:count1— count typed before the command;1if 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:count1overv:countwhen your action should happen at least once by default v:countis 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