etoolbox's iftoggle vs verbatim

My problem is that I can set up toggles, using etoolbox's \newtoggle{x}, set it to true with \toggletrue{x} and even use it with iftoggle{x}{this for true}{this for false}. However, if I try to put a verbatim environment inside a conditional block, it breaks and gives me an error message:

Runaway argument?
for x in range(1, 43): print('x=', x) \end {verbatim}
./q4.tex:19: Paragraph ended before \@xverbatim was complete.
<to be read again> )
./Quiz1.tex:90: Missing number, treated as zero.
<to be read again>
{
l.90 \vspace{
1 pc}
?
\par
l.19 }{}

?


for the code:

\iftoggle{displaysolutions}{

\textit{The statement will execute y times.}
\begin{verbatim}
for x in range(0, y):
print('x=', x)
\end{verbatim}

}{}


Any ideas of what I'm possibly doing wrong? Any alternatives?

-
Thank you so much! Do you have any idea of an alternative? – Eduardo Bezerra Oct 22 '12 at 15:50
Welcome to TeX.SX! – egreg Oct 22 '12 at 16:15

1 Answer

Having a verbatim environment in the argument to another command is not allowed: the changes that need to be done to the special characters' meaning can't be made when the environment has already been read in as an argument.

A way out is adapting to use a "primitive" syntax:

\documentclass{article}
\usepackage{etoolbox}

\makeatletter
\newcommand{\iftoggleverb}[1]{%
\ifcsdef{etb@tgl@#1}
{\csname etb@tgl@#1\endcsname\iftrue\iffalse}
{\etb@noglobal\etb@err@notoggle{#1}\iffalse}%
}
\makeatother

\newtoggle{displaysolutions}
\togglefalse{displaysolutions}

\begin{document}
\section{A}

Are solutions displayed? \iftoggle{displaysolutions}{Yes}{No}.

\iftoggleverb{displaysolutions}

\noindent\textit{The statement will execute y times.}
\begin{verbatim}
for x in range(0, y):
print('x=', x)
\end{verbatim}

\fi

\toggletrue{displaysolutions}

\section{B}

Are solutions displayed? \iftoggle{displaysolutions}{Yes}{No}.

\iftoggleverb{displaysolutions}

\noindent\textit{The statement will execute y times.}
\begin{verbatim}
for x in range(0, y):
print('x=', x)
\end{verbatim}

\fi

\end{document}


There should be a "matching \fi" after the part you want displayed or not.

You can also use

\iftoggleverb{displaysolutions}
<material to be displayed if the toggle is true>
\else
<material to be displayed if the toggle is false>
\fi


Important limitation. Don't use \iftoggleverb nested in other conditional statements.

-
Perfect! This is precisely what I needed! – Eduardo Bezerra Oct 22 '12 at 16:27