[Tex/LaTex] Alias for verbatim environment

macrosverbatim

I'm trying to create an alias for the verbatim environment like this:

\newcommand{\vb}[1]{\begin{verbatim} #1 \end{verbatim}}

So I can use it like this:

 \vb{
      word.
  }

But when using it, I get this error:

! Missing $ inserted.
<inserted text> 
            $
l.93 \end{verbatim}

Where line 93 is the end of a verbatim environment I used after later down the file after closing the \vb. If I replace all verbatim environments with the \vb syntax, then I get this error:

Runaway argument?
zip([],B) = case ([],B) of ([],_) => [] | (_,[]) => [] | (x::L,y::R\ETC.
! File ended while scanning use of \@xverbatim.
<inserted text> 
            \par 

So it seems like the \vb is not closing the environment correctly? How do I get this to work ? The end goal is to get a \vb command that I can use like I described above, and bonus points if I could indent the stuff in the \vb command by a few mm.

Best Answer

A general rule is that you can't have \begin{verbatim} or the \verb command in the argument to another command, including an argument to \newcommand.

If you really want to use that syntax, you of course can't have braces in the argument and hope that they will be printed as themselves: either they delimit the argument or they must be printed.

If this limitation satisfies you, then

\makeatletter
\newcommand{\vb}{%
  \begingroup
  \advance\@totalleftmargin\parindent
  \@verbatim
  \catcode`{=1 \catcode`}=2 \catcode` =10
  \frenchspacing
  \@vb}
\def\@vb#1{#1\endtrivlist\endgroup} 
\makeatother

will allow you to write

\vb{
    word.
  }

I don't think this is a great improvement than saying

\begin{verbatim}
word.
\end{verbatim}

If you want a margin indent of the verbatim, look at the option xleftmargin in to the Verbatim environment provided by the package fancyvrb.

Related Question