There are two ways this can be accomplished, the pure vimscript way and the wc
way.
The pure vim way
You can use the search and replace command to do this. For example:
:%s/\<\w\{-}\>//gn
What this does is instead of replacing a given pattern with something, it just counts the occurrences of the pattern. This is because of the n
flag. To count the words in a specific section (in this case lines 5 through 15), you could do something like this:
:5,15s/\<\w\{-}\>//gn
This removes the need to yank the contents of a selection into a register. To see more possibilities for what can be put in place of 5-15
, read the help topic for cmdline-ranges
. If you want to do this often, it is probably good to create a mapping (or command) for it. Also, if you have hlsearch
enabled, you might want to run :nohlsearch
afterwards to clear the highlighting.
The wc
way
The same thing can be accomplished with wc
. In the same way you can use cmdline-ranges
to select the area with the :s
command, you can use them with external commands. For example:
:5,15!wc -w
This runs lines 5 through 15 through the wc
command. The downside to this is that it replaces that range of lines with the output of the command. You can undo this change by pressing u
. Also note that the vimscript solution may not work with different languages, because \w
does not match what would normally be word characters in other languages. wc
may do better at this than \w
. Also, here is a fancy command to make it faster to do this:
command -range=% -addr=lines WordCount execute '<count>!wc -w' | .y a | undo | echo @a
Note that this clobbers the a
register.
Note
It appears that this can also be accomplished in visual mode with the g<C-g>
key combination. See Carpetsmoker's answer for an explanation of this.