After a lot of trial and error, I haven't been able to solve the following problem:
A simplified version: I want to use \g@addto@macro to add code to another macro wich will use a command of the macro, I expected this code to work:
\newcommand{\foo}[1]{#1, }
\newcommand{\bar}[1]{
\g@addto@macro\foo{
##1#1
}
}
And to produce this output:
\foo{A} -> A,
\bar{B}
\show\foo = #1, #1B
\foo{A} -> A, AB
\bar{C}
\show\foo = #1, #1B#1C
\foo{A} -> A, ABAC
I hope it is clear what I want. In an actual implementation, I want to expand a \switch-like structure dynamically. The problem with the code is, that the ##
is not expanded to #
when adding code, however #1
is expanded to the first parameter of \bar
. This causes
\bar{B}
\show\foo = #1, ##1B
wich in turn doesn't produce the desired output. I would like to avoid additional packages if possible.
#
you are missing several%
which would add spurious space tokens to your result.\g@addto@macro
goes to some lengths passing the tokens through a toks register specifically to prevent the need to double#
(so you can build up strings including that character)