6

Is it possible to define a verbatim{} command that I could use instead of the environment?

\begin{verbatim}
\end{verbatim}
1

3 Answers 3

6

As Stefan has said, fancyvrb is usually the way to go. However, it’s not straightforward to use in an environment since the relevant macro is undocumented1).

Here’s a minimal working example:

\documentclass{article}

\usepackage{fancyvrb}

\newenvironment{codeframe}[1]
  {
    % First, we tell fancyvrb that we're inside a verbatim environment.
    \VerbatimEnvironment
    \textbf{Source code ``#1'':}\\
    % Now we start the actual environment:
    \begin{Verbatim}[frame=single]%
  }
  {\end{Verbatim}}

\begin{document}
\begin{codeframe}{example}
  this->is(a[source]).code();
\end{codeframe}
\end{document}

The comment % right behind the \begin{Verbatim}… is important – otherwise, the compiler will complain with horrible, undecipherable error messages. The same will happen for any other error you make, so be careful.

The \VerbatimEnvironment command is equally crucial, and undocumented.


1) For simple cases, using the (documented) \DefineVerbatimEnvironment may be enough, but the above example cannot be written with it.

2
  • This creates a verbatim environment, not a verbatim command, which I think the OP wanted.
    – hadley
    Commented May 18, 2013 at 18:59
  • Note for reader: It's Verbatim with a capital V, not verbatim. Commented May 21, 2020 at 6:39
5

Why not use \verb?

\documentclass{article}

\begin{document}
 Foo \verb|\bar| baz
\end{document}
2
  • I thought of the inline \verb, but I need something that can span over several lines.
    – landroni
    Commented Aug 7, 2010 at 11:01
  • 1
    @landroni In many (but not all) ways, \detokenize{} can emulate verbatim, and it includes line breaking. Commented Jan 5, 2017 at 1:43
3

If you need further functionality, have a look at the fancyvrb package, it provides further environments and commands for flexible handling of verbatim text.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .