This pattern is very useful to me to get the count of a pattern in a vim file:


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.

  • Lol that's so hacky.. even with vim standards – abbood Mar 8 '18 at 5:28
  • The idea comes from Damian's Conway. It does the job and works the same on every platform, I would say it's not that bad :) – statox Mar 8 '18 at 9:03

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)

  • 1
    Could use :keeppatterns with your substitution to prevent the search register mutation. – Peter Rincker Mar 7 '18 at 19:11
  • @PeterRincker. Yes, you're right. The thing is I'm not completely used to it yet ^^' – Luc Hermitte Mar 7 '18 at 21:52
  • 1
    @LucHermitte yeah, it is only available for 4 years :) – Christian Brabandt Mar 7 '18 at 21:57
  • 1
    @ChristianBrabandt. Exactly, It's much too recent ^^ – Luc Hermitte Mar 7 '18 at 21:58
  • 1
    More seriously, in my plugins I often struggle to stay compatible with older versions of vim. As such, there are a few things that haven't entered yet in my everyday vocabulary. – Luc Hermitte Mar 7 '18 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.