Avoid Page Breaks In \lstlistings
Answer :
Wrapping the lstlisting
inside a minipage
(of width \linewidth
) boxes the content making it unbreakable and avoids breaking across the page boundary:
... \begin{minipage}{\linewidth} \begin{lstlisting} static boolean abcde ( abc_defg_hijk * const lm ); \end{lstlisting} \end{minipage} ...
Depending on the location of usage, you may have to prepend the environment with \noindent
to avoid any paragraph indentation.
A somewhat similar approach is followed if you load the float
package and use
... \begin{lstlisting}[float,floatplacement=H] static boolean abcde ( abc_defg_hijk * const lm ); \end{lstlisting} ...
More on the float placement H
is discussed in How to influence the position of float environments like figure and table in LaTeX?
I'm using version 1.5 (2013) of the listings
package. I use lstinputlisting
to include the code from the file, and I just put float
inside the options of the environment. It works fine.
For example, this goes in my preamble:
\lstdefinestyle{freefempp}{ language=C++, basicstyle=\footnotesize\ttfamily, commentstyle=\itshape\color{violet}, identifierstyle=\color{blue}, morekeywords={ border, buildmesh, cos, dx, dy, fespace, fill, func, int2d, label, mesh, on, pi, plot, problem, sin, real, x, y}, % float, frame=single, numbers=left } \lstset{style=freefempp}
And this goes in my document's body.
\lstinputlisting [caption=Solution to question 1, float, linerange={1-21}, firstnumber=1] {listings/ex1-1.edp}
However, the float option only works inside the lstinputlisting
environment definition, not inside the style definition. Maybe this bug will be corrected in future versions.
I use a similar solution to the one proposed by werner. However I prefer to define the minipage with text instead of line width:
\begin{minipage}[c]{0.95\textwidth} \begin{lstlisting} \end{lstlisting} \end{minipage}
"c" for centering and "0.95\textwidth" to make the listing a little bit smaller than the rest of the text.
Comments
Post a Comment