# Space around escaped equations in listings?

I am using listings with mathescape=true to include some typeset output. However, I would like a little white space around that output. Currently I have

\lstset{language=,
keepspaces=true,
basicstyle=\ttfamily,
columns=flexible,
mathescape=true,
}


However, the result is that a typeset equation is put on the line immediately following the preceding code, with no vertical white space.

For example:

\begin{lstlisting}
code: Gimme the square root of two:
$\sqrt{2}$
code: Gimme a rational approximation to pi:
$\displaystyle{\frac{355}{133}}$
\end{lstlisting}


comes out as

I know I could put the equations outside the listing, but it works better for me to have equations escaped within a listing.

How can I force escaped equations to be indented, and have a little white space above and below?

You can insert tokens with escapebegin and escapeend. If you don't use mathescape but escapechar you can e.g. switch to displaystyle:

\documentclass{article}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\usepackage{listings}
% #################################################################### COLORS #
\lstset{language=,
keepspaces=true,
basicstyle=\ttfamily,
columns=flexible,
%mathescape=true,
code: OK
\end{lstlisting}

\end{document}


We have to jump off two groups in order \vadjust can act.

• This looks like a solution which could be generalized; however I've never used \aftergroup before! (I had to look it up to see what it meant.) – Alasdair Jan 30 '16 at 0:08
• @Alasdair We have to escape the group due to the math formula and also the box made by listings around the line. – egreg Jan 30 '16 at 0:11