For playing the following example adds a
\fbox around inline math:
Update: Explanation and
The goal is to have something like
\everymath is called, we are already in math mode. Therefore the first
$ ends the math mode. The space, given by
\mathsurround would be set around the empty formula,
therefore it is set to zero.
Then a horizontal box is opened (
lrbox) and we switch in math mode again, but with
\aftergroup we get to the point right after the closing
$ and we can close the box and set the box with
Also we could let the math group in place and put the
The difference of these methods is the handling of
\mathsurround, if it is not zero.
In the first case the space is put inside the box, in the second case, the space is outside.
However, there is a serious drawback of this general method via
Inline math is used at many different places, thus the example also shows boxes at places where inline math is not expected.