I tried using the built in lstlisting float type (\@float{lstlisting}[#1]
) but could not get it to work with subcaptions. Specifically, every lstlisting
increments the lstlisting counter, reseting the subcounter. So instead I created a separate float type for listing
.
Note that this causes \lstlistoflistings
to stop working.
\documentclass{article}
\usepackage{listings}
\usepackage{newfloat}
\usepackage{subcaption}
\DeclareFloatingEnvironment[fileext=lst, listname={List of Listings}]{listing}
\DeclareCaptionSubType{listing}
\begin{document}
\listoflistings
\begin{listing}[h]
\caption{Test}
\begin{sublisting}{\dimexpr 0.5\textwidth-0.5\columnsep}
\begin{lstlisting}
left listing
\end{lstlisting}
\caption{}
\end{sublisting}\hfill
\begin{sublisting}{\dimexpr 0.5\textwidth-0.5\columnsep}
\begin{lstlisting}
right listing
\end{lstlisting}
\caption{}
\end{sublisting}
\end{listing}
\end{document}
Of course, if you don't want subcaptions, the original solution works fine.
\documentclass{article}
\usepackage{listings}
\makeatletter
\newenvironment{listing}[1][htp]{\@float{lstlisting}[#1]}{\end@float}
\newenvironment{listing*}[1][tp]{\@dblfloat{lstlisting}[#1]}{\end@dblfloat}
\makeatother
\begin{document}
\lstlistoflistings
\begin{listing}
\begin{minipage}{\dimexpr 0.5\textwidth-0.5\columnsep}
\begin{lstlisting}[caption=Test A]
left listing
\end{lstlisting}
\end{minipage}\hfill
\begin{minipage}{\dimexpr 0.5\textwidth-0.5\columnsep}
\begin{lstlisting}[caption=Test B]
right listing
\end{lstlisting}
\end{minipage}
\end{listing}
\end{document}