[Tex/LaTex] How to highlight \[…\] properly in LaTeX listings

delimiterslistings

The listings package provides the option moredelim, allowing for custom styles for words enclosed by given delimiters. I would like to give $...$, \[...\] and $$...$$ custom colors. \[...\], however, doesn't seem to work well. MWE:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\lstset{language=[LaTeX]TeX,
basicstyle=\ttfamily,%
commentstyle=\slshape\color{blue},%
texcsstyle=*\bfseries,%
delim=[s][\color{purple}]{$}{$},%
moredelim=[s][\color{purple}]{\[}{\]},%
moredelim=[s][\color{purple}]{$$}{$$},%
moredelim=[is][\slshape\color{violet}]{@@}{@@}}

\begin{document}
\begin{lstlisting}
\begin[@@opt_par@@]{@@obl_par@@}
    bla
\end{x}
\[math mode\]
$$math mode$$
\end{lstlisting}
\end{document}

This results in:

result

I would like to put \[...\] fully in color, without interfering [...]s. The optional parameter opt_par should appear just as obl_par (again, [...] seems to be problematic). I have tried several variations of moredelim, to no avail.

Best Answer

The problem is that the texcsstyle key modifies the way listings processes backslash characters. Actually, because the font you're using (LaTeX's default font, Computer Modern) doesn't come with a boldface typewriter version,

texcsstyle=*\bfseries,

has no effect on the style of your listings. If you can afford not to customise the style of control sequences (e.g. \begin), just don't use thetexcsstyle key at all, and you should be able to highlight \[...\] as you want.

Also, note that, in the definition of delimiters, you need to escape backslash characters:

moredelim = [s][\color{purple}]{\\[}{\\]},

For more details about which characters must be escaped in values passed to listings keys, see subsection 4.1 of the listings manual:

If you want to enter one of the special characters {}#%\, this character must be escaped with a backslash. This means that you must write \} for the single character 'right brace'—but of course not for the closing paramater character.

enter image description here

\documentclass{article}

\usepackage{listings}
\usepackage{xcolor}

\lstset{
    language     = [LaTeX]TeX,
    basicstyle   = \ttfamily,%
    commentstyle = \slshape\color{blue},
    delim        = [s][\color{purple}]{$}{$},
    moredelim    = [s][\color{purple}]{\\[}{\\]},
    moredelim    = [s][\color{purple}]{$$}{$$},
    moredelim    = [is][\slshape\color{violet}]{@@}{@@},
}

\begin{document}
\begin{lstlisting}
\begin[@@opt_par@@]{@@obl_par@@}
    bla $x_1$
\end{x}
\[math mode\]
$$math mode$$
\end{lstlisting}
\end{document}