Just because it is there, here's a version which uses coffins to arrange and typeset the boxes.
The syntax is identical to that specified in the question except that \cwrapper
can take an optional argument specifying the horizontal distance between the larger box and the superscript and subscripts. Since this is optional, the OP's syntax can be used unchanged. In that case, the default is 1pt
, but this can obviously be modified as desired.
Essentially, each of \csup
, \csub
and \crepeat
is defined to put its content into a coffin. \cwrapper
is defined to join the coffins appropriately and typeset the result. Nesting works as expected, as shown in the extended example below.
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\coffin_new:N \l_clement_main_coffin
\coffin_new:N \l_clement_tmpa_coffin
\coffin_new:N \l_clement_sup_coffin
\coffin_new:N \l_clement_sub_coffin
\dim_new:N \l_clement_spacer_dim
\NewDocumentCommand \csup { m }
{
\hcoffin_set:Nn \l_clement_sup_coffin { \scriptsize #1 }
}
\NewDocumentCommand \csub { m }
{
\hcoffin_set:Nn \l_clement_sub_coffin { \scriptsize #1 }
}
\NewDocumentCommand \crepeat { m }
{
\hcoffin_set:Nn \l_clement_tmpa_coffin { \fbox { \tl_trim_spaces:n { #1 } } }
}
\NewDocumentCommand \cwrapper { O { 1pt } m }
{
\group_begin:
\clement_cwrapper:nn { #1 } { #2 }
\group_end:
}
\cs_generate_variant:Nn \coffin_join:NnnNnnnn { NnnNnnVn }
\cs_new_protected:Npn \clement_cwrapper:nn #1 #2
{
#2
\dim_set:Nn \l_clement_spacer_dim { #1 }
\coffin_join:NnnNnnVn \l_clement_tmpa_coffin { r } { t } \l_clement_sup_coffin { l } { t } \l_clement_spacer_dim { 0pt }
\coffin_join:NnnNnnVn \l_clement_tmpa_coffin { \l_clement_tmpa_coffin-r } { \l_clement_tmpa_coffin-b } \l_clement_sub_coffin { l } { b } \l_clement_spacer_dim { 0pt }
\coffin_set_eq:NN \l_clement_main_coffin \l_clement_tmpa_coffin
\coffin_typeset:Nnnnn \l_clement_main_coffin { l } { H } { 0pt } { 0pt }
}
\ExplSyntaxOff
\begin{document}
\cwrapper{\crepeat{%
AAA
}%
\csup{pA}\csub{bA}%
}
\cwrapper{\crepeat{%
AAA
\cwrapper{\crepeat{%
BBB
}%
\csup{pB}\csub{bB}%
}%
}%
\csup{pA}\csub{bA}%
}
\cwrapper{\crepeat{%
AAA
\cwrapper{\crepeat{%
BBB
\cwrapper{\crepeat{CCC}\csup{pC}\csub{bC}%
}%
}%
\csup{pB}\csub{bB}%
}%
}%
\csup{pA}\csub{bA}%
}
\cwrapper[5pt]{\crepeat{%
AAA
\cwrapper{\crepeat{%
BBB
\cwrapper[10pt]{\crepeat{CCC}\csup{pC}\csub{bC}%
}%
}%
}%
}%
\csup{pA}\csub{bA}%
}
\cwrapper{\crepeat{%
AAA
\cwrapper{\crepeat{%
BBB
\cwrapper{\crepeat{CCC}\csup{pC}%
}%
}%
\csub{bB}%
}%
}%
}
\end{document}