# Underline in lstlisting environment

I would like to get the same result I get with \underline in a lstlisting environment.

I was almost sure I got it in this way:

\documentclass{article}

\usepackage{listings}
\usepackage{upquote}

\lstdefinestyle{myStyle}{
language=SQL,
basicstyle=\small\ttfamily,
moredelim=[is][\underbar]{_}{_},
keepspaces=true
}

\begin{document}

\begin{lstlisting}[style=myStyle]
SELECT * FROM usr WHERE _id = 7_
\end{lstlisting}

\end{document}


but when I use the _ delimiter between '' it doesn't work:

\documentclass{article}

\usepackage{listings}
\usepackage{upquote}

\lstdefinestyle{myStyle}{
language=SQL,
basicstyle=\small\ttfamily,
moredelim=[is][\underbar]{_}{_},
keepspaces=true
}

\begin{document}

\begin{lstlisting}[style=myStyle]
SELECT * FROM usr WHERE id ='_7_'
\end{lstlisting}

\end{document}


How can I solve this problem?

• 7 should be underlined? – user31729 Oct 6 '15 at 20:14
• Yes. In particular I would like to underline words bewteen ''. For instance, my code doesn't work with var = '_something_' but it works with var = _'something'_. However, your answer solves this problem. Thanks :) – BlackBrain Oct 6 '15 at 20:30

There might be easier approaches, but since lstlisting is a verbatim environment, \underline does not work this way (as any other command would fail too). It's necessary to escape to LaTeX with a user defined escapechar, I chose % for this

\documentclass{article}

\usepackage{listings}
\usepackage{upquote}

\lstdefinestyle{myStyle}{
language=SQL,
basicstyle=\small\ttfamily,
moredelim=[is][\underbar]{_}{_},
keepspaces=true
}

\begin{document}

\begin{lstlisting}[style=myStyle,escapechar=\%]
SELECT * FROM usr WHERE %\underline{id} = \underline{7}%
\end{lstlisting}

\end{document}


• This may change the spacing of the identifiers being underlined, when compared to those not underlined. – Werner Oct 6 '15 at 20:30
• @Werner: Thanks. Any suggestions to cure this? – user31729 Oct 6 '15 at 20:42