# Suppressing vertical space between environments

I specified two environment in a LaTeX document to highlight different lines of codes:

\newenvironment{code}{\color{blue}}{\ttfamily}{\par}
\newenvironment{codegrey}{\color{grey}}{\ttfamily}{\par}


In the document, I want the latter one appear right below the first one without any spacing. Here are the codes:

\begin{code}
\begin{verbatim}
\renewcommand{\arraystretch}{1.5}
\end{verbatim}
\end{code}
\begin{codegrey}
\begin{verbatim}
\begin{tabular}{|c|p{3cm}llcp{5cm}|}
\end{verbatim}
\end{codegrey}


My goal is to display them as: Instead of this: Any suggestions are appreciated! This is my first time using newenvironment command and I find it really powerful.

• I think the problem is from the verticle space caused by using the verbatim environment, not using \newenvironment itself. Any solution to this? – carl-pch Sep 7 '15 at 5:13
• How about an alternative suggestion? – Werner Sep 7 '15 at 5:21

## 3 Answers

Here is a shorter version using fancyvrb. You need not use separate environments for changing colours here.

\documentclass{article}
\usepackage{xcolor}
\usepackage{fancyvrb}

\begin{document}
\begin{Verbatim}[commandchars=+,fontsize=\footnotesize]
+color[blue]\renewcommand{\arraystretch}{1.5}
+color[gray]\begin{tabular}{|c|p{3cm}llcp{5cm}|}
\end{Verbatim}
\end{document}


You can also use listings package which offers escapechar key to enable the latex commands inside the verbatim atmosphere.

You could add a \vspace with negative value in between like so:

\begin{code}
\begin{verbatim}
\renewcommand{\arraystretch}{1.5}
\end{verbatim}
\end{code}

\vspace{-3mm} %negative \vspace
\begin{codegrey}
\begin{verbatim}
\begin{tabular}{|c|p{3cm}llcp{5cm}|}
\end{verbatim}
\end{codegrey}


Edit: alternative is to add the negative vspace in the environment--

\newenvironment{code}{\color{blue}}{\ttfamily \vspace{-3mm}}
\newenvironment{codegrey}{\color{grey}}{\ttfamily \vspace{-3mm}}


but note that this will affect the spacing on the next paragraph after closing the environment

Here is an option using listings:

\documentclass{article}

\usepackage{xcolor,listings,etextools}
\lstset{basicstyle=\ttfamily,mathescape,columns=fullflexible}

\begin{document}

\begin{lstlisting}
$\AfterGroup{\color{blue}}$\renewcommand{\arraystretch}{1.5}
$\AfterGroup{\color{gray}}$\begin{tabular}{|c|p{3cm}llcp{5cm}|}
\end{lstlisting}

\end{document}


Without etextools you can use

\newcommand{\colorblue}{\color{blue}}
\newcommand{\colorgray}{\color{gray}}

...

\begin{lstlisting}
$\aftergroup\colorblue$\renewcommand{\arraystretch}{1.5}
$\aftergroup\colorgray$\begin{tabular}{|c|p{3cm}llcp{5cm}|}
\end{lstlisting}