1

In my language, I use the dash character - in three different contexts.

  1. As an operator, e.g., 5 - 1.
  2. As a minus sign, e.g., -10.
  3. 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.

naive

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.

workaround

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.

Safron
  • 360
  • 1
  • 9
  • Your some-keyword isn't highlighted even if you use alsoletter=- because your language setup uses other-keyword (which isn't the same). – Skillmon Dec 08 '21 at 16:16

1 Answers1

2

By using alsoletter={-} the - is considered a letter. This way things like -1 (or any number) become an unknown keyword, so aren't highlighted as a single keyword. Also, this way it can be used in the middle of another keyword you want to define with morekeywords:

\documentclass{article}

\usepackage{listings} \usepackage{xcolor}

\lstdefinelanguage{MyLang}{ alsoletter={-}, keywords={-}, % operators otherkeywords={+}, keywords=[2]{akeyword,some-keyword}, % keywords }

\lstset{ keywordstyle=[1]\color{magenta}, % operators keywordstyle=[2]{\color{violet}}, % keywords language=MyLang }

\begin{document}

\begin{lstlisting} 5 - 1 + -10 akeyword some-keyword \end{lstlisting}

\end{document}

Caveat: In 5-1 the - will not be highlighted as a binary operator (you need spaces).

Output:

enter image description here

Skillmon
  • 60,462
  • Wow, and now that I added this answer I read the last part of your question and see you already considered alsoletter... Well, here is how you should use it! – Skillmon Dec 08 '21 at 16:15