4

I would like to make use of the advantages of the cleveref package also for pseudocode I write. More precisely, I am looking for a way to get the cleveref package to work with clrscode3e such that lines of code snippets can be referenced. To illustrate how exactly I would like to use the two packages in combination, I am providing a MWE down below.

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

\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}

Unfortunately, this way, the reference is not resolved. Interestingely, using \ref instead of \cref prints the correct line number. Is there a way to get this result with cleveref as well? I have tried defining a type with \crefname, but the counter is off: I have only gotten the \cref command to print the section number.

  • 1
    cleveref doesn't support clrscode3e. You could either try to figure out, how to patch clrscode3e to make it work (the code of both packages is nicely documented) or you use algorithmicx (which is supported by cleveref) or you stick to plain \ref... – DG' Apr 18 at 12:04
1

clrscode3e quite effectively disables cleveref (and hyperref too) by not using \refstepcounter by creating the label code itself.

You could define your own \label command:

\documentclass{article}
\usepackage{clrscode3e}

\usepackage{cleveref}
\crefname{codelinenumber}{code}{code} %adapt
\newcommand\clrslabel[1]
 {\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}, \dots
\end{document}

enter image description here

  • Thank you for the suggestion. Unfortunately, if I use the \clrslabel command for multiple code boxes, referencing any but the first does not work correctly. For instance, if I label the second line of the second code box in my document, and subsequently reference the label, the line number is shown correctly, but the reference points to the first code box when clicking it. Any way of potentially fixing this? – foobar May 5 at 17:35
  • You probably need a sensible definition of \theHcodelinenumber. But your original question didn't mention hyperref, so better ask a new question. – Ulrike Fischer May 5 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.