0

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.

  • 1
    The catcode of the character has to be set when the \def is 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
  • I used 11 for my tests. Ok, I mixed parsing and execution. Thanks. – Saroupille Feb 25 '19 at 17:09
  • Is there a way to achieve my goal dynamically though? Replacing the token generated by & by the token corresponding to a space? – Saroupille Feb 25 '19 at 17:20
  • Sorry, I didn't understand what exactly you want to achieve. If you want to force a space in math mode you can use \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 \ensuremath does 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
  • I probably oversimplified my example. Originally, the math code is something contained in an align environment. Here, I used the ampersand just for the snippet. Then my point is to define a command \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
  • I finally solved my problem using this thread https://tex.stackexchange.com/questions/185682/command-which-replaces-all-occurrences-of-a-certain-character-with-another-chara – Saroupille Feb 25 '19 at 20:05

0 Answers0