101

I'm trying to avoid page breaks in my lstlisting (seen in section 0.0.2) I know I can remedy this by floating my lstlisting, but it adds some unwanted white space (seen in section 0.0.1).

float

Is there an alternative to float so that my lstlisting will not break across pages?

OR

Can I configure float to eliminate the white space so it looks identical to how it is when not in a float

no float

*I apologize for the cruft in my MWE. I'm just trying to use this in a much larger document, so I'd rather keep it as close to it as possible.

\documentclass{article}

% New commands
\newcommand{\HRule}{\rule{\linewidth}{0.5mm}}
\newcommand{\superscript}[1]{\ensuremath{^{\textrm{#1}}}}

% Modified commands
\renewcommand*\abstractname{Revision History}

%%%%% Packages and configuration %%%%%
\usepackage[firstpage]{draftwatermark}
\SetWatermarkText{\textsc{Confidential}}
\SetWatermarkScale{4}
\SetWatermarkColor[gray]{0.9}

%\usepackage{fancyhdr}
%\pagestyle{fancy}
%\fancyhf{} % clear all fields
%\fancyfoot[LE,CO]{\thepage}           % page number in "outer" position of footer line
%\fancyfoot[RE,LO]{Message of the day} % other info in "inner" position of footer line

\usepackage{tabularx}

\usepackage[table]{xcolor}
\definecolor{dark-red}{rgb}{0.4,0.15,0.15}
\definecolor{dark-blue}{rgb}{0.15,0.15,0.4}
\definecolor{medium-blue}{rgb}{0,0,0.5}
\definecolor{light-grey}{gray}{0.8}

\usepackage[hidelinks]{hyperref}% keep at end
\hypersetup{
    colorlinks,
    linkcolor={black},
    citecolor={dark-blue}, 
    urlcolor={medium-blue}
}

%\usepackage[cm]{fullpage}
%\usepackage[letterpaper, top=0.7in, bottom=0.9in, left=0.7in, right=0.7in, showframe]{geometry}
\usepackage[margin=0.5in]{geometry}


%\usepackage{color}
\usepackage{listings}
\lstset{ %
language=C,                % choose the language of the code
basicstyle=\footnotesize,       % the size of the fonts that are used for the code
%numbers=left,                   % where to put the line-numbers
%numberstyle=\footnotesize,      % the size of the fonts that are used for the line-numbers
%stepnumber=1,                   % the step between two line-numbers. If it is 1 each line will be numbered
%numbersep=5pt,                  % how far the line-numbers are from the code
%backgroundcolor=\color{white},  % choose the background color. You must add \usepackage{color}
showspaces=false,               % show spaces adding particular underscores
showstringspaces=false,         % underline spaces within strings
showtabs=false,                 % show tabs within strings adding particular underscores
%frame=single,           % adds a frame around the code
tabsize=4,          % sets default tabsize to 4 spaces
captionpos=b,           % sets the caption-position to bottom
breaklines=true,        % sets automatic line breaking
breakatwhitespace=false,    % sets if automatic breaks should only happen at whitespace
%escapeinside={\%*}{*)}          % if you want to add a comment within your code
}

\usepackage{mdwlist}
\usepackage{underscore}
\usepackage{tikz}
\usepackage{float}
\usepackage{lipsum}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\usepackage{etex}
\usepackage{etoolbox}
\makeatletter
\patchcmd{\@afterheading}%
    {\clubpenalty \@M}{\clubpenalties 2 \@M \@M }{}{}
\patchcmd{\@afterheading}%
    {\clubpenalty \@clubpenalty}{\clubpenalties 1 \@clubpenalty }{}{}
\makeatother
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

\lipsum[1-8]

\subsubsection{Lorem Ipsum Dolomite}\leavevmode
\begin{lstlisting}
void abc_defgh_ijklmn_stuff * const ( void );
\end{lstlisting}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc id sapien eget magna tempus ornare vitae ut dolor. Donec pharetra diam vitae erat sollicitudin a blandit sapien blandit. Nam ligula metus, imperdiet ut accumsan non, tincidunt id a.

\subsubsection{abcde}
\begin{lstlisting}
static boolean abcde
(
abc_defg_hijk * const   lm
);
\end{lstlisting}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc id sapien eget magna tempus ornare vitae ut dolor. Donec pharetra diam vitae erat sollicitudin a blandit sapien blandit. Nam ligula metus, imperdiet ut accumsan non, tincidunt id a.\\

\end{document}
2
  • 9
    90% are 4-5 line function declarations and I have a portion of them breaking across pages. As my MWE is derived from some documentation that I'm writing, I'd like to avoid moving a bunch of \newpage around every time I update it. Commented Sep 19, 2012 at 17:55
  • 2
    possible duplicate of How can I ensure that a listing is not going to be split? Commented Jan 8, 2013 at 21:57

3 Answers 3

141

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?

6
  • 1
    Just a small remark, shouldn't we use also \begin{center}. Otherwise I get my text and my listing intertwined. Commented Jan 19, 2017 at 17:25
  • 1
    @AlexanderCska: Not really.
    – Werner
    Commented Jan 19, 2017 at 18:33
  • 7
    According to the current docs of the listing package its: \begin{lstlisting}[float=H] Commented Feb 10, 2018 at 21:53
  • 1
    @Winter: Yes. You can define your own/custom listing environment using \lstnewenvironment. See How can I define a custom listing environment?
    – Werner
    Commented Feb 6, 2019 at 21:02
  • 1
    You probably want to use \noindent before your minipage.
    – Bex
    Commented May 16, 2020 at 9:38
18

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.

1
  • +1 This is the solution that worked for me. With this, I don't have to deal with extra indentation that comes with minipage.
    – akalanka
    Commented Dec 1, 2023 at 18:13
6

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.

2
  • 2
    Why do you prefer \textwidth when \linewidth adjusts with you margins? For example, when you set an lstlisting inside a list. Also, why not a full \textwidth?
    – Werner
    Commented Aug 13, 2014 at 4:42
  • 4
    I work with two-column styles most of the time. In such styles, \textwidth is typically the better choice as listings rarely fit into a single column. However, in one-column styles it makes no difference. So \textwidth is valid for both of these styles.
    – Benjamin
    Commented Aug 14, 2014 at 15:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .