[Tex/LaTex] lstlisting: how to underline a keyword

listings

In the following, I am trying to underline the keyword 'true' in a C++ code listing.

\documentclass[11pt]{article}
\usepackage[T1]{fontenc}
\usepackage[lighttt]{lmodern} % bold and italic ttfamily
\usepackage{xcolor}
\usepackage{listings}

\lstset{
    language=C++,
    basicstyle=\ttfamily,
    keywordstyle=\color{blue}\bfseries,
    moredelim=**[is][\underbar]{@}{@}     % <----
}

\begin{document}

\begin{lstlisting}
    int i = foo(@true@);
\end{lstlisting}

\end{document}

What I get is:

enter image description here

If I use [is] instead of **[is], the word 'true' is underlined,
but in this case it is not highlighted as a keyword.

How can I underline a keyword, without loosing its highlighting?

Update 1:

At the same time, I would like to underline words that are not keywords.
For example:

\begin{lstlisting}
    int @i@ = foo(@true@);
\end{lstlisting}

Update 2:

Using \slshape instead of \underbar generates the expected output.

enter image description here

Why does \slshape work and \underbar does not?

Best Answer

Here a workaround in which you should patch \lst@DelimClose and add \underbar within the command

Code

\documentclass[11pt]{article}
\usepackage[T1]{fontenc}
\usepackage[lighttt]{lmodern} % bold and italic ttfamily
\usepackage{xcolor}
\usepackage{listings}

\makeatletter

\def\lst@DelimClose#1#2#3\@empty{%
    \lst@TrackNewLines \underbar{\lst@XPrintToken}\relax
    \lst@DelimPrint{#1#2}{#3}%
    \lst@LeaveMode
    \lst@DelimPrint{#1}{#3}}

\makeatother


\begin{document}

\lstset{
    language=C++,
    basicstyle=\ttfamily,
    keywordstyle=\color{blue}\bfseries,
    keepspaces=true,
    moredelim=**[is]{@}{@},    
    }


\begin{lstlisting}
    int i = foo(@true@);
    @hello@, @and@
\end{lstlisting}

\end{document}