It would be a bit fragile to do that in TeX: I'd do the replace with a regex in the editor as you suggest. (If you just wanted to make a ~
in text and a normal space in math that would be easier, but having it work in listings and verbatim would be harder)
For example given
\documentclass{article}
\usepackage{amsmath}
\begin{document}
A new example here will add a "tilde", after single letter, but will skip math mode.
$12 \times A = 128$
\[ a b c = 123\]
and a bit nore text
\begin{align}
a &= b\\
x & = y
\end{align}
\begin{verbatim}
A new example here will add a "tilde", after single letter,
but will skip math mode.
$12 \times A = 128$
\[ a b c = 123\]
and a bit nore text
\begin{align}
a &= b\\
x & = y
\end{align}
\end{verbatim}
A new example here will add a "tilde", after single letter, but will skip math mode.
$12 \times A = 128$
\[ a b c = 123\]
and a bit nore text
\begin{align}
a &= b\\
x & = y
\end{align}
\begin{verbatim}
A new example here will add a "tilde", after single letter,
but will skip math mode.
$12 \times A = 128$
\[ a b c = 123\]
and a bit nore text
\begin{align}
a &= b\\
x & = y
\end{align}
\end{verbatim}
\end{document}
The command M-x addtilde
in emacs produces
\documentclass{article}
\usepackage{amsmath}
\begin{document}
A~new example here will add a~"tilde", after single letter, but will skip math mode.
$12 \times A = 128$
\[ a b c = 123\]
and a~bit nore text
\begin{align}
a &= b\\
x & = y
\end{align}
\begin{verbatim}
A new example here will add a "tilde", after single letter,
but will skip math mode.
$12 \times A = 128$
\[ a b c = 123\]
and a bit nore text
\begin{align}
a &= b\\
x & = y
\end{align}
\end{verbatim}
A~new example here will add a~"tilde", after single letter, but will skip math mode.
$12 \times A = 128$
\[ a b c = 123\]
and a~bit nore text
\begin{align}
a &= b\\
x & = y
\end{align}
\begin{verbatim}
A new example here will add a "tilde", after single letter,
but will skip math mode.
$12 \times A = 128$
\[ a b c = 123\]
and a bit nore text
\begin{align}
a &= b\\
x & = y
\end{align}
\end{verbatim}
\end{document}
where addtilde
is defined by
(defun hidespaceenv (e)
(goto-char (point-min))
(while (re-search-forward
(if (string-equal e "[") "\\\\\\["
(if (string-equal e "$") "\\$"
(concat "\\\\begin{" e "}")))
nil 1)
(while (re-search-forward "\\([a-zA-Z]\\)\\(\\s-+\\)\\|\\(\\\\begin\\)" (save-excursion(re-search-forward
(if (string-equal e "[") "\\\\\\]"
(if (string-equal e "$") "\\$"
(concat "\\\\end{" e "}")))
nil 1) (point)) 1)
(replace-match "\\1SPACE@@\\2\\3@@" t))))
(defun addtilde ()
(interactive)
(mapcar `hidespaceenv (list "verbatim" "align" "equation" "[" "$"))
(goto-char (point-min))
(while (re-search-forward "\\(\\(^\\|\\s-+\\)[a-zA-Z]\\)\\s-+" nil 1)
(replace-match "\\1~"))
(goto-char (point-min))
(while (re-search-forward "SPACE@@\\(\\s-+\\|\\\\begin\\)@@" nil 1)
(replace-match "\\1")))