[Tex/LaTex] lstlisting: color LaTeX commands like `\\` or `\!`

listings

How can I achieve it with lstlisting, that LaTeX commands like \\ or \! are properly highlighted as syntax?
Adding those commands (with or without backslash) to moretexcs does not deliver the indented result.

\documentclass{scrartcl}

\usepackage{fontspec}

\usepackage{listings}
\usepackage{xcolor}

\lstset{
  language=[LaTeX]TeX,
  basicstyle=\ttfamily,
  texcsstyle=*\color{cyan},
  moretexcs={!},
}


\begin{document}
\begin{lstlisting}
\begin{equation}
  \left(\frac{1}{2}\right)^{\! 2}
\end{equation}
\end{lstlisting}
\end{document}

Best Answer

You can use literate option to replace desired commands with highlighted ones.

Problem is that, when you use starred texcsstyle option, code added to SelectCharTable hook, by tex aspect (p.152 of listings developers guide), partially overrides code used by literate option (p. 137).

If you want listings to properly use literate replacement, you need to "rehook" code used by literate, after loading tex aspect.

\documentclass{scrartcl}

\usepackage{fontspec}

\usepackage{listings}
\usepackage{xcolor}


\lstset{
  language=[LaTeX]TeX,
  basicstyle=\ttfamily,
  texcsstyle=*\color{cyan},
  literate=*%
    {\\!}{{\textcolor{cyan}{\textbackslash{}!}}}2
    {\\\\}{{\textcolor{cyan}{\textbackslash{}\textbackslash{}}}}2,
}

% "Rehook" literate char table.
\makeatletter
\lst@AddToHook{SelectCharTable}
    {\ifx\lst@literate\@empty\else
         \expandafter\lst@Literate\lst@literate{}\relax\z@
     \fi}
\makeatother


\begin{document}

\begin{lstlisting}
\begin{equation}
  \left(\frac{1}{2}\right)^{\! 2}
  \gamma!
  \\!
  \\left
\end{equation}
\end{lstlisting}

\end{document}

pdf screen shot

Of course you can add all replacements, as in Ismo's answer, just without ยกs at the beginning.