Create a smart cross-reference to a line in an 'algorithmic' environment using \autoref
The line counter is hidden from hyperref
's \autoref
because the counter is stepped using \addtocounter{ALG@line}{1}
instead of \refstepcounter{ALG@line}
. The following patch corrects this, allowing you to define \ALG@lineautorefname
:
\documentclass{article}
\usepackage{algorithm,algpseudocode}
\usepackage{hyperref,etoolbox}
\makeatletter
\patchcmd{\ALG@step}{\addtocounter{ALG@line}{1}}{\refstepcounter{ALG@line}}{}{}
\newcommand{\ALG@lineautorefname}{Line}
\makeatother
\newcommand{\algorithmautorefname}{Algorithm}
\begin{document}
See \autoref{alg:myalg}, specifically \autoref{algl:y}.
\begin{algorithm}
\caption{An algorithm}\label{alg:myalg}
\begin{algorithmic}[1]
\State Do X
\State Do Y \label{algl:y}
\State $x = y + z$
\end{algorithmic}
\end{algorithm}
\end{document}
The following is a cleveref
-based solution. Note: \cref
(the main user macro of the cleveref
package) works very much like \autoref
, except that it's actually far more powerful and flexible than \autoref
. For instance, \cref
can take multiple arguments; see the code below for an example. Further good news: cleveref
is programmed "out of the box" to know that lines in an algorithmic
environment should be called, well, "lines" -- no need to provide this setup yourself.
\documentclass{article}
\usepackage{algorithm,algpseudocode}
\usepackage[colorlinks]{hyperref}
\usepackage[noabbrev,capitalize,nameinlink]{cleveref}
\begin{document}
\begin{algorithm}
\caption{Baseline}\label{ALG_baseline}
\begin{algorithmic}[1]
\State Do X
\State Do Y \label{algl:y}
\State $x = y + z$ \label{algl:sum}
\end{algorithmic}
\end{algorithm}
\cref{algl:y} in \cref{ALG_baseline} is \dots
\cref{algl:y,algl:sum} of the algorithm are based on \dots
\end{document}