[Tex/LaTex] Listings, keywords with backslash in them

listings

This probably have an answer on here somewhere…

Here is an MWE:

\documentclass[a4paper]{memoir}
\usepackage{listings}
\usepackage[svgnames,dvipsnames]{xcolor}
\colorlet{level1}{red}
\lstset{
  basicstyle=\small\ttfamily,
  keywordstyle=\bfseries\color{level1},
  alsoletter={\\},
}
\begin{document}
\lstset{
  morekeywords={\\bigl,\\bigr}
}

\begin{lstlisting}
$\bigl(\sqrt{x^2}\bigr)$
\end{lstlisting}

\begin{lstlisting}
$ \bigl(\sqrt{x^2}\bigr)$
\end{lstlisting}

\end{document}

Why do I need a space in order to get a red \bigl?

enter image description here

Best Answer

The math shift is also a letter, so listings see the "keyword" $\bigl. You could add alsoother={$}.

Edit

Probably a better way is to define an own language:

\documentclass[a4paper]{memoir}
\usepackage{listings}
\usepackage[svgnames,dvipsnames]{xcolor}
\colorlet{level1}{red}

\lstdefinelanguage{daleif}{%
 moretexcs={bigr}}%default keywords
[keywords,tex,comments] %aspects

\lstset{
  language=daleif,
  basicstyle=\small\ttfamily,
  texcsstyle=*\bfseries\color{level1},
  }
\begin{document}

\begin{lstlisting}
$\bigr\bigl\def$
\end{lstlisting}

\begin{lstlisting}[moretexcs={bigl}]
$\bigr\bigl\def$
\end{lstlisting}


\begin{lstlisting}
$\bigr\bigl\def$
\end{lstlisting}


\end{document}