This question is kind of follow up question of the following
- How to capture the current math style?
- Is there a test for the different styles inside maths mode?
- Cache math content in savebox and account for math style
There are some suggestions, but I wasn’t able to get the following MWE to work with the \ThisStyle{...\SavedStyle...} construct. I want to save some content math or text in an hbox while keeping the correct math style. At the moment everything is in double script style if it is put in my box.
% !TeX program = xelatex
\documentclass[11pt]{scrartcl}
\usepackage{xparse,scalerel,parskip}
\ExplSyntaxOn\makeatletter
% - #1: Box-Register
% - #2: Content
\cs_new:Npn \tobiw_set_text_or_math_hbox:nn #1#2 {
\mode_if_math:TF {
\ThisStyle {
\hbox_gset:Nn #1 {
\(
\SavedStyle
#2
\)
}
}
} {
\hbox_gset:Nn #1 {
#2
}
}
}
\cs_generate_variant:Nn \tobiw_set_text_or_math_hbox:nn { Nn, NN }
\NewDocumentCommand { \boxtest } { m } {
\tobiw_set_text_or_math_hbox:Nn \l_tmpa_box { #1 }
\box_use:N \l_tmpa_box
}
\makeatother\ExplSyntaxOff
\begin{document}
\boxtest{Box}
$a \boxtest{a}$
$a^2 a^{\boxtest{2}}$
$\frac{2}{3} \boxtest{\frac{2}{3}}$
\[\frac{2}{3} \boxtest{\frac{2}{3}}\]
\end{document}
As I need to use mathspec I’m bound to XeTeX and can't use LuaTeXs \mathstyle primitive.

\tobiw_set_text_or_math_hboxinside a\ThisStyle. Do you know why it doesn’t work when\ThisStyleis part of the definition of the boxing macro? – Tobi May 14 '17 at 14:00\tobiw_set_text_or_math_hboxmacro. I suppose you could put a LaTeX2e wrapper around the macro, i.e., define a macro which only invokes\ThisStyleand calls on\tobiw_set_text_or_math_hbox... – Steven B. Segletes May 14 '17 at 22:21\tobiw_set_text_or_math_hbox, that thescalerelmode switch\m@switch, which carries the math style in the form ofD,T,S, ors, is properly set just prior to the\hbox_gset, but becomessinside of the\hbox_gset, thus putting everything into\scriptscriptstyle, regardless of value just prior to the\hbox_gset. If I knew anything about LaTeX3, I might suspect a bug, for changing macro values, but as I said, I don't understand the LaTeX3 syntax at all. – Steven B. Segletes May 14 '17 at 22:40\hboxwithin the confines of the\ThisStyle, but you are trying to employ it outside the argument of\ThisStyle. The macro\ThisStyleis a glorified version of\mathchoice, which will generate boxes in all mathstyles and choose which one to use at the last moment. By using it outside the\ThisStyleargument (\box_use:N \l_tmpa_box), you are using it outside the\mathchoiceand thus just using the last of the 4\hboxes generated, which will always be\scriptscriptstyle. – Steven B. Segletes May 15 '17 at 10:49\ThisStyleis a bit unhandy, thats why I decided to stick to LuaTeX (I wanted to use XeTeX because the font loading takes so much longer in Lua), which has a simple\mathstyleprimitive I can use … – Tobi May 17 '17 at 17:03