I have a command that may contain the ampersand charater: &. Sometimes, when I use this command, I want that ampersand interpreted as a space. This is why I wanted to use the TeX command \catcode.
While the code below seems to be OK
\catcode`\&=11
\ensuremath{2&=2}
\catcode`\&=4
When I put the content inside a definition with \def for example:
\def\foobar{\ensuremath{2&=2}}
\catcode`\&=11
\foobar
\catcode`\&=4
I get an error message:
Misplaced alignment tab character &.
leading text: \foobar
How can I solve my problem? Moreover, I don't understand why the second snippet generates this error message while the first one does not.
\defis being executed, not when it defined command is being expanded. More precisely, the catcode is set when TeX first sees the character. You'd have to use\catcode`\&=11 \def\foobar{\ensuremath{2&=2}} \catcode`\&=4. Furthermore, the catcode of a space is 10, not 11. – Phelype Oleinik Feb 25 '19 at 17:01&by the token corresponding to a space? – Saroupille Feb 25 '19 at 17:20\def\foobar{\ensuremath{2\ =2}}... Or, if you want a proper space token you can use\@sptoken. – Phelype Oleinik Feb 25 '19 at 17:36\ensuremath{2&=2}looks a very odd construct, why the\ensuremath? if it is in math the\ensuremathdoes nothing, and if it is not in math then it is$2&=2$which would be an error if&has its normal catcode. – David Carlisle Feb 25 '19 at 17:52\def\foo[1]{#1 ... #1}such that the first occurrence of the argument is normal and the second one is the one where ampersands are replaced by spaces. – Saroupille Feb 25 '19 at 18:01