# referencing listing with custom caption using autoref

I'm trying to use the listings package to show some pseudocode. For that I want to add some keywords and a special environment which is used for all pseudocode listings. Additionally the referencing label should state "algorithm X.Y" instead of "listing X.Y". While the caption itself is correcty, the references using \autoref{...} still display "listings X.Y".

Here is small example of the issue:

\documentclass[10pt,a4paper]{book}
\usepackage[utf8]{inputenc}
\usepackage{hyperref}
\usepackage{listings}
\usepackage{caption}

\DeclareCaptionLabelFormat{algocaption}{Algorithm \thenalg}
\newcounter{nalg}[chapter]
\renewcommand{\thenalg}{\thechapter .\arabic{nalg}}
\lstnewenvironment{algorithm}[1][]
{
\refstepcounter{nalg}
\captionsetup{labelformat=algocaption,labelsep=colon}
\lstset{
frame=tblr,
numbers=left,
keywords={
,input
,output
,if
,else
,for
,foreach
,while
,end
},
numbers=left,
xleftmargin=.04\textwidth,
#1
}
}
{}

\begin{document}
\chapter{test}
\begin{algorithm}[caption={Integer division.}, label={alg:test}]
input: test
\end{algorithm}
\autoref{alg:test}
\end{document}

• Welcome to TeX.SX! There are some algorithm packages already, no need to use listings for this – user31729 Jul 9 '15 at 7:37

The \autoref command tries to detect the underlying counter for the reference, this is lstlisting in this case and looks for a corresponding \lstlistingautorefname, which is not defined so far. This has to be provided then.

The unfortunate feature for this that each lstlisting environment still has the same counter. And other non-algorithm environments from listings will now provide the wrong autoref - name.

\documentclass[10pt,a4paper]{book}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\usepackage{caption}

\DeclareCaptionLabelFormat{algocaption}{Algorithm \thenalg}

\newcounter{nalg}[chapter]
\renewcommand{\thenalg}{\thechapter.\arabic{nalg}}
\lstnewenvironment{algorithm}[1][]
{
\refstepcounter{nalg}%
\captionsetup{labelformat=algocaption,labelsep=colon}
\lstset{
frame=tblr,
numbers=left,
keywords={
,input
,output
,if
,else
,for
,foreach
,while
,end
},
numbers=left,
xleftmargin=.04\textwidth,
#1
}
}
{}

\usepackage{hyperref}

\AtBeginDocument{%
\providecommand*{\lstlistingautorefname}{Algorithm}
}

\begin{document}
\chapter{test}
\begin{algorithm}[caption={Integer division.}, label={alg:test}]
input: test
\end{algorithm}
\autoref{alg:test}
\end{document}