I have created a macro \piece to structure longer sections into smaller, numbered pieces. (I am using the macro in a set of lecture notes where I try to introduce one concept per piece.) The code, which I have basically stolen from \@startsection, has been working fine so far, but now I am experiencing problems with it in connection with the listings package. When I start a \piece immediately after an lstlisting, there is too much vertical space between the listing and the new piece.
Similar issues with vertical space after an lstlisting have been discussed before, but I was not able to derive the answer to my question from the answers:
- avoid empty vert space after lstlisting
- vertical extra space below lstlisting environment inside a list environment
How can I make the code for \piece more robust so that this problem disappears?
Here is a minimal working example that illustrates the problem:
\documentclass{minimal}
\usepackage{listings}
\makeatletter
\newcounter{piece}
\def\thepiece{\arabic{piece}}
\newcommand*{\piece}{%
\if@noskipsec \leavevmode \fi
\par
\@afterindentfalse
\if@nobreak
\everypar{}%
\else
\addvspace\belowdisplayskip
\fi
\refstepcounter{piece}%
\@afterheading
\makebox[0pt][r]{\thepiece\quad}%
}
\makeatother
\begin{document}
\piece Piece 1
\piece Piece 2
\begin{lstlisting}
Listing
\end{lstlisting}
\piece Piece 3
\end{document}
Output of the minimal example:

\sectionor\subsectionisn't better suited for this 'splitting'? And please have a look on Why should the minimal class be avoided – Jan 16 '16 at 10:01\pieceand the sectioning commands are similar; that's why I stole the code for\piecefrom there :). A crucial difference is that there is no title. But perhaps there already is a similar command in some package? – Marco Kuhlmann Jan 16 '16 at 10:29\leavevmodetypo; that was helpful! – Marco Kuhlmann Jan 16 '16 at 12:44\begin{lstlising}[belowskip=-0.8 \baselineskip] …or with\lstset{belowskip=-0.8 \baselineskip}– white_gecko Jul 23 '20 at 11:44