1

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.

  • 2
    I'm voting to close this question as off-topic because an option provided by the listings package (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

1 Answers1

2

This does not affect just the amsmath environments. This minimal example also exhibits the problem:

\documentclass[12pt,a4paper]{article}
\usepackage{listings}

\lstset{mathescape,keepspaces}

\newcommand\identity[1]{#1}

\begin{document}
  \lstinline!let $v_1$ = 10 in $v_1$ + $v_2$!

  \identity{\lstinline!let $v_1$ = 10 in $v_1$ + $v_2$!}
\end{document}

Which produces this output

Example 1

In the listings documentation, Section 6.1, it says that if \lstinline is used inside an argument, some spaces have to be protected by escaping them with \. Although it doesn't mention escaping to math mode, it seems to be one of the cases. Escaping spaces with \ fixes the problem for both align and my example.

  \lstinline!let $v_1$ = 10 in $v_1$ + $v_2$!

  \identity{\lstinline!let\ $v_1$ = 10 in\ $v_1$ +\ $v_2$!}
  \begin{align}
    \lstinline!let\ $v_1$ = 10 in\ $v_1$ +\ $v_2$!
  \end{align}

Example 2

It is mighty annoying to have to do this, especially since, e.g., changing align to equation will show the backslashes and they have to be removed again.

FerD
  • 128
  • Indeed, as soon as the listings command is used as an argument somewhere, it seems quite brittle. I've switched to minted, which seems much more robust, although it is more involved to setup. – Hendrik van Antwerpen Dec 13 '15 at 21:28