[Tex/LaTex] LaTeX – lstinline

listings

I want to include a short code snippet using the listings package. I have already chosen the parameters for \lstset and my C++ code looks nice with these setttings.

For an inline code snippet I try to use the \lstinline command. But when trying something like this:

\lstinline$#define EXAMPLE$

the output is like this: 
# 
define

EXAMPLE

instead of this:
#define EXAMPLE

I made a minimal version and could see that it is because of \singlespacing in my \lstset settings. How can I fix this without losing the \singlespacing command?

minimal version:

\documentclass[a4paper,oneside,12pt,2.1headlines]{scrreprt}

\usepackage{setspace}
\usepackage{listings}

\lstset{
  basicstyle=\singlespacing
}

\begin{document}

  \lstinline$#define EXAMPLE$

\end{document}

Best Answer

The basicstyle is applied at every line beginning. So, you're calling \singlespacing at each line.

Let's try to write a minimal file, with no listings, but intermixing the command \singlespacing with every line. Something like

Mary had a little lamb%
\singlespace%
and his fur was white as%
\singlespace%
snow.

You'll realize the command is skipping a line every time it's launched. Let's look at the setspace code, in kpsewhich setspace.sty:

\newcommand{\setstretch}[1]{%
  \def\baselinestretch{#1}%
  \@currsize
}

\newcommand{\SetSinglespace}[1]{%
  \def\setspace@singlespace{#1}%
}

% Here's the default single line spacing value.
\SetSinglespace{1}

\newcommand{\singlespacing}{%
  \setstretch {\setspace@singlespace}%  normally 1
  \vskip \baselineskip  % Correction for coming into singlespace
}

Look at the last line: ... guilty as charged. Let's now do what it does, without the "correction for coming into singlespace":

\documentclass[a4paper,oneside,12pt,2.1headlines]{scrreprt}

\usepackage{setspace}
\usepackage{listings}


\newcommand{\mysinglespacing}{%
  \setstretch{1}% no correction afterwards
}

\lstset{
  basicstyle=\mysinglespacing,
  breaklines=no
}

\begin{document}

\lstinline$#define EXAMPLE$

\end{document}

VoilĂ  !