# Listings: text highlighting based on prefix

How can I apply different styles to keywords depending on their prefix?

Here is some sample code:

(-2,0,0) (2,1,1) op-registerbox !box1
;box1 /Blue op-setproperties


I'd like to typeset

1. words starting with ! and ; in color red,
2. words starting with / in color green,
3. words starting with cp- in bold.

So far, this is what I've got:

\lstdefinelanguage{XX}
{
basicstyle=\small\sffamily\fontseries{c},
emphstyle=\underbar,
keywordsprefix=[2]{/},
alsoletter={/},
keywordstyle=\textbf,
keywordstyle=[2]\color{green},
morekeywords={op,registerbox, ...},
morestring=[b][\color{green}]",
columns=flexible,
escapechar=\%,
numbersep=6pt,
numberstyle=\scriptsize
}


I'm aware that only one keywordsprefix can be defined at the moment: specifying more than one class of prefix (keywordsprefix=[2]{/}) is currently not supported. I'd like to avoid having to list all the words that match my description into morekeywords. Is that possible? How?

Here is one way of doing it using moredelim. I assumed you meant words starting with op-, not words starting with cp-. I didn't use keywordsprefix because it currently only allows for one prefix "class", and the listings documentation (v1.5b) still considers it a buggy feature; see subsection 4.18 about that.

Remember to load lmodern if you want some stuff to be typeset in bold typewriter font.

\documentclass{article}

\usepackage[dvipsnames]{xcolor}
\usepackage{lmodern}
\usepackage{listings}

\lstdefinelanguage{XX}
{
basicstyle=\small\sffamily\fontseries{c},
morestring=[b][\color{green}]",
%
moredelim=[s][\color{red}]{!}{\ },
moredelim=[s][\color{red}]{;}{\ },
moredelim=[s][\color{ForestGreen}]{/}{\ },
moredelim=[s][\bfseries]{op-}{\ },
%
columns=flexible,
escapechar=\%,
numbersep=6pt,
numberstyle=\scriptsize
}

\begin{document}

\begin{lstlisting}[language=XX]
(-2,0,0) (2,1,1) op-registerbox !box1
;box1 /Blue op-setproperties
\end{lstlisting}

\end{document}

• +1: Neat trick to use a space (\ ) as terminating delimiter! Jan 13 '14 at 19:32
• @Daniel Thanks ;p Please see this somewhat related question of mine: tex.stackexchange.com/questions/153896/… Jan 13 '14 at 19:35