6

I am using listings to display custom keywords in bold. In my listings, those keywords are sometimes followed by a comma. However, in the example below, any comma following a keyword will prevent the keyword from being recognized.

Rendering of the code below

How can I make listings recognize CustomKeyword and if as keywords, even when they're immdiately followed by a comma ?

\usepackage{lstlistings}

\lstdefinelanguage{csharp}{
  alsoletter={@,=,>,},
  morekeywords={return, if, is, int, CustomKeyword, else, or, bool},
  sensitive=true,
  morecomment=[l]{//},
  morecomment=[s]{/*}{*/},
  morestring=[b]"
}

\lstset{
  language=csharp,
  showstringspaces=false,
  columns=spaceflexible,%fullflexible,
  mathescape=true,
  numbers=none,
  numberstyle=\tiny,
  basicstyle=\codestyle
} 

\begin{lstlisting}[columns=fullflexible]
CustomKeyword  // OK in bold.
CustomKeyword, // Not in bold anymore.
if //OK in bold
if, // Not in bold anymore
\end{lstlisting}
jub0bs
  • 58,916

1 Answers1

5

The problematic line is

alsoletter={@,=,>,},

You shouldn't use commas to delimit the characters you want to declare as "letters". If you do, listings takes those commas literally and declares the comma itself as a "letter"; as a result, listings treats if, as an identifier distinct from if.

Correct alsoletter syntaxes include

alsoletter={@=>},

and even (much less readable!)

alsoletter=@=>,

(Note that the comma at the end of that line is simply interpreted as a delimiter for listings key-value pairs, not as a character declared as "letter".)

enter image description here

\documentclass{article}

\usepackage{listings}

\lstdefinelanguage{csharp}{
  alsoletter={@=>},
  morekeywords={return, if, is, int, CustomKeyword, else, or, bool},
  sensitive=true,
  morecomment=[l]{//},
  morecomment=[s]{/*}{*/},
  morestring=[b]",
}

\lstset{
  language=csharp,
  showstringspaces=false,
  columns=spaceflexible,%fullflexible,
  mathescape=true,
  numbers=none,
  numberstyle=\tiny,
} 

\begin{document}
\begin{lstlisting}[columns=fullflexible]
CustomKeyword  // OK in bold.
CustomKeyword, // in bold too :)
if //OK in bold
if, // in bold too
\end{lstlisting}
\end{document}
jub0bs
  • 58,916