A mapping I added to my .vimrc based on the answers here:
" count nr of occurrences of word under cursor
nnoremap <leader>c :%s/<c-r><c-w>//gn<cr>
" count nr of occurrences of visual selection
vnoremap <leader>c :<c-u>%s/<c-r>*//gn<cr>
A bit of explanation, hopefully helpful for newer vimmers:
<c-r><c-w>
inserts the word under the cursor in the command line, super handy in many occasions.The
<c-u>
is needed to remove the automatically inserted'<,'>
when pressing:
in visual mode and going to the command line. The*
register contains the (last) visual selection, so<c-r>*
inserts the contents of the register in the command line (can also be used in insert mode).