I'm not very familiar with Overleaf, and so can't tell how Overleaf does things. But as far as I understand it uses TeXcount to do the counting which I do know.
TeXcount initially processes individual TeX files, but can add included files in two different ways:
-inc
makes a list of included files which are counted separately
-merge
tries to merge included files in where included
In this case, -merge
is required for this to work. This will simply read the included file and insert the content in place.
If you are using -inc
, the main file will be processed/counted first, and then the included files will be processed afterwards. This would give the described behaviour as \usepackage{subfiles}
is only parsed when packages.tex
is processed.
The macro processing rule for \subfile
is only set up when TeXcount detects that the subfiles
package is included, so if -inc
is used it will remain undefined (TeXcount will use a default processing rule) when parsing the main file until later when packages.tex
is processed.
The default rule, used if no other rule is specified by or to TeXcount, is that the macro does nothing. So this would make TeXcount process \subfile{myfile}
by counting myfile
as a word of text.
If this is not the cause, you would have to provide more details: like what options TeXcount is run with and some more details on what output it produces.
TeXcount comes with options to generate verbose output detailing exactly how every bit of TeX code is parsed and counted, but I suspect this cannot easily be run within Overleaf. The TeXcount web service provides this, but cannot handle multiple files.
From OP: In accordance with this advice, the following code works. Replacing -merge with -inc reproduces the Overleaf Word Count undercounting behavior.
\usepackage{verbatim}
\newcommand{\detailtexcount}[1]{
\immediate\write18{texcount -merge -sum #1.tex > #1.wc }%
\verbatiminput{#1.wc}
}
\begin{document}
\detailtexcount{main}
main.tex
,subfile.tex
, andpackages.tex
. You would want each of them to be as short as possible that still exhibits the behavior you're describing. Then you would post the content here.