I know that vim has a function wordcount() that returns a dictionary containing the number of bytes, lines, words etc in the current buffer. The problem I have is that the words field of the dict from wordcount() seems to include the number of WORDs (vim's term for any sequence of chars that are not a whitespace character). For example, given:

# a markdown title

in a buffer, wordcount()['words'] returns 4, because the "#" counts as a word to vim. Is there some way I can count only the alphanumerical words in a buffer? I know I can use


but redirecting the output is cumbersome and slow if I want to have a constant word count (say, in the statusline). I need this for writing assignments.

1 Answer 1


You can split() on non-word characters and count the number of resulting words.

:let cnt=0 | g/./let cnt+=len(split(getline('.'), '\W\+'))
  • What does the g/./ bit do? Looks like it must cycle over the lines but I'm not sure how.
    – StevieD
    Mar 8, 2022 at 2:35
  • @StevieD :h :g
    – Matt
    Mar 8, 2022 at 5:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.