Expand control sequence previously written to file
You need to input \reffile
-at the start- to collect the values from the previous run. as is you do
\immediate \openout \refs = \reffile
which empties the file just before you do
\input \reffile\
incidentally that line should be
\input \reffile
otherwise you will force white space into the document.
\def \reffile {refs}%
\newwrite \refs
\newread\refcheck
\openin\refcheck=\reffile
\ifeof\refcheck\else
\input \reffile
\fi
\immediate \openout \refs = \reffile
\def \label #1{\def \text {#1}\makelabel}%
\def \makelabel {\edef \writeit
{\write \refs
{\def \expandafter\string\csname \text \endcsname
{\noexpand \number \pageno}}}%
\writeit
}%
\def \ref #1{\expandafter \ifx \csname #1\endcsname \relax
\immediate \write 16 {Undefined label ``#1''.}%
\else \csname #1\endcsname \fi
}%
The main problem is, as already remarked by David Carlisle, that you're inputting \reffile
after having opened it for writing, but this operation clears the file.
You also have assorted slips; for instance, closing the file should not be immediate, or you might lose material. Second, you are defining macros in the wild, which could overwrite existing ones. If you do \label{box}
, you'll end up in very deep trouble. So it's better to decorate the macros with some prefix.
You also have a level of indirection that doesn't seem needed: it's useful if you have some part of the token list to be written that should be expanded immediately, which is not your case. There's no point in defining \text
: the less macros you define, the least is the risk of overwriting needed ones.
I added a check for duplicate labels. Instead of writing directly the macros to the auxiliary file, I think it's better to have a \newlabel
macro: it makes writing much easier.
\edef\reffile{\jobname refs.tex}
% read the labels
\def\newlabel#1#2{%
\expandafter\show\csname ref@#1\endcsname
\expandafter\def\csname ref@#1\endcsname{#2}%
}
\newread\refcheck
\openin\refcheck=\reffile\relax % <--- important
\ifeof\refcheck % still no refs file
\else
\input\reffile
\fi
\closein\refcheck
\newwrite\refs
\immediate\openout\refs=\reffile % this clears the file
\def\label#1{%
\expandafter\ifx\csname label@#1\endcsname\relax
\write\refs{\string\newlabel{#1}{\the\pageno}}%
\global\expandafter\let\csname label@#1\endcsname\empty
\else
\immediate\write16{Duplicate label ``#1''.}%
\fi
}
\def\ref#1{%
\expandafter\ifx\csname ref@#1\endcsname\relax
\immediate\write16{Undefined label ``#1''.}%
\else
\csname ref@#1\endcsname
\fi
}
foo\label{foo}
\vfill\eject
bar (\ref{foo})%
\closeout\refs % not \immediate
\bye