Skip to content

Instantly share code, notes, and snippets.

@smith558
Last active December 2, 2023 12:00
Show Gist options
  • Save smith558/b25ddced6ad00320aa15934d71fffe8e to your computer and use it in GitHub Desktop.
Save smith558/b25ddced6ad00320aa15934d71fffe8e to your computer and use it in GitHub Desktop.
LaTex word count

Integrating texcount directly into a LaTeX document to display a live word count requires a bit of setup. Here's a basic method to do this:

Step 1: Enable Shell Escape

First, make sure that shell escape is enabled in your LaTeX compiler. This is necessary because the document will need to run external commands (texcount in this case).

  • For pdflatex, you can enable shell escape by compiling with the -shell-escape option (e.g. pdflatex -shell-escape yourfile.tex).
  • If you're using an editor like TeXShop or Overleaf (for Overleaf, yourfile.tex file must be named output.tex), check their respective settings or documentation on how to enable shell escape.

Step 2: Define a New Command in Your LaTeX Document

In your LaTeX document, you need to define a new command to run texcount and import its output. Add the following to your preamble (before \begin{document}):

\newcommand\wordcount{
    \immediate\write18{texcount -1 -sum -merge \jobname.tex > \jobname-words.sum }
    \input{\jobname-words.sum}
}

This command does the following:

  • The \immediate\write18 command allows LaTeX to execute an external shell command.
  • texcount -1 -sum -merge \jobname.tex runs texcount on the current document (\jobname.tex), with options to output the sum of words.
  • The output is then redirected to a file named \jobname-words.sum.
  • \input{\jobname-words.sum} reads the contents of this file and inserts it into the document.

Step 3: Use the Command in Your Document

Anywhere in your document where you want the word count to appear, use the command \wordcount. For example:

\begin{document}

This document contains \wordcount{} words.

\end{document}

Each time you compile your document, the word count will be updated.

Important Notes

  • This method requires that your LaTeX distribution is configured to allow running shell commands (shell escape). This can pose a security risk if you run documents that you haven't authored yourself.
  • If you are using an online LaTeX editor like Overleaf, this method might not work due to restrictions on running external shell commands.
  • The accuracy of the word count depends on the complexity of your document. texcount has limitations, especially with documents that contain a lot of non-standard text (like heavy mathematical formulas).
@smith558
Copy link
Author

smith558 commented Dec 1, 2023

pdflatex -shell-escape yourfile.tex

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment