Consider the lstlisting in this MWE. (I have added normal text and itemize environment blocks for comparison.)


%\topsep 0pt
%\parsep 0pt
%\itemsep 0pt
%\partopsep 0pt
\lstset{aboveskip=0pt, belowskip=0pt}
%       \vspace{-0.85ex}
some text
some more text

        some text\\
        some more text

            \item some text
            \item some more text

The listing comes with supplementary vertical spacing above and below, compared to the other two blocks. I tried setting various lengths (see code commented out), but this had no visible effect.

How can I suppress this vertical spacing, without using vspace, if reasonably easy? If not easy, I’d prefer using a vspace than use complicated and fragile code to modify the inner workings of lstlisting, but is it then at least possible to use a symbolic name for the space to be suppressed instead of a constant that has to be manually adjusted by trial-and-error (e.g., \vspace{-\thenameofsomelength} rather than \vspace{-0.85ex})?

Related (but different): spacing within block and between blocks with list in beamer; How to modify itemize vertical spacing within blocks in beamer?; Why such spurious vertical space before listings? (related to tikz overlays); Spacing inside listings in beamer; Extra vertical glue in listings within beamer frame (closest to my question, but talks about glue, I’m not sure this space really is glue, and the answer only refers to aboveskip and belowskip, which I used).

  • I think the cause is, lstlisting adds \strut to every line of its output (so they share the same height with normal input). You can test with \begin{block}{Block} \strut some text\\ \strut some more text \end{block}. Commented Nov 14, 2021 at 15:45
  • @muzimuzhiZ interesting! And do you know how I can remove exactly the space added by this \strut? Commented Nov 14, 2021 at 21:02
  • I don't think it's a good practice but you can try \begin{lstlisting}[basicstyle=\ttfamily\setbox\strutbox\hbox{}] (since \strut simply uses box \strutbox). Here \ttfamily is optional. Commented Nov 14, 2021 at 21:45


You must log in to answer this question.

Browse other questions tagged .