[Tex/LaTex] Seemingly trivial: verbatim, newenvironment, and colorbox

colorenvironmentsverbatim

I am, once again, trying to achieve what seems like a trivial goal. I want to use \newenvironment to define a verbatim environment with a background color. I need to define my own environment because I need to run extra commands when opening the environment.

Here's what I have so far:

\newenvironment{response}{%
  % here, run extra commands, mostly related to \tikzmark and other extra legwork
  \verbatim
}{
  \endverbatim
}

This works fine. I tried the following to add a background color.

  • Define a background color for FancyVrb (Background color for fancyvrb), but then if I put \begin{Verbatim} and \end{Verbatim} in lieu of \verbatim and \endverbatim, this no longer works,
  • Playing myself with \color@setgroup and \color@endroup but these do not seem to be exposed by the xcolor package.
  • Using an lrbox, but again, any pair of \begin{foo} and \end{foo} that go across the environment are rejected (possibly because of \verbatim?)

I'm quite puzzled now and would love to have any pointers. Thanks!

UPDATE: the first comment has the solution, namely my failing to use \VerbatimEnvironment!

Best Answer

For fancyvrb, you need to use \VerbatimEnvironment before the \begin{Verbatim}. That tells fancyvrb to detect the name of the current environment, and look for the end of that environment, rather than looking for a literal \end{Verbatim}.

You will probably want to use a proper framing package to provide the background color...that way you won't have to worry about coming up with your own solutions for pagebreaks and will have access to a lot more features. You may want to take a look at mdframed or tcolorbox. An example with mdframed is below. tcolorbox has built-in solutions for a lot of use cases; one of those might give you most or all of what you need.

\documentclass{article}

\usepackage{fancyvrb}
\usepackage{mdframed}
\usepackage{xcolor}

\newenvironment{response}%
  {\VerbatimEnvironment
    \begin{mdframed}[backgroundcolor=green]
    \begin{Verbatim}}
  {\end{Verbatim}%
    \end{mdframed}}

\begin{document}

\begin{response}
<Text>
\end{response}

\end{document}