I am trying to write a macro that works in math-mode like this: \mymacro^3 str produces the same result as \pi^3 str, whereas \mymacro{str1}{str2}{str3} produces the same result as \pi str1 \pi str2 \pi str3. In other words, if the character that immediately follows is ^, it only prints π; otherwise it absorbs an argument (a string), printing π and the argument, and keeps absorbing arguments until the next character is not {.
Here is my code:
\def\mmymacro#1{
\pi #1
\@ifnextchar\bgroup{\mmymacro}{\relax}
}
\def\mymacro{
\@ifnextchar^{\pi}\mmymacro
}
It works as long as it is in display-mode followed by other characters or in inline-mode, but it produces a warning when used as
$$
\mymacro
$$
The warning is
! Display math should end with $$.<to be read again> $
! Missing $ inserted.<inserted text>$
I have already added \relax in the definition, but it does not fix the problem. So I tried another way:
\def\mmymacro#1{
\pi #1
\@ifnextchar\bgroup{\mmymacro}{}
}
\def\mymacro{
\@ifnextchar^{\pi}{\mmymacro}\relax
}
This no longer produces warnings, but when used like \mymacro{x}{y}, i.e. no leading ^, it produces the same result as \pi \pi x \pi y, no matter in display-mode or in inline-mode. I saw Werner's answer, but following his clue I find it seem to have an extra { inserted. Any explanation please? How can fix it?


$$\mymacro $$is$$\mymacro{$}$so$$\pi$ $with the space coming as you have no%at the ends of lines in the definition. Of course$$is not supported syntax in latex anyway, so you could not worry if that is broken.... – David Carlisle Dec 07 '16 at 13:51\@ifnextchar^{\pi}{\mmymacro}\relaxthere's no extra brace inserted, the problem just is that the\relaxbecomes the token checked against^which is always false and so\mmymacrowill always be called. – siracusa Dec 07 '16 at 15:33