3

The arguments that I need to pass to a Verbatim environment are in a variable. I'm trying to do this:

\documentclass{article}
\usepackage{fancyvrb}
\begin{document}
\def\opts{numbers=left}
\begin{Verbatim}[\opts]
Hello, world!
\end{Verbatim}
\end{document}

Obviously, t fails:

! Package keyval Error: numbers=left undefined.

See the keyval package documentation for explanation. Type H <return> for immediate help. ...

l.5 \begin{Verbatim}[\opts]

What is the right way?

yegor256
  • 12,021

2 Answers2

5

You generally don't want to pass a macro for options, but to define a new key.

\documentclass{article}
\usepackage{fancyvrb}

\makeatletter \define@key{FV}{opts}[]{% \setkeys{FV}{ numbers=left, % additional options }% } \makeatother

\begin{document}

\begin{Verbatim}[opts] Hello, world! \end{Verbatim}

\end{document}

If you insist in passing macros, you need to expand them prior the environment parses them.

\documentclass{article}
\usepackage{fancyvrb}

\newcommand{\opts}{numbers=left}

\begin{document}

\expanded{\noexpand\begin{Verbatim}[\opts]} Hello, world! \end{Verbatim}

\end{document}

But I can't recommend this.

Another strategy is to define a new Verbatim:

\documentclass{article}
\usepackage{fancyvrb}

\DefineVerbatimEnvironment{lVerbatim}{Verbatim}{numbers=left}

\begin{document}

\begin{lVerbatim} Hello, world! \end{lVerbatim}

\end{document}

egreg
  • 1,121,712
  • I define my options in a few steps, setting it once and then adding more elements to it, according to some configuration requirements. In the end I have a variable \opts where all keys are accumulated. Is it possible to do the same with the key you recommended? Can you please illustrate how exactly? – yegor256 Jan 09 '24 at 15:47
  • @yegor256 Some more details would be useful. – egreg Jan 09 '24 at 15:54
2

You need to expand \opts prior to the invocation of Verbatim. Here is one way it can be done.

\documentclass{article}
\usepackage{fancyvrb}
\begin{document}
\def\opts{numbers=left}
\def\z{\begin{Verbatim}}
\expandafter\z\expandafter[\opts]
Hello, world!
\end{Verbatim}
\end{document}

enter image description here