This method works, but is fragile. Maybe Lua has a better solution by traversing the nodes.
You can redefine the dollar, so:
%! TEX program = pdflatex
\documentclass{article}
\begingroup
\ExplSyntaxOn
\catcode`\$=\active
\protected\gdef${
\unless\ifmmode
% ======== we're near the start of a formula
\ifdim\lastskip>\c_zero_dim
\l_tmpa_dim=\lastskip\relax
\unskip
\nolinebreak[3]
\hskip\l_tmpa_dim
\fi
\(
\else
% ======== we're near the end of a formula ========
\)\nolinebreak[3]
\fi
}
\ExplSyntaxOff
\endgroup
\begin{document}
one two three $f$ four five six
one two three $f$ four five six
one two three $h$ four five six
one two three $f$ four five six
one two three $f$ four five six
one two $g$ three $f$ four five six
one two three $f$ four five six
one two three $f$ four five six
one two three $f$ four five six
\catcode`\$=\active
one two three $f$ four five six
one two three $f$ four five six
one two three $h$ four five six
one two three $f$ four five six
one two three $f$ four five six
one two $g$ three $f$ four five six
one two three $f$ four five six
one two three $f$ four five six
one two three $f$ four five six
\end{document}
Of course this will break things that rely on $
having the catcode it should have e.g. TikZ calc
library:
\begin{tikzpicture}
\draw (0, 0)--($(0, 0)+(1, 1)$); % "Missing $ inserted." --- what?
\end{tikzpicture}
There are some ways to patch it e.g.
\AddToHook{env/tikzpicture/begin}{\catcode`\$=3\relax}
But then the text inside nodes don't get this applied (this is fragile!):
\begin{tikzpicture}
\node [text width=10cm, above] {one two three $f$ four five six one two three $f$ four five six one a $f$ four five six one two three $f$ four five six};
\node [text width=10cm, below] {one two three $f$ four five six one two three $f$ four five six one a~$f$~four five six one two three $f$ four five six};
\end{tikzpicture}
In this specific case you can get away with using TikZ' node font
:
\begin{tikzpicture}[node font={\catcode`\$=\active}]
\node [text width=10cm, above] {one two three $f$ four five six one two three $f$ four five six one a $f$ four five six one two three $f$ four five six};
\node [text width=10cm, below] {one two three $f$ four five six one two three $f$ four five six one a~$f$~four five six one two three $f$ four five six};
\end{tikzpicture}
\(
\)
syntax, one reason for introducing that is it is then trivial to redefine the commands for special affects, eg define\(
to include\nolinebreak[3]
or whatever.\(
/\)
, I'll stick with$
/$
.