71

There is a nice feature in Google Chrome when you do a search. It tells you the number of matches there is for the keyword you are searching for. However, in Vim I don't see such a feature. Some people suggested using %s/pattern//gn or similar:

http://vim.wikia.com/wiki/Count_number_of_matches_of_a_pattern
Unable to count the number of matches in Vim

But that is quite long really!! I am looking for the count when a press the '*', '%', or do any search using '/' and '?'.

Any idea?

10
  • 1
    You might consider asking this in superuser.com. I won't vote to close, even if this is off-topic, just because this might be an appropriate forum to find vim users. Jan 12, 2011 at 12:16
  • 10
    (And SU wouldn't be a good forum as the answer requires scripting, and please stop scattering the people that provide advanced answers!) Jan 12, 2011 at 13:34
  • 5
    I completely agree with Luc: in the stackoverflow faq (stackoverflow.com/faq), it says that "if your question generally covers... software tools commonly used by programmers ...then you're in the right place to ask your question!". Therefore, this is definitely not off-topic.
    – DrAl
    Jan 12, 2011 at 13:49
  • @Luc, thanks for the comments. What do you mean by "scattering the people that provide advanced answers!"?
    – Rafid
    Jan 12, 2011 at 14:49
  • 3
    By scattering vim questions on all SE/SO/SU site, we are lowering the global quality of the answers. @Promather, As fas as I'm concerned, you've chosen the right forum. Jan 12, 2011 at 15:12

12 Answers 12

68

Modern Vim

Starting with Vim 8.1.1270, there's a new feature in core to show the current match position. NeoVim enables this functionality by default, but standard Vim does not.

To enable it in standard Vim, run:

:set shortmess-=S

Originally mentioned below in Ben's answer, and added here for visibility.

Older Versions

In Vim 7.4+, the IndexedSearch plugin can be used.

Check henrik/vim-indexed-search on GitHub to ensure you get the latest version.

4
  • That seems to be the best answer. I will try it and see if it works well to mark your answer as the accepted answer.
    – Rafid
    Jan 12, 2011 at 16:47
  • 1
    Looks very interesting. Just be careful that it doesn't cause other plugins to stop working since it's redefining some fairly fundamental keys.
    – DrAl
    Jan 12, 2011 at 17:22
  • 5
    There is a newer version of this plugin, with included documentation and more features, at GitHub – henrik/vim-indexed-search. Oct 11, 2014 at 14:30
  • 2
    A great answer, unfortunately doesn't handle >99 matches well :( Sep 28, 2022 at 9:49
24

I don't know of a direct way of doing it, but you could make use of the way :%s/// uses the last search as the default pattern:

:nmap ,c :%s///gn

You should then be able to do a search and then hit ,c to report the number of matches.

The only issue will be that * and # ignore 'smartcase', so the results might be off by a few after using *. You can get round this by doing * followed by /UpENTER and then ,c.

1
  • 2
    You can do it like this to handle the 'smartcase' case appropriately: nnoremap ,c :%s/<C-R>=&ignorecase ? '\c' : '\C'<CR><C-R>///gn<CR>
    – Jan Larres
    Mar 10, 2012 at 6:48
13

One addition to @Al's answer: if you want to make vim show it automatically in the statusline, try adding the following to the vimrc:

let s:prevcountcache=[[], 0]
function! ShowCount()
    let key=[@/, b:changedtick]
    if s:prevcountcache[0]==#key
        return s:prevcountcache[1]
    endif
    let s:prevcountcache[0]=key
    let s:prevcountcache[1]=0
    let pos=getpos('.')
    try
        redir => subscount
        silent %s///gne
        redir END
        let result=matchstr(subscount, '\d\+')
        let s:prevcountcache[1]=result
        return result
    finally
        call setpos('.', pos)
    endtry
endfunction
set ruler
let &statusline='%{ShowCount()} %<%f %h%m%r%=%-14.(%l,%c%V%) %P'
1
  • Could I request the version that incorporates ignorecase? :P
    – Steven Lu
    May 17, 2016 at 14:47
11

Here's a cheap solution ... I used Find and Replace All in Vim. No fancy scripting. I did a Find X and Replace All with X. At the end, Vim reports "2134 substitutions on 9892 lines". X appeared 2134 times. Use :q! to quit the file without saving it. No harm done.

1
  • Or replace all replacing with the same string that you're searching for -- with the exception of some capitalization issues depending on your settings, you shouldn't change anything. Worst case, you're a u away from undoing it anyhow. Smart trick. ;^)
    – ruffin
    Nov 22, 2019 at 16:20
9

I'm not sure exactly what version added it, but this is built into Vim now, you just need to:

:set shortmess-=S

Added sometime in the 8.1.x patches (as of this writing we're at 8.1.2300).

3

You already have a good wealth of answers, but it seems to me that there is still one more approach to this problem.

This is actually something I had to deal with a few days ago. I added a function and a mapping in such a way that you hit the mapping when the cursor is under the word you want to count and it returns the number of matches.

The Function:

" Count number of occurances of a word
function Count(word)
    let count_word = "%s/" . a:word . "//gn"
    execute count_word
endfunction

And the mapping:

" Count current word 
nmap <Leader>w <Esc>:call Count(expand("<cword>"))<CR>
1
  • I suggest storing your previous search register with: :let old_query = getreg('/') and restoring at the end with: :call setreg('/', old_query). Here my "preserve" function to vim: pastebin.com/GZctZxdb and here the neovim version: pastebin.com/2SpeWFC0 Aug 18, 2021 at 19:43
2

Alternatively from what @Al suggests you can map the key combination to write most of the line and then move the cursor to the position where the actual pattern is inserted:

:nmap ,c ^[:%s///gn^[OD^[OD^[OD^[OD

Where '^[' is Ctrl+V,Esc and '^[OD' is Ctrl+V,Left

Then pressing ',c' will go into command mode, enter the pattern and leave the cursor over the second '/', ready to insert the pattern.

1

This plugin does just that. https://github.com/osyo-manga/vim-anzu

When searching for a word in vim, it will display word count on the statusline. It also has the option to display next to the searched word ie. this_is_my_sample_word (3/12), or this_is_my_sample_word(7/12). This basically says: this is the 3rd or 7th occurrence out of 12 total occurrences.

1

another nice vim plugin for that: https://github.com/google/vim-searchindex

will be shown like this:

when looking for 'cd' in the file

0
:vim[grep][!] /{pattern}/[g][j] {file} ...

Vimgrep uses Vim's built-in regex search engine, so you can reuse the patterns from Vim's standard search command. So, I first test the search pattern the normal way using: /{pattern}/

Then enter the following:

:vim /CTRL+r//g %

where CTRL+r/ will insert the last search pattern after the first slash. The status line will display (1 of max), where max is the maximum number of matches for the {pattern}. Then use the :cnext and :cprev to search for the next & previous matches and :cfirst and :clast for the first and last matches. These 4 commands can be remapped to make them faster to execute.

0

A alternative is to count using the grep command.

Ex. If you want to search TODO in current file is:

:echo system('grep -c TODO ' . expand('%:p'))
0

If you replace your patter with the pattern itself, vim reports the number of substitutions.

e.g.

:%s/Human/Human/

in my documents reports 220 substitutions on 220 lines

:%s/1/1/g

reports 294 substitutions on 252 lines since some lines contain more than one 1.

Your Answer

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

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