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 se
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.
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.
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>
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'
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.
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
.