how to count words and lines in the emacs editor

One of the functionality you might want from a text editor is the ability to count words and lines in the current buffer. This is especially useful for writers, but can be useful for others a well.

There are several different ways to count the words and lines in a buffer. Some of them are built-in to the emacs depending on your versions, while others are packages that you can install.

The emacs command count-words is probably the easiest of them. Despite the name of the command, it actually does count the words, lines and characters in the current buffer.

M-x count-words

If you plan to use the command often enough, you can bind it to a easy to use shortcut. I don’t think the command is bound to a keystroke by default.

If you want to count the words in a region and not the entire buffer then you can use the count-words-region command. In practice, you may use either the count-words or the count-words-region command. If a region is selected then it will display the count of the region or else it will display the count for the whole buffer.

M-x count-words-region

Another useful command is the count-matches. It will count the matches based on the regular expression that you provide. This is useful for counting the occurrences of a particular word or phrase with in the selected region.

M-x count-matches

Another related command is the count-lines-page which will show you just the number of lines but it will also show the line count before and after the point.

M-x count-lines-page

You can also execute a shell command such as wc to count the words, lines and characters in the buffer or region. Although this does not provide any more information than the previous commands, it is good trick to know as it will allow you to run arbitrary shell commands on the buffer.

You execute the command shell-command-on-region or the shortcut M-| and then enter the shell command wc to execute it on the selected region or the buffer.