Categories: Utilities

Emacs Tip: Word counting with a regular expression

Here’s a word counting function for Emacs that counts the number of words in a buffer by using a regular expression:

The regular expression matches against one or more word characters. It doesn’t move the current point of the buffer so you don’t have to keep re-positioning the cursor every time you run this function.

The reason I’m posting this is because I was searching for “emacs word counting” and the forums and StackOverflow suggested using the “wc” shell command while in Linux, but at the moment was developing in Windows! How can I use it? (Update in 2018: Windows now has an Ubuntu Linux subsystem that allows the use of the wc word counting command). Another thing I found is that people write up functions that loop through words and count them. I’m guilty of doing that, but using the above function is much much easier.

Emacs has most everything that you can think of. The problem is that it’s all hidden away somewhere and you have to take the time to dig around.

Update: The how-many function is defined in replace.el. To find out more about it, press C-h f how-many RET.

Rudolf Olah is a software development expert with over 8 years of professional software developer experience. He has produced the video courses "Reactive Programming in Python with RxPy, PyQt5 and Tornado" and "Learning AngularJS Testing" for PacktPublishing. Rudolf offers web development training courses for individual developers and for web development teams. He writes about tech leadership, career coaching and project management.