[Tex/LaTex] Make lstlisting honour baselinestretch

line-spacinglistings

I have to use lstlisting instead of Verbatim in a particular case, because math escape doesn't work properly with the latter. I managed to have both look the same, but lstlisting ignores my baselinestretch settings, so the line spacing is too big:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{fancyvrb}
\usepackage{listings}
\usepackage[scaled=.73]{beramono}
\fvset{baselinestretch=0.94}
\lstdefinelanguage{scala}{
  morekeywords={type}%
}
\lstset{
  language=scala,%
% baselinestretch=0.94,% keyword doesn't exist
  basicstyle=\ttfamily,%
  fancyvrb=true,%
  mathescape=true,%
}

\begin{document}

\begin{lstlisting}
type Vertex = ($\mathit{lb}_\mathsf{pre}$: Label, $\mathit{lb}_\mathsf{post}$: Label)
Next Line
Next Line
\end{lstlisting}

\begin{Verbatim}
type Vertex = ($\mathit{lb}_\mathsf{pre}$: Label, $\mathit{lb}_\mathsf{post}$: Label)
Next Line
Next Line
\end{Verbatim}

\end{document}

You can see the different line spacing here:

enter image description here

The difference is not that big, but it makes a huge impact on long listings. What is the best way to apply the base line stretching to lstlisting?

Best Answer

Use basicstyle=\linespread{0.94}\ttfamily

As the following example shows, the lines are spaced exactly in the same way

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{fancyvrb}
\usepackage{listings}
\usepackage[scaled=.73]{beramono}
\fvset{baselinestretch=.94}
\lstdefinelanguage{scala}{
  morekeywords={type}
}
\lstset{
  language=scala,
  basicstyle=\linespread{.94}\ttfamily,
  fancyvrb=true,
  mathescape=true,
}

\begin{document}

\begin{lstlisting}
type Vertex = ($\mathit{lb}_\mathsf{pre}$: Label, $\mathit{lb}_\mathsf{post}$: Label)
Next Line
Next Line
\end{lstlisting}

\kern-50pt % back up to see that the lines are equally spaced

\begin{Verbatim}
type Vertex = ($\mathit{lb}_\mathsf{pre}$: Label, $\mathit{lb}_\mathsf{post}$: Label)
Next Line
Next Line
\end{Verbatim}

\end{document}

enter image description here