w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
VIM , how to show the count of occurrence the current match pattern under cursor?

Here is a function and a mapping to do the job (add these lines to the end of your .vimrc; it needs at least vim 7.4 and nocompatible to be set before it):

nnoremap  X  :call Count( '<C-R>=expand( '<cWORD>'
)<CR>' )<CR>

function! Count( word )
  redir => cnt
    silent exe '%s/' . a:word . '//n'
  redir END
  silent exe 's/.*/& ' . matchstr( cnt, 'd+' ) . '/'
endfunction

If you pressing X on a WORD (bordered with withespace characters), the Count function will add the count of the same words in the file to the end of the actual line.

To add the ordinal number, change Count to NthCount in the mapping and add these lines to .vimrc:

function! NthCount( word )
  redir => nth
    silent exe '0,.s/' . a:word . '//n'
  redir => cnt
    silent exe '%s/' . a:word . '//n'
  redir END
  silent exe 's/.*/& ' . matchstr( nth, 'd+' ) . '/'
  echo a:word . ': ' . matchstr( nth, 'd+' ) . '/' . matchstr( cnt, 'd+' )
endfunction

For example pressing it on the first bb:

aa
bb 1
aab
aa
bb
-- STATUSLINE --
bb: 1/2




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.