[Tex/LaTex] How to prevent page break between listing caption and code

listingspage-breaking

How to prevent page break between listing caption and code (see the picture)?

screenshot

Minimal example illustrating issue:

\documentclass[a4paper, 12pt, oneside]{report}

\usepackage[a4paper, left=3.5cm, right=2cm, bottom=2.5cm, top=3cm]{geometry}

\usepackage{hyperref}
\usepackage{listings}
\usepackage{caption}

\lstset{
    frame=top,
    stepnumber=1,
    numbersep=10pt,
    tabsize=4,
    extendedchars=true,
    breaklines=true,
    captionpos=t,
    mathescape=true,
    showspaces=false,
    showtabs=false,
    xleftmargin=17pt,
    framexleftmargin=17pt,
    framexrightmargin=0pt,
    framexbottommargin=5pt,
    framextopmargin=5pt,
    showstringspaces=false,
    upquote=true
}

\DeclareCaptionFormat{listing}{\textbf{#1#2}#3}
\captionsetup[lstlisting]{format=listing,singlelinecheck=false, margin=0pt, font={sf},labelsep=space,labelfont=bf}

\renewcommand\lstlistingname{Listing}

\fontsize{10}{12pt}

\begin{document}

\chapter{XXX}

X \\
X \\
X \\

\section{XXX}

\begin{lstlisting}
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
\end{lstlisting}

\begin{lstlisting}
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
\end{lstlisting}

\end{document}

Just for clarification: I don't want to disable breaking listings.

Best Answer

In your case you can just add option float to the call of the second listing. Then the listing can float over pages. In your case the complete second listing is moved to page two.

MWE (see changed line marked with <=======):

\documentclass[a4paper, 12pt, oneside]{report}

\usepackage[a4paper, left=3.5cm, right=2cm, bottom=2.5cm, top=3cm]{geometry}

\usepackage{hyperref}
\usepackage{listings}
\usepackage{caption}

\lstset{
    frame=top,
    stepnumber=1,
    numbersep=10pt,
    tabsize=4,
    extendedchars=true,
    breaklines=true,
    captionpos=t,
    mathescape=true,
    showspaces=false,
    showtabs=false,
    xleftmargin=17pt,
    framexleftmargin=17pt,
    framexrightmargin=0pt,
    framexbottommargin=5pt,
    framextopmargin=5pt,
    showstringspaces=false,
    upquote=true
}

\DeclareCaptionFormat{listing}{\textbf{#1#2}#3}
\captionsetup[lstlisting]{format=listing,singlelinecheck=false, margin=0pt, font={sf},labelsep=space,labelfont=bf}

\renewcommand\lstlistingname{Listing}

\fontsize{10}{12pt}

\begin{document}

\chapter{XXX}

X \\
X \\
X \\

\section{XXX}

\begin{lstlisting}[caption=xxx]
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
\end{lstlisting}

\begin{lstlisting}[float,caption=xxx] % <=================== added float
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
x
\end{lstlisting}

\end{document}

with the result:

result of mwe