[Tex/LaTex] How to add space around all inline equations, adjusting for punctuation

spacing

The answer to this question explains how to add space around inline equations, but it doesn't account for punctuation. You can see what I mean in the picture below.

enter image description here

Is there a way to put the space after the comma, rather than before it? The obvious solution of putting the comma inside the equation environment, e.g., $A = \pi r^2,$ won't work because the fonts are different (I'm using XeLaTeX). That is, unless you manually specify each time that the comma should be a different font, but I'm hoping for a lazier solution (which accounts for all of the normal punctuation: periods, commas, semicolons, etc.).

Best Answer

If you use a non zero value for \mathsurround, you should add punctuation inside the formula and then restore the spacefactor afterwards.

\documentclass{article}

\newcommand{\fp}[1]{%
  \mbox{#1\xdef\fpsf{\the\spacefactor}}%
  \aftergroup\setfpsf
}
\newcommand\setfpsf{\spacefactor\fpsf\relax}

\begin{document}

The area of a circle is given by $A=\pi r^2$, where $r$ is its radius.
The length of the circumference is $C=2\pi r$. Easy.

\mathsurround=6pt \xspaceskip=10pt

The area of a circle is given by $A=\pi r^2$, where $r$ is its radius.
The length of the circumference is $C=2\pi r$. Easy.

The area of a circle is given by $A=\pi r^2,$ where $r$ is its radius.
The length of the circumference is $C=2\pi r.$ Easy.

The area of a circle is given by $A=\pi r^2\fp{,}$ where $r$ is its radius.
The length of the circumference is $C=2\pi r\fp{.}$ Easy.

\end{document}

Here the settings are exaggerated by the high \xspaceskip, used just for testing that the additional space is inserted when appropriate (fourth paragraph).

enter image description here

Here's the output of

The area of a circle is given by $A=\pi r^2\fp{,}$ where $r$ is its radius.
The length of the circumference is $C=2\pi r\fp{.}$ Easy.

when \mathsurround=3pt is used:

enter image description here