[Tex/LaTex] Can the `verbatim` environment be used inside a custom environment definition

environmentsverbatim

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?

Best Answer

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}

Result

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}

Result fancyvrb

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}

Result listings