In my language, I use the dash character - in three different contexts.
- As an operator, e.g.,
5 - 1. - As a minus sign, e.g.,
-10. - As part of a keyword, e.g.,
some-keyword.
I would like to have a different style for each of these. Is this possible?
What I tried so far. Let me start from the most naive minimal example.
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\lstdefinelanguage{MyLang}{
keywords={},
otherkeywords={+,-}, % operators
morekeywords=[2]{akeyword, other-keyword}, % keywords
}
\lstset{
keywordstyle=\color{magenta}, % operators
keywordstyle=[2]{\color{violet}}, % keywords
language=MyLang
}
\begin{document}
\begin{lstlisting}
5 - 1 + -10 akeyword some-keyword
\end{lstlisting}
\end{document}
This results in all dashes being styled as an operator. However, I would like the second dash to be rendered black, and the third one purple. Note that the keyword containing a dash is not recognized at all.
For the minus sign, I found a workaround using the literate option of listings. For example, by adding literate={_}{\textminus}1, to the language definition, I can rewrite the example program as 5 - 1 + _10 akeyword some-keyword which results in the following.
Of course, this is not ideal, because I have to replace each minus sign with an underscore manually, but in my case I find this acceptable. Still, bonus points if there is a solution for this. :)
For the keyword, I understood from this answer that adding alsoletter=-, should do the trick, but this does not seem to work.



some-keywordisn't highlighted even if you usealsoletter=-because your language setup usesother-keyword(which isn't the same). – Skillmon Dec 08 '21 at 16:16