How can I count the number of words in a file whilst editing the file in vim

You can count words and lines inside vi using vi's own counter:

Press g and then CTRL-g. Then the bottom line look for example like this:

Col 1 of 11; Line 1 of 106; Word 1 of 344; Byte 1 of 2644

Or use vi's method to call shell commands:

:w !wc -w

This calls the save (:w) command first and then wc -w and shows the output. Example:

:w !wc -w
344

Press ENTER or type command to continue

Press Enter to go back to vi.


Since vim version 7.4.1042

Since vim version 7.4.1042, one can simply alter the statusline as follows:

set statusline+=%{wordcount().words}\ words
set laststatus=2    " enables the statusline.

Word count in vim-airline

Word count is provided standard by vim-airline for a number of file types, being at the time of writing: asciidoc, help, mail, markdown, org, rst, tex ,text

If word count is not shown in the vim-airline, more often this is due to an unrecognised file type. For example, at least for now, the compound file type markdown.pandoc is not being recognised by vim-airline for word count. This can easily be remedied by amending the .vimrc as follows:

let g:airline#extensions#wordcount#filetypes = '\vasciidoc|help|mail|markdown|markdown.pandoc|org|rst|tex|text'
set laststatus=2    " enables vim-airline.

The \v statement overrides the default g:airline#extensions#wordcount#filetypes variable. The last line ensures vim-airline is enabled.

In case of doubt, the &filetype of an opened file is returned upon issuing the following command:

:echo &filetype

Here is a meta-example:

vim-airline word count

Tags:

Vi

Vim