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?


2 Answers 2


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
    Commented Mar 8, 2018 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
    Commented Mar 8, 2018 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. Commented Mar 7, 2018 at 19:11
  • @PeterRincker. Yes, you're right. The thing is I'm not completely used to it yet ^^' Commented Mar 7, 2018 at 21:52
  • 1
    @LucHermitte yeah, it is only available for 4 years :) Commented Mar 7, 2018 at 21:57
  • 1
    @ChristianBrabandt. Exactly, It's much too recent ^^ Commented Mar 7, 2018 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. Commented Mar 7, 2018 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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