[Tex/LaTex] etoolbox: environment hooks in boolean switch

conditionalsenvironmentsetoolbox

What did I wrong, that the following does not work here:

(Edit: I mixed up the true and false parts, but I don't want to change the code, because the answers refer to this in a way confusing one.)

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{xcolor}

\usepackage{fancyvrb}
  \DefineVerbatimEnvironment{ExampleVerbatim}{Verbatim}%
    {fontsize=\small,formatcom=\color{blue},commandchars=\\\{\}}

\usepackage{setspace}
  \doublespacing

\usepackage{etoolbox}
  \newbool{tightspace}
  \setbool{tightspace}{false}
%----------------------------%
\ifbool{tightspace}{% true part empty - should do nothing
}{% false part:
  \BeforeBeginEnvironment{ExampleVerbatim}{\begin{spacing}{0.9}}%
  \AfterEndEnvironment{ExampleVerbatim}{\end{spacing}}%
}

\usepackage{lipsum}

\begin{document}

\lipsum[1]

\begingroup
\setbool{tightspace}{true}
\begin{ExampleVerbatim}
Because of \textcolor{black}{\itshape{\textbackslash}setbool\{tightspace\}\{true\}}
the line spacing should be very narrow ...
Don't wonder at \textcolor{red}{the missing line breaks:}
\lipsum[2]
\end{ExampleVerbatim}
\endgroup

\begin{ExampleVerbatim}
And now, with \textcolor{black}{\itshape{\textbackslash}setbool\{tightspace\}\{false\}},
it should have \textcolor{red}{the document's line stretch ...}
\lipsum[3]
\end{ExampleVerbatim}

\lipsum[4]

\end{document}

It seem's, that the boolean switch has no effect – or is there another thing I didn't realize?

Best Answer

You check the boolean switch once in the preamble and make the definition, which is not changed later.

It would work as expected if you would make the test later, such as:

\BeforeBeginEnvironment{ExampleVerbatim}{\ifbool{tightspace}{}{\begin{spacing}{0.5}}}%
\AfterEndEnvironment{ExampleVerbatim}{\ifbool{tightspace}{}{\end{spacing}}}%

However, I would make the spacing value a variable instead. And I guess you meant your tightspace check the other way round as in the original code.