[Tex/LaTex] Cleveref can’t refer to line numbers in listings

cleverefcross-referencinglistings

Consider the following minimal example:

\documentclass{article}

\usepackage{listings}
\usepackage{cleveref}

% \crefname{lstnumber}{line}{Line}

\begin{document}

% \section{Section}

\begin{lstlisting}[escapechar=@]
Lorem ipsum@\label{lineref}@
\end{lstlisting}

See \cref{lineref}: line~\ref{lineref}.

\end{document}

Compiling this document (twice) produces the warning

LaTeX Warning: cref reference format for label type `' undefined on input line 16.

And the output is:

See ??: line 1.

If I uncomment the \section{Section} line, everything compiles, and the reference comes out as

See section 1: line 1.

It seems that cleveref is picking up on the closest ambient reference for some reason, and not referring to the line number. Note that, in longer examples, the \ref command always produces the right line number.

The version of cleveref I'm using shouldn't need a manual \crefname{lstnumber}{line}{Line}, and indeed, uncommenting that doesn't change anything.

The relevant information from my log file is:

This is pdfTeX, Version 3.1415926-1.40.10 (TeX Live 2009/Debian) (format=pdflatex 2011.7.11)  21 APR 2012 21:29
...
(/usr/share/texmf-texlive/tex/latex/listings/listings.sty
...
(/usr/share/texmf-texlive/tex/latex/listings/lstmisc.sty
File: lstmisc.sty 2007/02/22 1.4 (Carsten Heinz)
...
(/usr/share/texmf-texlive/tex/latex/listings/listings.cfg
File: listings.cfg 2007/02/22 1.4 listings configuration
...
Package: listings 2007/02/22 1.4 (Carsten Heinz)
...
(/home/cs-students/12abs1/texmf/tex/latex/cleveref/cleveref.sty
Package: cleveref 2012/02/15{} v0.18.4{} Intelligent cross-referencing
Package cleveref Info: `listings' support loaded on input line 2843.
Package cleveref Info: loaded `english' language definitions on input line 6732
...

Any thoughts on what's going on, or how to fix it?

Best Answer

Try with the latest version v0.18.5. The changelog says

Fix listings and algorithm package support, broken by change to local rather than global \cref@currentlabel denitions....

From Gonzalo Medina's comment it seems that this solved it, but if it hadn't I'd say you should write to Toby Cubitt, author of cleveref with your MWE. He is very helpful and quite likely to make a bugfix.