Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Latex: How to make listings subfloats use listing counters, TOC, etc

I have a macro that do side-by-side figures, below. It uses subfloats, and so it goes in a figure.

\newcommand{\listbylist}[6][showlines=true]{
   \begin{figure}
      \subfloat[ ]{
        \lstinputlisting[showlines=true,#1]{#2}                                                  
     \label{#4:A}
  }
  \hfill{}
  \subfloat[ ]{                                                                               
     % by setting the frame to leftline, we avoid a box into oblivion                         
     % turn off numbers                                                                       
     \lstinputlisting[showlines=true,frame=leftline,#1,numbers=none]{#3}                      
     \label{#4:B}                                                                             
  }                                                                                           
  \hfill{}
   \caption[#5]{#6}
       \label{#4}                                                                                         
   \end{figure}
}

Unfortunately, this uses the Figure counters, not the Listings ones. It also shows up in the wrong table of contents, and uses the word "Figure" instead of "Listings" in the caption, references to it, etc. Is there a way to rectify this?

I would prefer a simple way, like adding the word "Listing" somewhere...

like image 245
Paul Biggar Avatar asked Nov 06 '22 19:11

Paul Biggar


1 Answers

Instead of using the built-in float of lstlistings, wrap them in a custom float:

\begin{mylisting}
\begin{lstlisting}
int x = 1;
\end{lstlisting}
\end{mylisting}

Then use the same float (mylisting) for the subfloat usage:

\newcommand{\listbylist}[6][showlines=true]{
  \begin{mylisting}
    \subfloat[ ]{
      ...
    }
    \hfill{}
    \subfloat[ ]{
      ...
    }
    \hfill{}
    \caption[#5]{#6}
    \label{#4}
  \end{mylisting}
}

This needs to all be set up in the preamble:

\newfloat{mylisting}{tbphH}{lopbl}[chapter]
\floatname{mylisting}{Listing}
\newsubfloat{mylisting}
\newcommand{\listofmylistings}{\listof{mylisting}{List of Listings}}
% if you use the hyperref package
\providecommand*\theHmylisting{\themylisting}
like image 59
Paul Biggar Avatar answered Nov 15 '22 08:11

Paul Biggar