[Tex/LaTex] Listings package : Increase spacing between = in ==

listingsspacing

Everything is in the title. The minimal example below

\documentclass[a4paper,11pt]{article}

\usepackage{listings}
\usepackage{xcolor}

% set the default code style
\lstset{
    frame=tb, % draw a frame at the top and bottom of the code block
    tabsize=4, % tab space width
    showstringspaces=false, % don't mark spaces in strings
    numbers=left, % display line numbers on the left
    commentstyle=\color{green}, % comment color
    keywordstyle=\color{blue}, % keyword color
    stringstyle=\color{blue!60} % string color
}


\begin{document}
\begin{lstlisting}[language=C++,breaklines]
#include <iostream>
using namespace std;

int main() {
  int a = 1;
  if ( a == 1 )
    cout << "Hello world" << endl; 
  return 0;
}
\end{lstlisting}

\end{document}

produces the following output

Minimal example showing the == output

I find the spacing between = in the == operator too small. Therefore I would like to increase it. How can I do that ?

Thanks!

Best Answer

You have to increase the “base width”, since = is wider than the default 0.6em. If we do a measurement, we find that 0.6em for the standard font is about 6.57pt, whereas the width of the “=” glyph is about 8.52pt (but it has side bearings). So a base width of 0.8em seems necessary.

\documentclass[a4paper,11pt]{article}

\usepackage{listings}
\usepackage{xcolor}

% set the default code style
\lstset{
    frame=tb, % draw a frame at the top and bottom of the code block
    tabsize=4, % tab space width
    showstringspaces=false, % don't mark spaces in strings
    numbers=left, % display line numbers on the left
    commentstyle=\color{green}, % comment color
    keywordstyle=\color{blue}, % keyword color
    stringstyle=\color{blue!60}, % string color
    basewidth=0.8em,
}


\begin{document}

\begin{lstlisting}[language=C++,breaklines]
#include <iostream>
using namespace std;

int main() {
  int a = 1;
  if ( a == 1 )
    cout << "Hello world" << endl; 
  return 0;
}
\end{lstlisting}

\end{document}

enter image description here

I'd much prefer basicstyle=\ttfamily, though.

\documentclass[a4paper,11pt]{article}

\usepackage{listings}
\usepackage{xcolor}

% set the default code style
\lstset{
    frame=tb, % draw a frame at the top and bottom of the code block
    tabsize=4, % tab space width
    showstringspaces=false, % don't mark spaces in strings
    numbers=left, % display line numbers on the left
    commentstyle=\color{green}, % comment color
    keywordstyle=\color{blue}, % keyword color
    stringstyle=\color{blue!60}, % string color
    columns=fullflexible,
    basicstyle=\ttfamily,
}


\begin{document}

\begin{lstlisting}[language=C++,breaklines]
#include <iostream>
using namespace std;

int main() {
  int a = 1;
  if ( a == 1 )
    cout << "Hello world" << endl; 
  return 0;
}
\end{lstlisting}

\end{document}

enter image description here

Related Question