I want to label and reference the modified listing environments namely Matlab Code and Matlab Output. However, when I add the \label
command and try to reference the labelled modified listing environments, I get ??
which is something I do not desire. Below is my MWE which is a solution to my problem by @Tom found at Incorrect classification of multiple listings entries:
\documentclass[openany]{book}
\usepackage{regexpatch}
\usepackage[nottoc]{tocbibind}
\usepackage{caption}
\usepackage{listings}
\usepackage{hyperref}
% --------------------------------------- C++
\newcommand{\lstlistmatlaboutputname}{List of Matlab Output}
\newcommand{\lstlistofmatlaboutput}{\begingroup
\tocfile{\lstlistmatlaboutputname}{loc}
\endgroup}
% --------------------------------------- R
\newcommand{\lstlistmatlabcodename}{List of Matlab Code}
\newcommand{\lstlistofmatlabcode}{\begingroup
\tocfile{\lstlistmatlabcodename}{lor}
\endgroup}
% --------------------------------------- Pseudocode
\newcommand{\lstlistpseudocodename}{List of Pseudocode}
\newcommand{\lstlistofpseudocode}{\begingroup
\tocfile{\lstlistpseudocodename}{lop}
\endgroup}
\makeatletter
\lstnewenvironment{matlaboutput}[1][]{%
\renewcommand{\lstlistingname}{Matlab Output}%
\renewcommand{\ext@lstlisting}{loc}%
%\xpatchcmd*{\caption@ORI@lst@MakeCaption}{lol}{loc}{}{}% use this with earlier version caption package
\lstset{language=C++,#1}}%
{}
\lstnewenvironment{matlabcode}[1][]{%
\renewcommand{\lstlistingname}{Matlab Code}%
\renewcommand{\ext@lstlisting}{lor}%
%\xpatchcmd*{\caption@ORI@lst@MakeCaption}{lol}{lor}{}{}% use this with earlier version caption package
\lstset{language=R,#1}}
{}
\lstnewenvironment{pseudocode}[1][]{%
\renewcommand{\lstlistingname}{Pseudocode}%
\renewcommand{\ext@lstlisting}{lop}%
%\xpatchcmd*{\caption@ORI@lst@MakeCaption}{lol}{lop}{}{}% use this with earlier version caption package
\lstset{basicstyle=\ttfamily,#1}}%
{}
\makeatother
\begin{document}
\lstlistofmatlaboutput
\lstlistofmatlabcode
\lstlistofpseudocode
\chapter{Listings}
\begin{matlaboutput}[caption = {Some class definition}]\label{outp:1}
% example matlab output
\end{matlaboutput}
\begin{matlabcode}[caption = {For educational purposes}]\label{code:1}
% example matlab code 1
\end{matlabcode}
See Output \ref{outp:1} and Code \ref{code:1} above.
\end{document}