[Tex/LaTex] Create a smart cross-reference to a line in an ‘algorithmic’ environment using \autoref

algorithmicxalgorithmsautorefcross-referencing

To set the name of the \autoref command for an algorithm I use:

\newcommand{\algorithmautorefname}{Algorithm}

like commented here. I would also like to be able to refer to lines within an algorithmic environment with line x.

\begin{algorithm}
\label{alg:myalg}
\begin{algorithmic}[1]
  \State Do X 
  \State Do Y \label{algl:y}
  \State $x = y + z$
\end{algorithmic}
\end{algorithm}

\autoref{alg:myalg} gives me correctly Algorithm 1. In addition, I would also like to have \autoref{algl:y} generate line 2. Until now I'm using: line~\ref{algl:y}.

Seeing the same answer you can define the autoref names by: \....autorefname.
But then he mentions that some counters are hidden, for example the line numbering: \c@ALG@line. Is it possible to create an autoref name for them?

I have tried:

\newcommand{\ALGlineautorefname}{line}
\newcommand{\ALG_lineautorefname}{line}
\newcommand{\ALG@lineautorefname}{line}

but none work and only the first compiles.

If possible, how can I create an \autorefname for a line in an algorithmic environment.

Best Answer

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:

enter image description here

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