16

In the following code, if you change \def to \edef the code crashes. Nor can you perform normal string operations or tests. Removing hyperref (and replacing \ref* with \ref) works fine with \edef. Is there a way to convert \ref* into a usable string?

\documentclass{article}
\usepackage{hyperref}
\begin{document}
\section{Section}\label{first}

\def\temp{\ref*{first}}\noindent Section = \temp

%\edef\temp{\ref*{first}}\noindent Section = \temp

\end{document}
cgnieder
  • 66,645
John Kormylo
  • 79,712
  • 3
  • 50
  • 120
  • Can you elaborate more on what you mean by usable string? From the [tag:xstring] I'm guessing there is more to this question. – percusse Oct 26 '14 at 20:30

2 Answers2

16

\ref can't go in \edef no matter whether you load hyperref or not. The code

\documentclass{article}
\begin{document}
\section{Section}\label{first}

\edef\temp{\ref{first}}\noindent Section = \temp

\end{document}

stops with

! Missing control sequence inserted.
<inserted text> 
                \inaccessible 
l.5 ...\temp{\ref{first}}\noindent Section = \temp

Only if the label has already been written to the .aux file the \edef works. In any case, no command with a *-variant or optional argument can go in \edef (unless it's defined in a special way with xparse).

Solution:

\documentclass{article}
\usepackage{refcount}
\usepackage{hyperref}
\begin{document}
\section{Section}\label{first}

\edef\temp{\getrefnumber{first}}\noindent Section = \temp

\end{document}

On the first run after the \label has been added, \temp will expand to 0. Upon rerunning LaTeX, you'll get the correct reference.

egreg
  • 1,121,712
0

I am not sure whether my answer perfectly answers the question, but the problem that I had seems very related, so I am posting my answer anyway -- hopefully it is useful to someone.

I had to perform a computation with a reference, i.e., to add some number to the value of, e.g., \ref{some-label}. However, the result of \ref{some-label} was not recognized as number (although the output, if printed, is a number). Thus, I was not able to use it as a number, getting a ! Missing number, treated as zero. error message. Instead, using \getrefnumber{some-label} solves the problem, i.e., then computations can be done.

  • 1
    The problem is similar (calculations require expandable arguments) and so is the solution (use refcount's \getrefnumber). Therefore, it doesn't seem to add anything new to this post is not already covered. – Werner Jan 26 '19 at 18:52