5

in this document \thepage give me wrong number (in first paragraph of each page)

\documentclass{article}
\textheight5\baselineskip
\begin{document}
test -\thepage-

test -\thepage-

test -\thepage-

test -\thepage-

test -\thepage-

test -\thepage-

test -\thepage-

test -\thepage-

test -\thepage-

test -\thepage-

test -\thepage-\\
test -\thepage-\\
test -\thepage-\\
test -\thepage-\\
test -\thepage-\\
test -\thepage-

test -\thepage-

\end{document}
touhami
  • 19,520

1 Answers1

7

In your example you have a six line paragraph, whereas there's only place for at most five lines in the page.

The paragraph is fully typeset, then the lines (as horizontal boxes) are sent to the “recent contributions list” and the “page builder is exercised”, that is, the material in the recent contributions is moved to the main vertical list and TeX does its internal computations to see whether a page break must be issued, and where.

In this case, it obviously has to break pages, so a part of the just typeset paragraph will be on page n, while some other part will be on page n+1. However all \thepage commands will have already been fully expanded to the value n and nothing can change this any more, because the paragraph has already been typeset.

If instead you use \pageref, the page number will be assigned from the value gathered from the previous LaTeX run, so they'll be correct unless page breaks have changed in the meantime. Another run of LaTeX will fix the situation.

You can rely upon the value of \thepage only immediately after a \newpage command, because such a command ends the paragraph possibily being built and makes TeX exercise the page builder.

Well, one can think to borderline situations where not even at such a point \thepage is reliable (big floats, for instance).

egreg
  • 1,121,712
  • thanks for details. can i ask : is it possible to built test in \pageref. I want to know if a newpage start or not. – touhami Apr 19 '15 at 15:46
  • @touhami Can you be more precise? You cannot know, when typesetting a paragraph, whether it will be split across pages. – egreg Apr 19 '15 at 15:49
  • i think in somme thing like this (\label{a}blabla....\label{b}) and test if \pageref{a}=\pageref{b} is it possible? – touhami Apr 19 '15 at 16:04
  • @touhami Not with \pageref, but the numbers can be compared with \getpagerefnumber from the package refcount, or with methods using zref. Maybe a new question is better, so you can explain the problem with more details. – egreg Apr 19 '15 at 16:07