Assume I have a macro like
\def\myMacro#1{<some stuff>}
And I am calling it like this
\myMacro{There are \some arguments \in \here g}
How can I iterate over each single token in the #1
argument inside \myMacro
? So basically I want to know how I can iterate over a list whose delimiter is not a comma or any other character but rather the token boundaries as applied by TeX. Note that the argument may contain control sequences that are undefined so they must not be expanded.
Example of what I mean:
\def\myMacro#1{<iterate over all tokens>|\string<current token>|}
\myMacro{A \test}
which should result in
|A|| ||\test|
It is important to note that I also care about spaces so they shouldn't be gobbled away. Also I don't want to execute any code outside of \mymacro
in order for this to work (e.g. changing the catcode of spaces before calling \myMacro
).
As I am really into understanding how such a thing works I'd appreciate if you could also explain how and why your provided code works :)
My attempt at this was
\def\iterate#1{%
\tokenGrabber#1\relax<!;!>%
}
\def\tokenGrabber#1#2<!;!>{%
|\string#1|%
\noexpandarg%
\IfStrEq{#2}{\relax}{%
}{%
\tokenGrabber#2<!;!>%
}%
}
But this gobbles away spaces and it produces an error for empty inputs or inputs ending with a space.
{
/}
if it does ... – Joseph Wright♦ Dec 15 '18 at 9:54a{xyz}b
do you want to iterate three times, witha
,xyz
andb
or 7 times witha
,{
,x
,y
,z
,}
,b
and it is presumably Ok to use something like\bgroup
for{
as you can't hold an unmatched brace in a macro. – David Carlisle Dec 15 '18 at 10:07