# Pageref inside alltt

Here is minimal working example that shows bug:

\documentclass[a4paper,12pt,openany]{book}
\usepackage{alltt}

\begin{document}
\begin{alltt}
\pageref{asd fgh jkl}
\end{alltt}
\end{document}


I would expect that output would be

??


Instead, what I get is

?? fgh jkl


\pageref works fine as long as there are no spaces in argument. When there are spaces, then all the words except the first one are outputed aswell. How can I prevent it? Thanks.

-

This is another good reason for not using spaces in labels. However, forcing them to be "real spaces" works:

\documentclass[a4paper,12pt,openany]{book}
\usepackage{alltt}

\begin{document}
\begin{alltt}
\pageref{asd\string fgh\string jkl}
\end{alltt}
\label{asd fgh jkl}
\end{document}


Alternative method:

\documentclass[a4paper,12pt,openany]{book}
\usepackage{alltt}
\newcommand{\ttpageref}{\begingroup\catcode\ =10 \ttpagerefaux}
\newcommand{\ttpagerefaux}[1]{\pageref{#1}\endgroup}

\begin{document}
\begin{alltt}
\ttpageref{asd fgh jkl}
\end{alltt}
\label{asd fgh jkl}
\end{document}


You can also use \pageref directly, with a more complicated setup:

\documentclass[a4paper,12pt,openany]{book}
\usepackage{alltt}
\let\latexpageref\pageref
\newcommand{\ttpageref}{\begingroup\catcode\ =10 \ttpagerefaux}
\newcommand{\ttpagerefaux}[1]{\latexpageref{#1}\endgroup}
\usepackage{etoolbox}
\AtBeginEnvironment{alltt}{\let\pageref\ttpageref}

\begin{document}
\begin{alltt}
\pageref{asd fgh jkl}
\end{alltt}
\label{asd fgh jkl}
\end{document}

-
Thanks I'll accept this answer as it allows me to use \pageref directly. – Marin Jul 13 '12 at 14:07
@Marin The real answer is in the first line, though. – egreg Jul 13 '12 at 14:10

You presumably don't just get the stated output but also the error

! Missing \endcsname inserted.


simplest way to avoid it is to hide the ref in a temp macro, Or if you prefer you can make the space safe with \string

\documentclass[a4paper,12pt,openany]{book}
\usepackage{alltt}

\begin{document}
\label{asd fgh jkl}
\def\foo{\pageref{asd fgh jkl}}
\begin{alltt}

\foo

\pageref{asd\string fgh\string jkl}

\end{alltt}
\end{document}

-
Would it be possible somehow to pass argument through \foo for example so I would not have to define a new temp macro for each \pageref? – Marin Jul 13 '12 at 13:55
perhaps you prefer the second version with \string? – David Carlisle Jul 13 '12 at 14:00
Yes, I like the second version more. – Marin Jul 13 '12 at 14:07