# [texhax] A macro programming question

Philipp Stephani st_philipp at yahoo.de
Sun Apr 11 16:47:44 CEST 2010

Am 11.04.2010 um 15:19 schrieb Vafa Khalighi:

>
>
>
> To add to the other solutions... this one only defines one
> macro and works with both { } and \bgroup \egroup...
>
> \def\hboxR{\begingroup
>  \everyhbox{%
>   \aftergroup\endgroup
>   \everyhbox{}%
>   \beginR
>   \bgroup
>   \aftergroup\endR
>   \aftergroup\egroup
>  }\hbox}
>
>
> \setbox0=\hboxR{This is a test.}
> \box0
>
> Would not work here, because TeX expects a box. How can one fix this?

The following is a hack that might or might not work in your situation:

\TeXXeTstate=1
\def\hboxR{\hhboxR{}}
\def\hhboxR#1#2{%
\hhhboxR{#1}#2\nil
}
\def\firstofthree#1#2#3{#1}
\def\secondofthree#1#2#3{#2}
\def\thirdofthree#1#2#3{#3}
\def\hhhboxR#1#2#3\nil{
\ifx&#3&%
\ifx#2\bgroup
\expandafter\expandafter\expandafter\firstofthree
\else
\expandafter\expandafter\expandafter\secondofthree
\fi
\else
\expandafter\thirdofthree
\fi
{\hhhhboxR{#1}}%
{\hhboxR{#1#2}}%
{\hhhhhboxR{#1}{#2#3}}%
}
\def\hhhhboxR#1#2\egroup{%
\hhhhhboxR{#1}{#2}%
}
\def\hhhhhboxR#1#2{%
\hbox#1{\beginR#2\endR}%
}
\setbox0=\hboxR to 35pt \bgroup abc\hfil def\egroup
\box0
\bye

Issues: Significant spaces are gobbled, braces must be either both explicit or both implicit, only \bgroup...\egroup is allowed (no other implicit brace tokens), the contents are read as a macro argument, preventing interesting applications like opening and closing the box in different macros.
Maybe you want to abandon the idea of simulating the box primitives and use a different syntax (like LaTeX's \sbox and lrbox) instead.