如何防止列表标题和代码之间出现分页符?

如何防止列表标题和代码之间出现分页符?

如何防止列表标题和代码之间出现分页符(见图)?

截屏

说明问题的最小示例:

\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}[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}

\end{document}

只是为了澄清:我不想禁用突发列表。

答案1

就您而言,您只需将选项添加float到第二个列表的调用中即可。然后列表可以浮动在页面上。就您而言,完整的第二个列表将移至第二页。

MWE(参见标有 的更改行<=======):

\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}

结果如下:

mwe 的结果

相关内容