[Tex/LaTex] Listings with keywords that contain both letters and numbers

highlightinglistings

I have a listing which needs to highlight keywords with both letters and numbers. Following the advice in this question I've used the otherkeywords to define the keywords which contain numbers. This works for keywords which contain only letters (e.g. FOO) and keywords which contain only numbers (e.g. 1234) but not those that contain both (e.g. 1234FOO).

Here is an example document:

\documentclass[12pt]{article}

\usepackage{xcolor}
\usepackage{listings}

\renewcommand{\ttdefault}{pcr}

\definecolor{Black}{gray}{0.0}
\definecolor{Blue}{rgb}{0.12,0.29,0.53}

\lstset{
  basicstyle=\color{Black}\ttfamily, %
  keywordstyle=[1]\color{Blue}\ttfamily\bfseries, %
}

\lstdefinelanguage{mylang}{ %
  keywords={FOO,BAR,BAZ,ARG}, %
  otherkeywords={1234,XYZ1234,XYZ1234HelloWorld}, %
}

\begin{document}
\begin{lstlisting}[numbers=none,breaklines=true,caption={},language=mylang]
FOO
BAR
BAZ
ARG
1234
XYZ1234
XYZ1234HelloWorld
\end{lstlisting}
\end{document}

The resulting PDF looks like this:

PDF generated from the LaTeX above

In this example the keywords XYZ1234 and XYZ1234HelloWorld should be highlighted, but the first three letters (XYZ) are not styled consistently with the rest of the keyword. How can I change the language definition to make the highlighting consistent?

Best Answer

The easiest thing to do here is to declare all digits as "letters" and define all your keywords with the keywords key alone, eschewing the otherkeywords key completely:

enter image description here

\documentclass[12pt]{article}

\usepackage{xcolor}
\usepackage{listings}

\renewcommand{\ttdefault}{pcr}

\definecolor{Black}{gray}{0.0}
\definecolor{Blue}{rgb}{0.12,0.29,0.53}

\lstset{
  basicstyle=\color{Black}\ttfamily, %
  keywordstyle=[1]\color{Blue}\ttfamily\bfseries, %
}

\lstdefinelanguage{mylang}{ %
  alsoletter=0123456789,
  keywords={FOO,BAR,BAZ,ARG,1234,XYZ1234,XYZ1234HelloWorld}, %
}

\begin{document}
\begin{lstlisting}[numbers=none,breaklines=true,caption={},language=mylang]
FOO
BAR
BAZ
ARG
1234
XYZ1234
XYZ1234HelloWorld
\end{lstlisting}
\end{document}