[Tex/LaTex] Problem with underline in listings

listingstext-decorations

I want to underline some code in my source code included using listings. I did the following but the underline is including the white space before the statement. How could I do it so that it only underlines "return 0"?

\lstset{
language=C, 
basicstyle=\ttfamily,
moredelim=[is][\underbar]{_}{_},
}

\begin{lstlisting}
int main() {
  _return 0_;
}
\end{lstlisting}

Best Answer

Use keepspaces=true as part of your listing settings.

enter image description here

\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\begin{document}

\lstset{
  language=C, 
  basicstyle=\ttfamily,
  moredelim=[is][\underbar]{_}{_}
}

\begin{lstlisting}
int main() {
  _return 0_;
}
\end{lstlisting}

\begin{lstlisting}[keepspaces=true]
int main() {
  _return 0_;
}
\end{lstlisting}

\end{document}