0

I am looking for a way to use cleveref and hyperref in combination with the clrscode3e package. Unfortunately, the packages do not work together out-of-the-box.

More precisely, I am considering the following use case. For a given codebox, I want to be able to label a line and later reference it in the text using the \cref command. When typeset, this should print a clickable line number hyperlinking back to the line in the codebox. A MWE is depicted below.

\documentclass{article}
\usepackage{hyperref}
\usepackage{cleveref}
\usepackage{clrscode3e}

\begin{document}
\begin{codebox} 
  \Procname{$\proc{MWE}$} 
  \li $x \gets 1$ \label{lin:assign}
  \End
\end{codebox}

As shown in \cref{lin:assign}, \dots
\end{document}

I have posted a similar question not too long ago: Cleveref with clrscode3e. The question however did not involve the use of hyperref and the solution therefore cannot be mapped one-to-one. The reason, more precisely, is that the hyperlinks created by hyperref always point to the first codebox in the document, no matter the codebox containing the label.

1 Answer 1

1

You need to ensure that the hyperref destination name is unique. hyperref uses (if it exists) a \theH<counter> command. As your codebox has no counter, one must number the labels:

\documentclass{article}
\usepackage{clrscode3e}
\usepackage{hyperref}
\usepackage{cleveref}
\crefname{codelinenumber}{code}{code} %adapt
\newcounter{codelabel}
\newcommand\theHcodelinenumber{\thecodelabel.\thecodelinenumber}

\newcommand\clrslabel[1]
 {\stepcounter{codelabel}%
  \addtocounter{codelinenumber}{-1}%
  \refstepcounter{codelinenumber}%
  \label{#1}}

\begin{document}
\begin{codebox}
  \Procname{$\proc{MWE}$}
  \li $x \gets 1$ \clrslabel{lin:assign}
  \End
\end{codebox}

As shown in \cref{lin:assign}, \cref{lin:assign2}\dots

\newpage
\begin{codebox}
  \Procname{$\proc{MWE}$}
  \li $x \gets 1$ \clrslabel{lin:assign2}
  \End
\end{codebox}

\end{document}
2
  • Thanks again for providing a solution. \theHcodelinenumber seems to be defined already. Can I simply renew its definition using \renewcommand without complications?
    – foobar
    Commented May 5, 2019 at 21:20
  • 1
    In my example it isn't defined, if your document defines it, I would have to know this definition before being able to say definitivly, if you can redefine it, but the answer is probably yes. Commented May 5, 2019 at 21:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .