# lstlisting with c++: spaces around scope resolution operator

I am having a hard time to make the output of lstlisting for c++ source look good. Currently, I am stuck with a problem to reduce the amount of space around the scope resolution operator ::. See the following example:

\documentclass{article}
\usepackage{listings}

\lstset{ %
language=C++,
basicstyle=\footnotesize,
captionpos=b,
}

\begin{document}

\begin{lstlisting}
hello::world
\end{lstlisting}

The amount of space \lstinline{is::too} damn high.

\end{document}


The output of this is shown in the picture below, where I marked the spaces that upset me. .

Do you guys know a way to configure this behaviour? I couldn't find something in lstlistings documentation.

-
If you add otherkeywords={::}, then the :: are printed darker as a keyword and even though this does not change the spacing, it does not look as bad. –  Peter Grill Mar 12 '12 at 15:05

## 3 Answers

Add columns=fullflexible, eliminates the spacing:

\documentclass{article}
\usepackage{listings}

\lstset{%
language=C++,
basicstyle=\footnotesize,
captionpos=b,
otherkeywords={::},
%columns=fullflexible
}

\begin{document}

\begin{lstlisting}
hello::world
\end{lstlisting}
\begin{lstlisting}[columns=fullflexible]
hello::world    // columns=fullflexible
\end{lstlisting}

Without \verb|columns=fullflexible| \lstinline{is::too}

With \verb|columns=fullflexible| \lstinline[columns=fullflexible]{is::too}
\end{document}

-

Using literate={<search>}{<replace>}<size> you have replace <search> with <replace> of width <size>:

\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\lstset{
language=C++,
basicstyle=\footnotesize,
captionpos=b
}
\begin{document}
\begin{lstlisting}
hello::world
\end{lstlisting}

\begin{lstlisting}[literate={::}{::}1]
hello::world
\end{lstlisting}
\end{document}


Literate programming is discussed in section 5.4 Literate programming (p 48) of the listings documentation.

-

I beg to differ with the other answers, which are kind of workarounds instead of a solution. Does the way your editor/IDE displays :: not go to your liking? All you need to get the same look is use a monospace font (\ttfamily), which should always be used to display code.

\documentclass{article}

\usepackage{listings}

\lstset{
language=C++,
basicstyle=\footnotesize\ttfamily
}

\begin{document}

\begin{lstlisting}
#include <iostream>

int main()
{
std::cout << "Hello World" << std::endl;
}
\end{lstlisting}

\end{document}


-
No, I am not satisfied with the output. gvim displays everything just fine ;) –  evnu Mar 12 '12 at 22:11
I disagree that code should be typeset in a monospace font. See e.g. the C++ book by Stroustrup. –  Ben Mar 12 '12 at 23:16