I have a several rather lengthy documents with numbered points (catechism
questions) that I would like to be able to selectively include in other
documents using a utility function that uses a range argument. I ran into
trouble and eventually traced it to the way the \foreach
seems to run in its
own private scope of some kind. The loops seem to iterate properly, but things
set inside them (such as \newif
definitions or toggles from the etoolbox
package don't seem to stick.
This fails miserably:
\documentclass{scrartcl}
\usepackage{pgffor}
\usepackage{etoolbox}
\newcommand{\wkk}[1]{%
\foreach \x in {1,...,5}{%
\providetoggle{wkk\x}
}
\foreach \x in {#1}{%
\toggletrue{wkk\x}
}
% In a real example the following content would be \input here
\iftoggle{wkk1}{output 1 }{}
\iftoggle{wkk2}{output 2 }{}
\iftoggle{wkk3}{output 3 }{}
\iftoggle{wkk4}{output 4 }{}
\iftoggle{wkk5}{output 5 }{}
}
\begin{document}
\wkk{2,...,4}
\end{document}
Yet if I replace the \foreach
loops with exactly what they should be doing in the above example, it works fine:
\documentclass{scrartcl}
\usepackage{pgffor}
\usepackage{etoolbox}
\newcommand{\wkk}[1]{%
\providetoggle{wkk1}
\providetoggle{wkk2}
\providetoggle{wkk3}
\providetoggle{wkk4}
\providetoggle{wkk5}
\toggletrue{wkk2}
\toggletrue{wkk3}
\toggletrue{wkk4}
% In a real example the following content would be \input here
\iftoggle{wkk1}{output 1 }{}
\iftoggle{wkk2}{output 2 }{}
\iftoggle{wkk3}{output 3 }{}
\iftoggle{wkk4}{output 4 }{}
\iftoggle{wkk5}{output 5 }{}
}
\begin{document}
\wkk{2,...,4}
\end{document}
Obviously these are kind of clumsy MWE's and I would be including the content from an external source file that was marked up with the correct toggles.
What am I doing wrong with the pgffor
package? Or is there a conceptually
better way to do this?
\foreach
uses a group.\iftoggle
does not survive any loop style I know -- I detected that too -- unfortunately. I think, there is always a grouping within loops, for some\ifthenelse
queries, whatever\setcounter
is not group-safe, or am I completely confused? So at least LaTeX - counters are not safe from being changed in a group.