Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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}
share|improve this answer
1  
That works great, thanks! –  snim2 Aug 25 at 14:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.