[Tex/LaTex] How to make figure and listing share their counter

countersfloatslistingsnumbering

I'm using the "listings" package to write pieces of code (XML, RDF, Java, etc) and I want them to have the same counter of the Figure environment.

For example,

Listing 1: blablabla
Listing 2: blebleble
Figure 3: bliblibli
Listing 4: blobloblo
Figure 5: blublublu

The purpose of doing it is to change the "Listing" label to "Figure". But I need both environments to share the same counter. How I do it?

Thanks in advance.

Best Answer

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}

enter image description here

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}