# Is it a listings package bug?

I use listings package (the newest version 1.8b), but in the following case it doesn't work correctly:

\documentclass{article}
\usepackage{listings}
\begin{document}

\section{Title}
\begin{lstlisting}
lstlisting content
\end{lstlisting}
text

\section{Title}
text
\begin{lstlisting}
lstlisting content
\end{lstlisting}
text

\section{Title}
text
\end{document}


There wasn't this problem in the previously versions. Is this a bug?

Yes, it's a bug and a very old one.

The lstlisting environment does, at the end, \let\if@nobreak\iffalse, which is wrong because it's a local assignment, whereas the kernel command \@nobreakfalse does the job globally.

\documentclass{article}
\usepackage{listings}

\makeatletter
\let\lstlisting\relax
\let\lstlisting@\relax
\lstnewenvironment{lstlisting}[2][]{%
\lst@TestEOLChar{#2}%
\lstset{#1}%
\csname\@lst @SetFirstNumber\endcsname
}{%
\@nobreakfalse
\csname\@lst @SaveFirstNumber\endcsname
}
\makeatother

\begin{document}

\section{Title}
\begin{lstlisting}
lstlisting content
\end{lstlisting}
text

\section{Title}
text
\begin{lstlisting}
lstlisting content
\end{lstlisting}
text

\section{Title}
text
\end{document}


This seems to be related to the way listings places its output if it is the first box after a section title (I didn't really investigate). You can work around this by placing a \leavevmode after \section and before \begin{lstlisting}:

\documentclass{article}
\usepackage{listings}
\begin{document}

\section{Title}
\leavevmode
\begin{lstlisting}
lstlisting content
\end{lstlisting}
text

\section{Title}
text
\begin{lstlisting}
lstlisting content
\end{lstlisting}
text

\section{Title}
text
\end{document}


• Thank you your answer. The maintainer of listings package removed the \leavevmode command in the definition of lstlisting environment. But I don't understand why. May 4, 2019 at 9:50
• @hair-splitter most likely to enable more possibilities for the placement, increasing versatility. Did you check whether that is the change causing this? Because I didn't. May 4, 2019 at 9:52
• I'm not sure. But it works correctly with \leavevmode. May 4, 2019 at 10:01