5

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}

result

How can I solve this problem?

2
  • 7 should be underlined?
    – user31729
    Commented Oct 6, 2015 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 :)
    – user77461
    Commented Oct 6, 2015 at 20:30

1 Answer 1

4

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}

enter image description here

3
  • 2
    This may change the spacing of the identifiers being underlined, when compared to those not underlined.
    – Werner
    Commented Oct 6, 2015 at 20:30
  • @Werner: Thanks. Any suggestions to cure this?
    – user31729
    Commented Oct 6, 2015 at 20:42
  • This question solves it, but it turns off any other highlighting you might expect within the delimiters: tex.stackexchange.com/questions/169612/… Commented Feb 3 at 13:01

You must log in to answer this question.