2

A \ref in LaTeX expands to the text of the current label at the point of the corresponding \label, followed by an empty \hbox. In LaTeX3 this \hbox is an explicit \null in the definition of \\@setref, so also appears after the page number in an expanded \pageref.

Why would you want an empty \hbox there? (It makes it hard to use \ref to generate, for example, file names or csnames.)

The \null was there in LaTeX2.09, so has been carefully preserved in rewriting

Willoughby
  • 3,649
Geraint
  • 23
  • 2
    You can't use \ref in any event to construct filenames, because \ref is not expandable. As I recall, there is an expandable alternative...\usepackage{refcount} and \getrefnumber. – Steven B. Segletes Jul 07 '21 at 14:49
  • Perhaps this question, https://tex.stackexchange.com/questions/518923/getting-the-equation-number-as-an-integer, is a duplicate – Steven B. Segletes Jul 07 '21 at 15:03
  • It's not quite a duplicate: the questkon was more about the motivation for putting the \null there. Likewise, something related to package refcount is what I had been implementing, but I was wondering why \ref itself was not useful in doing so. Thanks for that. – Geraint Jul 08 '21 at 11:01

1 Answers1

2

Let's see the code:

% latex.ltx, line 10226:
\def\ref#1{\expandafter\@setref\csname r@#1\endcsname\@firstoftwo{#1}}

Say we have \ref{foo}. The token \r@foo is built before expanding \@setref, so we get

\@setref\r@foo\@firstoftwo{foo}

Now let's see the definition of \@setref:

% latex.ltx, line 10217:
\def\@setref#1#2#3{%
  \ifx#1\relax
   \protect\G@refundefinedtrue
   \nfss@text{\reset@font\bfseries ??}%
   \@latex@warning{Reference `#3' on page \thepage \space
             undefined}%
  \else
   \expandafter#2#1\null
  \fi}

If the cross reference is not yet resolved, the test \ifx\r@foo\relax returns true and it's not the part that interests us. Suppose \r@foo is defined; then we get

#1 <- \r@foo
#2 <- \@firstoftwo
#3 <- foo

and the expansion becomes

\expandafter\@firstoftwo\r@foo\null

The expansion of \r@foo will be something of the form {1.1}{1}, where the first braced part is the cross reference and the second part is the page number, so we'd get

\@firstoftwo{1.1}{1}\null

With \pageref it would be essentially the same, but with \@secondoftwo.

Why \null? It sets the space factor to 1000 and avoids ligatures. Ligatures are not very likely to happen, but you don't want a period at the end of the number to be an end-of-sentence period.

I'm not sure how you'd make control sequences or file names from \ref. However, it's not difficult to make an expandable version of \ref by changing the “true text” in the \ifx so it is really expandable and removing \null.

egreg
  • 1,121,712