Spotting strings that are typos in "text mode" but that are right in "math mode"

In keeping with the Carlisle tradition, I am naming this "gem" \z. Done here for commas, periods and colons, but added loops could be set up for other tests.

I would be remiss if I didn't draw your attention to Ulrike's comments, noting that there are many pitfalls for \z. For example verbatim material, as well as the occurrence of the offending syntax inside a valid argument list are likely to cause compilation errors.

EDITED so that it can now work when the offending bit falls, for example, inside an align environment. Rather than outputting the parts on the fly (which causes problems if the offending bit falls inside an argument), I instead create a concatenated \def in which every ., etc. is replaced with an \ifmmode{} .\else\colorbox{cyan}{ .}\fi inside the \def. Only at the end, is the defed macro named \z@save regurgitated. [Just for completeness, the original behavior can be obtained by defining \newcommand\zz@[1]{#1} instead of the revised \newcommand\zz@[1]{\g@addto@macro\z@save{#1}} ]

\documentclass[11pt]{article}
\usepackage{xcolor,amsmath}
\makeatletter
\newcommand\z[1]{\def\z@save{}\z@A#1 ,\z@end\z@save}
\long\def\z@A#1 ,#2\z@end{%
  \z@B#1 .\z@end%
  \ifx\z@end#2\else\zz@{\ifmmode{} ,\else\colorbox{cyan}{ ,}\fi}\z@A#2\z@end\fi}
\long\def\z@B#1 .#2\z@end{%
  \z@C#1 :\z@end%
  \ifx\z@end#2\else\zz@{\ifmmode{} .\else\colorbox{orange}{ .}\fi}\z@B#2\z@end\fi}
\long\def\z@C#1 :#2\z@end{%
  \zz@{#1}%
  \ifx\z@end#2\else\zz@{\ifmmode{} :\else\colorbox{yellow}{ :}\fi}\z@C#2\z@end\fi}
\newcommand\zz@[1]{\g@addto@macro\z@save{#1}}
\makeatother
\pagestyle{empty}
\begin{document}
\z{
Punctuation , typos : such as 3 .75 and such .

No problem with this string
\begin{equation}
(3 .7\mu + \nu) ,
\end{equation}

\begin{align} 
\mathcal{A}_{\text{reg}}:\qquad ( - l_u/2+\epsilon_u , - l_\phi/2+\epsilon_\phi ) 
  \rightarrow ( l_u/2-\epsilon_u , l_\phi/2-\epsilon_\phi )\,. \end{align}
And again , are there these problems : a nd b .
}
\end{document}

enter image description here


You could use xelatex and \XeTeXinterchartoks:

\documentclass[11pt]{article}
%
\usepackage{xcolor}

\newXeTeXintercharclass\mypunctclass
\XeTeXcharclass `\. \mypunctclass
\XeTeXcharclass `\, \mypunctclass
\XeTeXinterchartokenstate=1
\XeTeXinterchartoks 4095 \mypunctclass{\textcolor{red}{TYPO}}



\pagestyle{empty}
\begin{document}

Punctuation , typos .

Punctuation, typos.

No problem with this string
\begin{equation}
(\mu + \nu) ,
\end{equation}
\end{document}

enter image description here