# Can the verbatim environment be used inside a custom environment definition?

I have the following code:

\documentclass{minimal}

\newenvironment{abc}
{\begin{verbatim}}
{\end{verbatim}}

\begin{document}

% This works.
\begin{verbatim}
abc
\end{verbatim}

% This does not work.
\begin{abc}
abc
\end{abc}

\end{document}


I am trying to create a custom environment that uses verbatim. But the above code does not work. How should I do this?

• It mostly depends on what you want the custom environment to do. Look at fancyvrb and tcolorbox before reinventing the wheel. – egreg Sep 11 '15 at 14:32

It depends on the verbatim environment in question.

# Environment verbatim of package verbatim

If you load package verbatim, then its environment verbatim can be used inside other environment definitions as long it is not hidden inside other groups. Also, it cannot be used as \begin{verbatim}, because verbatim needs to know the name of the parent environment to find the end tag \end{<parent>}. The parent environment name would be overwritten by the LaTeX code for \begin.

Example:

\documentclass{minimal}

\usepackage{verbatim}

\newenvironment{abc}
{\verbatim}
{\endverbatim}

\begin{document}

% This works.
\begin{verbatim}
abc
\end{verbatim}

% This does now work.
\begin{abc}
abc
\end{abc}

\end{document}


# Package fancyvrb

Custom verbatim environments can be created by \DefineVerbatimEnvironment, example from the documentation, slightly modified:

\documentclass{article}

\usepackage{fancyvrb}
\DefineVerbatimEnvironment{abc}{Verbatim}{%
gobble=2,
numbers=left,
numbersep=2mm,
frame=lines,
framerule=0.8mm,
}

\begin{document}
\begin{abc}
First verbatim line.
Second verbatim line.
\end{abc}
\end{document}


# Package listings

Environments can be defined with \lstnewenvironment. Example from the documentation:

\documentclass{article}

\usepackage{listings}
\lstnewenvironment{pascal}{%
\lstset{language=pascal}%
}{}

\begin{document}
\begin{pascal}
for i:=maxint to 0 do
begin
{ do nothing }
end;
\end{pascal}
\end{document}