Graphics, Figures & TablesGet equal above/belowskip regardless of float for lstlisting

Information and discussion about graphics, figures & tables in LaTeX documents.
Post Reply
pauljlucas
Posts: 1
Joined: Wed Oct 23, 2024 4:18 pm

Get equal above/belowskip regardless of float for lstlisting

Post by pauljlucas »

When using the listings package, for some listings I do not want to use float, i.e., I want the listing "inline." The minimal example below shows such a listing. The first lstlisting does not use float and the spacing above/below it is correct, i.e., a blank line.

For longer listings, however, I do want to use float. The second lstlisting does use float, but the spacing above/below it is incorrect — specifically, it's too big as if it were two blank lines.

(The length of the second listing is short since that's all that's necessary to illustrate the problem.)

I want the spacing above/below listings with float to be the same as those without. How can I get what I want?

Code: Select all

\documentclass[10pt]{book}
\usepackage{courier}
\usepackage[T1]{fontenc}
\usepackage[flushmargin, hang, perpage, symbol*]{footmisc}
\usepackage{geometry}
\geometry{letterpaper}
\usepackage{lipsum}

\usepackage{listings}
\lstset{
  language=C,
  abovecaptionskip=\baselineskip,
  aboveskip=\baselineskip,
  belowcaptionskip=0pt,
  belowskip=\baselineskip,
  basicstyle=\small\ttfamily,
  breakatwhitespace=true,
  breaklines=true,
  captionpos=b,
  floatplacement=hbt!,
  keepspaces=true,
  keywordstyle=\lst@ifdisplaystyle\bfseries\fi\normalsize,
  showspaces=false,
  showstringspaces=false,
  showtabs=false,
  tabsize=2,
  xleftmargin=.4in
}

\begin{document}
\mainmatter
\chapter{Chapter}

\lipsum[2]

\begin{lstlisting}
#include <stdio.h>

int main() {
  printf( "This has the correct amount of space above/below it.\n" );
}
\end{lstlisting}

\lipsum[3]

\begin{lstlisting}[float]
#include <stdio.h>

int main() {
  printf( "This with float has too much space above/below it.\n" );
}
\end{lstlisting}

\lipsum[4]
\end{document}

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org
TikZ book
Post Reply