1

Recently, when I've been working with environments with an optional argument, I've noticed that the behavior changes when I introduce a set of square braces, even when there is nothing inside them. For instance:

\documentclass{article}
\usepackage{fancyvrb}

\newenvironment{exer}[1][] { do the following exercise from #1 \VerbatimOut{\jobname.exer}% } { \endVerbatimOut% \input{\jobname.exer}% }

\begin{document} \begin{exer}[] some text \end{exer} \end{document}

It will compile a pdf with "some text" as well as a .exer file, but if I replace the exer environment with

\begin{exer}
some text
\end{exer}

it will throw the following error:

! FancyVerb Error:
  Extraneous input `some text' between \begin{exer}[<key=value>] and line end
.
\FV@Error ... {FancyVerb Error:
\space \space #1
}

l.16 some text

So I have two questions: first, why does the environment behave differently even when I pass in the default optional argument, and second, is there any way to patch or address this behavior?

Many thanks.

muzimuzhi Z
  • 26,474
  • Similar: https://tex.stackexchange.com/questions/9035/how-to-pass-an-optional-argument-to-an-environment-with-verbatim-content – muzimuzhi Z Jun 13 '21 at 06:13

2 Answers2

1

I'm not sure what would be the usefulness of this. Anyway, you have to announce fancyvrb that this is a \VerbatimEnvironment.

\documentclass{article}
\usepackage{fancyvrb}

\newenvironment{exer}[1][]{% \VerbatimEnvironment do the following exercise\if\relax\detokenize{#1}\relax\else\space from~#1\fi \begin{VerbatimOut}{\jobname.exer}% }{% \end{VerbatimOut}% \par\input{\jobname.exer}% }

\begin{document}

\begin{exer}[] some text \end{exer}

\begin{exer}[the book] some text \end{exer}

\end{document}

enter image description here

egreg
  • 1,121,712
0
\documentclass{article}
\usepackage{fancyvrb}

\makeatletter
\def\exer{\@ifnextchar[\exer@i\exer@i[]}
\def\exer@i[#1]{do the following exercise #1
\VerbatimOut{\jobname.exer}}
\def\endexer{\endVerbatimOut\par
\input{\jobname.exer}}
\makeatother

\begin{document}
\begin{exer}
some text
\end{exer}
\end{document}
user187802
  • 16,850