I would to include my listings as floats, pretty much as Figures, but I don't want to call them Figures. I want to call them listings. How can I do that?
[Tex/LaTex] How to make a float that is not labelled ‘Figure’ but ‘Listing’
floatslistingsnaming
Related Solutions
I think it's appropriate to use a little trick here: don't set the caption in the lstlisting
environment, but enclose the listing in figure
and use \caption
:
\documentclass{article}
\usepackage{listings}
\begin{document}
\listoffigures
\begin{figure}
\caption{Hello World}
\begin{lstlisting}[gobble=2]
print "Hello World!"
\end{lstlisting}
\end{figure}
\end{document}
This way you can mix real figures and listings while keeping consistent figure numbering.
You can make things so the figure
environment shares the counter with lstlisting
. However, you should ensure that lstlisting
environments are floating too, otherwise the numbers could not agree and a figure could appear before a listing with a lower number.
\documentclass{article}
\usepackage{listings}
\makeatletter
\AtBeginDocument{%
\let\c@figure\c@lstlisting
\let\thefigure\thelstlisting
\let\ftype@lstlisting\ftype@figure % give the floats the same precedence
}
\makeatother
\begin{document}
\begin{lstlisting}[caption=A listing,float]
a=1
\end{lstlisting}
\begin{lstlisting}[caption=Another,float]
b=2
\end{lstlisting}
\begin{figure}
F
\caption{A figure}
\end{figure}
\begin{lstlisting}[caption=Again,float]
c=3
\end{lstlisting}
\end{document}
Thanks to David Carlisle for noting the need for adjusting \ftype@lstlisting
.
If you also want that table
shares the counter, add similar instructions.
\documentclass{article}
\usepackage{listings}
\makeatletter
\AtBeginDocument{%
\let\c@figure\c@lstlisting
\let\thefigure\thelstlisting
\let\c@table\c@lstlisting
\let\thetable\thelstlisting
\let\ftype@lstlisting\ftype@figure % give the floats the same precedence
\let\ftype@table\ftype@figure % give the floats the same precedence
}
\makeatother
\begin{document}
\begin{lstlisting}[caption=A listing,float]
a=1
\end{lstlisting}
\begin{lstlisting}[caption=Another,float]
b=2
\end{lstlisting}
\begin{figure}
F
\caption{A figure}
\end{figure}
\begin{table}
G
\caption{A table}
\end{table}
\begin{lstlisting}[caption=Again,float]
c=3
\end{lstlisting}
\end{document}
Best Answer
There are two packages that let you format your listings and are able to let them float.
Here are two simple examples.
The respective manuals have more details about customization of your listings.