Can I use “moredelim” in package “listings” to fetch a regular expression?

2018-10-19 04:59:43

I would like to know if it is possible to use the listings package to highlight regular expressions in order to make them look like a normal string object. Note: The syntax of a regexp is not context free so I cannot expect a solution that recognizes 100% of the cases. Anyhow, in e.g. Ruby I would like to write

(/[a-z]+/)

and tell listings to recognize the regexp /[a-z]+/ by using the left parenthesis (as an anchor point (to make it apart from arithmetic division):

\lstset{moredelim=[s][\color{red}]{(/}{/}}

But, this makes the left parenthesis colored - not only the regexp itself. In order to better understand the parser I modified the statement to:

\lstset{moredelim=[s][\color{red}\textcolor{black}{:macro:}]{(/}{/}}

To my surprise, however, ":macro:" is applied to each of the tokens: (/, [, a, -, z, ], and /, spotted by moredelim. I wrongly expected that ":macro:" would have been applied to the entire matched expression (/[a-z]+/. Which, by the way, is the situ

  • This answer perhaps isn't relevant to the asker anymore. But because this problem was quite harder to solve then it really should have been and may be relevant to others, I'll post the answer anyway.

    As mentioned in the question and comments, the moredelim=**[s] variant treats the whole delimited text as one unit/group, which allows arbitrary text to be inserted at the start of the delimited group and also at the end (through \aftergroup). The problem with that is, other styles are applied on the text between the delimiters, too. On the other hand, moredelim=[s] doesn't apply other styles but in turn applies the delimiter group style to each chunk of characters of the same class (letter, other etc.). This prevents text to be inserted only right before and after the delimiters.

    There doesn't seem to be an easy way to achieve the desired effect, so we have to hook into some internals here. The \lst@DelimOpen and \lst@DelimClose macros control the actions for when a new delimiter pair

    2018-10-19 05:54:02