First, it is important to understand why the substitution is applied on [count]
lines when you do [count]q;
.
10q;
doesn't execute q;
10 times. It prepends 10
to the stream of inputs taken from the right-hand-side of your q;
mapping. In some cases it might behave like if you repeated your mapping 10 times:
nnoremap <key> dd
10<key> " same as 10dd
but, in your case, 10
is prepended to :call
and, as explained under :help N:
, a count before :
is automatically transformed into a range. But you are not done yet, :help :call
has this to say about [count]
:
[…]
When a range is given and the function doesn't handle it
itself, the function is executed for each line in the range,
with the cursor in the first column of that line. The cursor
is left at the last line (possibly moved by the last function
call). The arguments are re-evaluated for each line.
[…]
So this is your chain of transformations:
10q;
10:call Add_comment_css()<CR>
:.,.+9call Add_comment_css()<CR>
which explains why you end up calling that function on 10 lines.
From there, the next thing to decide is what meaning you want to give to 10
in 10q;
:
- Do you want it to express the number of lines you want to cover (current behavior)?
- Do you want it to be ignored?
- Do you want it to express the number of leading comments you add to the line?
If you want [count]
to be ignored, then you should probably avoid giving a count to begin with. That's extra work that you want to have no effect so why bother?
If the count is accidental (it happens), then you could simply use the old :help c_ctrl-u
technique:
nnoremap q; :<C-u>call Add_comment_css()<CR>
where <C-u>
removes any accidental range before call…
, or its more modern :help <Cmd>
alternative:
nnoremap q; <Cmd>call Add_comment_css()<CR>
If you want [count]
to express the number of leading comments you add to the line, then you will have to disable its native implicit handling first, then handle it explicitly:
function! Add_comment_css()
for i in range(v:count1)
silent s/^/\/\*
endfor
endfunction
nnoremap q; <Cmd>call Add_comment_css()<CR>
If you are still using an older Vim without <Cmd>
, use this mapping instead:
nnoremap q; :<C-u>call Add_comment_css()<CR>
See :help :for
, :help range()
, and :help v:count1
.
10q;
works is that it becomes:.,.+9call Add…()
, which calls the function once for each line in the range since the function is not declared to handle the range itself.