Introduction:
When you use \renewcommand within another macro or environment, one needs to double up the ## to access the parameters of the inner macro. This serves as a way to distinguish the inner macros ##1 with the outer macros #1 (even if the outer macro does not have any parameters, it provides for error checking). For example:
\newcommand*{\OuterCommand}{%
\renewcommand*{\SomeCommand}[1]{\color{red}##1}%
....
}%
The references below provide more details on this.
Issue:
It appears that the same doubling up of the # is needed within a \foreach loop as illustrated in the MWE below.
This took me quite some time to figure this out as the error message that the MWE below gives is:
Illegal parameter number in definition of \pgffor@body
This was within a very deeply nesting of \foreach loops, so I was sure the problem was that I was nesting the \foreach too deeply. Surprisingly, if you skip past the error, the output is still correct, so this made it even harder to locate the problem.
Questions:
- Since the
\foreachdoes not have parameters like#1(as\newcommanddoes), why is it necessary to double up the#within a definition within a\foreach? - How is that the output is still correct, if you simply ignore the error and hit return to continue processing?
References:
- renewcommand in a newcommand.
- Defining LaTeX commands within other commands.
- Nesting command definitions more than two levels.
Code:
\documentclass{article}
\usepackage{xcolor}
\usepackage{pgffor}
\newcommand*{\MyList}{A,B,C}%
\newcommand{\SomeCommand}[1]{#1}%
\begin{document}
\foreach \x in \MyList {%
\renewcommand*{\SomeCommand}[1]{\color{red}#1}% Using ## here eliminates the error.
\par\SomeCommand{\x}%
}%
\end{document}
##1"to access the parameters of the inner macro" it is simply that you need to use##to enter#. – David Carlisle Sep 15 '12 at 08:35#as escaping the#. But, then how do you explain that you need 4 for the next level? :-) – Peter Grill Sep 15 '12 at 09:20