5

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}

enter image description here

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

2 Answers 2

9

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}

enter image description here

4

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}

enter image description here

3
  • 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.
    – Skillmon
    May 4, 2019 at 9:52
  • I'm not sure. But it works correctly with \leavevmode. May 4, 2019 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.