This pattern is very useful to me to get the count of a pattern in a vim file:
:%s/pattern//gn
How can I do a keymap so that I can simply invoke it + pattern
while I'm in vim?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityThis pattern is very useful to me to get the count of a pattern in a vim file:
:%s/pattern//gn
How can I do a keymap so that I can simply invoke it + pattern
while I'm in vim?
You can use a mapping like this:
nnoremap S :%s///gn<LEFT><LEFT><LEFT><LEFT>
<LEFT>
is the left arrow key which allows you to move your cursor in command line mode. This way you can press S
+ pattern
and you are good to go.
You should also be able to ask the user to type the pattern with <c-r>=input("What do you want to count?")<cr>
.
But I don't find this approach very ergonomic, I avoid using input()
as much as possible.
Instead, I have another approach: I've defined a Count
command. In the end, I type :Cou<tab> <pattern><cr>
.
It could be defined with the one-liner:
command! -nargs=1 -range=% Count
\ echo eval(join(map(getline(<line1>,<line2>), 'count(v:val, "<args>")'), '+'))
Or if you prefer to stick with s//gn
->
command! -nargs=1 -range=% Count keeppatterns <line1>,<line2>s/<args>//gn
(I prefer the solution with :echo
as it leaves the search register unchanged, and as such it doesn't change what's highlighted when &hlsearch
is set)
:keeppatterns
with your substitution to prevent the search register mutation.
Mar 7, 2018 at 19:11