[Tex/LaTex] Command for character count including spaces (in overleaf)

countoverleaf

I'm becoming increasingly happy with overleaf, now prefering it to vscode or vim. A lot of the stuff I have to write for university needs a character count including spaces. Up until now I've been exporting as pdf and counting from there, but this process seems quite tedious. I recently found an overleaf example with character count as a command, but the problem is that this does not include spaces. The command is as follows:

\newcommand{\quickcharcount}[1]{%
\immediate\write18{texcount -1 -sum -merge -char #1.tex > #1-chars.sum }%
\input{#1-chars.sum}%
}

Additionally the include command for word count is:

\newcommand{\quickwordcount}[1]{%
\immediate\write18{texcount -1 -sum -merge #1.tex > #1-words.sum }%
\input{#1-words.sum}%
}

I therefore figured that the fastest way to get an (approximate) char count including count spaces is by adding the word count to the character count. I've been attempting to it has described here:

\numexpr \quickwordcount{main} + \quickcharcount{main}

But this just handles words and chars as strings and outputs the sum as so.

Sorry for the long confusing post, but here's the tl:dr: does anyone have an idea of have I can get the char count including as spaces in Overleaf?

Thanks

Best Answer

Here's one idea, similar to your approach, but using egreg's answer to Read number from file :

\documentclass{article}
\newread\tmp

\newcommand{\quickcharcount}[1]{%
  \immediate\write18{texcount -1 -sum -merge -char #1.tex > #1-chars.sum}%
  \openin\tmp=#1-chars.sum%
  \read\tmp to \thechar%
  \closein\tmp%
}

\newcommand{\quickwordcount}[1]{%
  \immediate\write18{texcount -1 -sum -merge #1.tex > #1-words.sum}%
  \openin\tmp=#1-words.sum%
  \read\tmp to \theword%
  \closein\tmp%
}

\begin{document}
\quickwordcount{main}
\quickcharcount{main}

There are \thechar characters and approximately \theword spaces.
That makes approximately \the\numexpr\theword+\thechar\relax\ characters total.

\end{document}

enter image description here

The \theword and \thechar macros could be extended to include the filename argument if you need to tally up multiple files, but I've kept it fairly simple here.

Related Question