[Tex/LaTex] Cross-referencing between files and equation counters

counterscross-referencing

I am using package xr to cross reference between two files.

Is there a way to make the equation numbers in one of the files follow the ones in the other? What I mean is, if the last equation in file A is say (28), then the first equation in file (B) be (29) and so on.

Another question is, can this be done with counters for lemmas, theorems, etc?

Best Answer

A solution using package zref:

Document A

The first document test-A.tex writes the latest value of counter equation in the zref reference eq-last:

% test-A.tex
\documentclass{article}

\usepackage{zref-base}
\usepackage{atveryend}
\makeatletter
\AfterLastShipout{%
  \if@filesw   
    \begingroup
      \zref@setcurrent{default}{\the\value{equation}}%
      \zref@wrapper@immediate{%
        \zref@labelbyprops{eq-last}{default}%
      }%
    \endgroup
  \fi
}
\makeatother

\begin{document}
\begin{equation}E=mc^2\end{equation}
\end{document}

Remarks:

  • Instead of \AtEndDocument it uses the hook \AfterLastShipout that is executed after the last page is shipped out and before the .aux file is closed.

  • \zref@wrapper@immediate maps \write to \immediate\write in order to write into the .aux file directly. At this point deferred writing without \immediate will not work, because the last page is already shipped out and there is no next page.

  • The code is put inside \if@filesw and \fi. That supports \nofiles, that forbids writing to auxiliary files.

Document B

The next "book in the series" imports the references from document test-A. The reference names are prefixed with A- to avoid name clashes (\zexternaldocument):

% test-B.tex
\documentclass{article}

\usepackage{zref-xr}
\makeatletter
\zexternaldocument[A-]{test-A}
\AtBeginDocument{%
  \setcounter{equation}{\zref@extractdefault{A-eq-last}{default}{0}}%
  \zref@refused{A-eq-last}%
}
\makeatother

\begin{document}
\begin{equation}v=\frac{s}{t}\end{equation}
\end{document}

Remarks:

  • \zref@extractdefault is expandable and can be directly used inside the value part of \setcounter.
  • \zref@refused complains, if the reference is not defined. LaTeX clears the warning status for undefined refernces in \begin{document}. Thus we need \AtBeginDocument (otherwise the final "LaTeX warning: There were undefined references." might be missing).