# Listings, keywords with backslash in them

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?

• The math shift is also a letter, so listings see the "keyword" $\bigl. You could add alsoother={$} – Ulrike Fischer Mar 5 '15 at 22:18
• Nice one thanks. Write an answer if you like. – daleif Mar 5 '15 at 22:20

## 1 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}

• Are there other caveats one need to keep a look at? I'm displaying LaTeX code, but is not declaring LaTeX as a language. I just want to use morekeywords to specify which parts to highlight in a given lstlisting. – daleif Mar 6 '15 at 12:09
• Well you will get problems if you write keywords without separation \bigr\bigl will no be recogized. – Ulrike Fischer Mar 6 '15 at 12:27
• I've noticed. Seams it is easier to load LaTeX, reset the keywords lists, and use texcs and moretexcs locally. – daleif Mar 6 '15 at 12:35
• Hmm, that is not that stable either... – daleif Mar 6 '15 at 12:40
• I don't know what you mean with "not stable". But I guess your main goal it to color the backslashes right? I think I had once some code but I will have to look. – Ulrike Fischer Mar 6 '15 at 12:46