Counting occurrences in Vim without marking the buffer changed

In order to know how many times a pattern exists in current buffer, I do:

:%s/pattern-here/pattern-here/g

It gives the number of occurrences of the pattern, but is obviously cumbersome and also has the side-effect of setting the 'changed' status.

Is there a more elegant way to count?


Solution 1:

To avoid the substitution, leave the second pattern empty, and add the “n” flag:

:%s/pattern-here//gn

This is described as an official tip.

Solution 2:

:help count-items

In VIM 6.3, here's how you do it.

:set report=0
:%s/your_word/&/g    # returns the count without substitution

In VIM 7.2, here's how you'd do it:

:%s/your_word/&/gn   # returns the count, n flag avoids substitution

Solution 3:

:!cat %| grep -c "pattern"

It's not exactly vim command, but it will give you what you need from vim.
You can map it to the command if you need to use it frequently.

Solution 4:

The vimscript IndexedSearch enhances the Vim search commands to display "At match #N out of M matches".