[Tex/LaTex] control vertical space before and after verbatim environment

spacingverbatim

How do I control how much vertical space appears before and after a verbatim environment?

With the following source (run through pdflatex):

\documentclass[varwidth]{standalone}
\begin{document}
text before verbatim
\begin{verbatim}
some verbatim text
\end{verbatim}
text after verbatim
\end{document}

I get the following:

bad behavior

I would like to be able to tweak things to get the following behavior:

good behavior

Edit:

I would also like the solution to work for verbatim environments in a list item:

\documentclass[varwidth]{standalone}
\begin{document}
\begin{itemize}
\item text before verbatim
\begin{verbatim}
some verbatim text
\end{verbatim}
text after verbatim
\end{itemize}
\end{document}

bad behavior in a list

Best Answer

verbatim uses trivlist which adds above and below it the current values of \topsep and \partopsep (the latter if at the beginning of a paragraph); since the trivlist is started when a group has already been opened by verbatim, it's safe to set locally the values: the command to patch is \@verbatim, that starts with \trivlist, so we can set the parameters just before this command:

\usepackage{etoolbox}
\makeatletter
\preto{\@verbatim}{\topsep=0pt \partopsep=0pt }
\makeatother

Here's an example, where I put two minipage environments next to each other just to show the line spacing:

\documentclass{standalone}
\usepackage{etoolbox}
\makeatletter
\preto{\@verbatim}{\topsep=0pt \partopsep=0pt }
\makeatother
\begin{document}
\begin{minipage}{5cm}
text before verbatim
\begin{verbatim}
some verbatim text
\end{verbatim}
text after verbatim
\end{minipage}%
\begin{minipage}{5cm}
abc\\
def\\
ghi
\end{minipage}
\end{document}

enter image description here