1
\def\totalobjects@putlabel{%
 \addtocounter{totalpage}{\c@page}
 \immediate\write\@auxout{\string
   \newlabel{reftotaltables}{{}{\refstepcounter{totalpage}}{\relax }{}{}}}
}
\AtEndDocument{\totalobjects@putlabel}

Or how I can make next work:

\def\totalobjects@putlabel{%
 \addtocounter{totalpage}{\c@page}
 \refstepcounter{totalpage}\label{reftotalpages}
}
\AtEndDocument{\totalobjects@putlabel}

I am using XeLaTeX. After using the second snippet, label doesn't work (I see «??», when refer to it). After using the first snippet, I receive compile errors.

  • 1
    Welcome to TeX.SX! Without a minimal example it's difficult to say. Do you want to have a page numbering of the form “page n of m”? If so, look at the lastpage package. – egreg Apr 28 '14 at 8:37
  • @egreg I also have another counters (for figures, bibliography and tables), so it is needed to add a label with calculated counter to the end of the document. The second snippet will work, if I add \null or \newpage before \addtocounter, but both of \null and \newpage adds new empty page to the end of my document. How I can escape from this? The first one perfectly works with \thepage instead of \refstepcounter{totalpage} (I also have tried \value{totalpage}). – yttrium Apr 28 '14 at 8:42
  • \usepackage{totcount}, if you don't want to reinvent the wheel. ;-) – egreg Apr 28 '14 at 9:09
1

Writes to the .aux files happen when a page is shipped out, unless \write is preceded by \immediate, as in your first code.

However, the first code can't work, because the page number is unpredictable unless LaTeX is shipping out a page or has just shipped out one: the page number counter is stepped at the end of the shipout procedure. So an \immediate\write is not guaranteed to work reliably.

With the second code you use \label, which in turn relies on writing to the .aux file but without \immediate, so the corresponding \newlabel command can be written out only at the next shipout. But there is no next shipout when you put the code in \AtEndDocument.

You could use the atveryend package for solving the issue; but if all you need is to write something in the .aux file to have available the final value of some counters, then the totcount package already does it for you.

With

\usepackage{totcount}
\regtotcounter{section}

in your document preamble, you can type \total{section} anywhere you need to print the highest section number in the document.

For having a reference to the last page number, do

\usepackage{lastpage}

and use \pageref{LastPage} where you want the last page number. Or use zref that has a very extensible mechanism.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.