There are two parts to a solution.
First is to make a .tex file that detects whether it's being compiled on the first run or not:
\documentclass{article}
\makeatletter
\AtEndDocument{\write\@auxout{\gdef\string\notfirstrun{}}}
\newcommand{\iffirstrun}{%
\@ifundefined{notfirstrun}}
\makeatother
\begin{document}
foo
\iffirstrun{yes}{no}
\end{document}
(Note that the syntax for the use of \iffirstrun is different from that for standard \iff... constructs. That could be fixed, of course.)
This solution puts a line \gdef\notfirstrun{} in the .aux file, to flag that the next run is not the first.
However, with only that part of the solution, when latexmk is again invoked after a change in source file(s), the first actual run will not be treated as a first run by the document. This is normally not desired. One could avoid this by deleting the .aux file, which may result in a lot of extra processing (and is easy to forget). This problem is solved by the following code in a latexmkrc file:
$latex = 'internal my_latex latex %O %S';
$lualatex = 'internal my_latex lualatex %O %S';
$pdflatex = 'internal my_latex pdflatex %O %S';
$xelatex = 'internal my_latex xelatex -no-pdf %O %S';
sub my_latex {
if ( ( -e $aux_main ) && ($pass{$rule} == 1) ) {
print "========Remove any 'notfirstline' line from aux file\n";
my $aux_bak = "$aux_main.bak";
rename $aux_main, $aux_bak;
my $auxold = new FileHandle;
my $auxnew = new FileHandle;
open $auxold, "<$aux_bak";
open $auxnew, ">$aux_main";
while (<$auxold>) {
if ( ! /^\\gdef \\notfirstrun\{\}$/ ) { print $auxnew $_; }
}
close $auxold;
close $auxnew;
}
return system( @_ );
}
It uses a couple of internal variables of latexmk: $aux_main and $pass{$rule}.
\IfFileExists{\jobname.aux}{yes}{no}in the preamble as the aux file is generated on the first run, at\begin{document}so by definition it's not there on teh first run in the preamble – David Carlisle Mar 24 '18 at 16:53Missing \begin{document}, but refrained, haha. – Andreas Storvik Strauman Mar 24 '18 at 17:50