In https://tex.stackexchange.com/a/127018/83257 there is a patch to make inline listings work in math mode. When using this together with listings' mathescape option, the space after a math escape is dropped in ams environments. The space is preserved in regular math blocks like \[ ... \]. I hope someone can help me fix this, I don't have the knowledge to figure it out by myself. A MWE is below:
\documentclass{article}
\usepackage{amsmath}
\usepackage{listings}
\lstset{mathescape,keepspaces}
%% patch from https://tex.stackexchange.com/a/127018/83257
\usepackage{etoolbox}
\expandafter\patchcmd\csname \string\lstinline\endcsname{%
\leavevmode
\bgroup
}{%
\leavevmode
\ifmmode\hbox\fi
\bgroup
}{}{%
\typeout{Patching of \string\lstinline\space failed!}%
}
%% end of patch
\begin{document}
Space before mathescape preserved:
\[
\lstinline|ifz $x$ then E$_2$ else E$_3$|
\]
Space before mathescape dropped:
\begin{align*}
\lstinline|ifz $x$ then E$_2$ else E$_3$|
\end{align*}
\end{document}
Edit: Discovered listings' keepspaces option solves part of the problem. Spaces after the mathe scape are not preserved, but spaces before are still dropped.


listingspackage (and found and reported by the author) easily solved the problem. oops, voted too soon; the question has been restated -- a problem still exists, just not the original one. – barbara beeton Aug 06 '15 at 12:50