In my document I want several different custom listing environments. The solution from fraktalek works like a charm, except for one thing: \autoref
doesn't work for me. I have tried the following:
\newcounter{algorithm}
\lstnewenvironment{algorithm}[1][]{
\renewcommand\lstlistingname{Algorithm}
\setcounter{lstlisting}{\value{algorithm}}
\lstset{#1}
} {\addtocounter{algorithm}{1}}
\newcounter{program}
\lstnewenvironment{program}[1][]{
\renewcommand\lstlistingname{Program}
\setcounter{lstlisting}{\value{program}}
\lstset{#1}
} {\addtocounter{program}{1}}
\def\algorithmautorefname{Algorithm}
\def\programautorefname{Program}
But, in my document,
\autoref{alg:firstalgorithm}, \autoref{prg:firstprogram}, \autoref{alg:secondalgorithm}
returns
Listing 1.1, Listing 1.1, Listing 1.2.
The separate numbering is correct, but autoref does not recognize the separate counters. However, if I use
\def\lstlistingautorefname{Code fragment}
instead, the result changes to
Code fragment 1.1, Code fragment 1.1, Code fragment 1.2.
I have tried putting this command inside the \lstnewenvirontment
commands, but this again gave
Listing 1.1, Listing 1.1, Listing 1.2
as a result. Obviously, I would like to result to be
Algorithm 1.1, Program 1.1, Algorithm 1.2.
Any thoughts on how to achieve this?
Best Answer
The solution I'm proposing here is adequate for relatively small documents, but will not work for more complex documents where the user wants to produce something like a
\listofalgorithms
or\listofprograms
. Since this was not specified in the original question, it is not included here. However, I'm sure it is easy to extend it to include such requirements using thefloat
package, for example.One proposed solution would be to add some macros that both prints a correct caption (albeit manually) and correctly hyperlinks to the respective
lstlisting
. This is done by introducing a "pre-hook" to each new\lstnewenvironment
and modifying the way in which parameters are passed to it. Caption and label support vialistings
'caption={...}
andlabel=...
is dropped in lieu of a manual alternative. This waylstlisting
environments are always using a incrementally different counter in the background, thereby avoiding thehyperref
duplicate destination warning.The macro
\listingcaption{<caption label>}{<caption>}
, which provides the manual caption support, takes 2 mandatory arguments.<caption label>
is the type of label (Algorithm or Program in this case) and<caption>
is the actual caption. The formatting of the caption is similar to the specificationsupported by the
caption
package. The optionjustification=centerlast
was obtained from this recent blog entry, originally suggested by Victor Eijkhout's TeX by Topic.When using the
float
package for managing captions, counters and\listof...
entries, it is advisable to also forego using thelistings
options forcaption={...}
andlabel=...
.