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 situation if I change the statement to its double-starred version:
\lstset{moredelim=**[s][\color{red}\textcolor{black}{:macro:}]{(/}{/}}
But, in this case the regexp will be parsed by listings
- coloring keywords inside the expression. This is not what I want. I want to use (
only as an anchor to find the regexp, afterwards I want to treat the anchor separately from the regexp itself (giving it a different color).
To be specific: I want to know if I can pick up only the first token in moredelim
- containing the (/
- and treat this separately from the other tokens.
An MWE for examining the issue is provided here:
\documentclass{article}
\usepackage[english]{babel}
\usepackage{listings}
\usepackage{xcolor}
\lstnewenvironment{lstRuby}{
\lstset{
language={},
moredelim=[s][\color{red}\textcolor{black}{:macro:}]{(/}{/}
}
}{}
\begin{document}
\setlength{\parindent}{0pt}
\ttfamily
This is the code:
(/[a-z]+/)
This is what I want to achieve:
(\textcolor{red}{/[a-z]+/})
This is what I get using listings:
\begin{lstRuby}
(/[a-z]+/)
\end{lstRuby}
\end{document}
listings
cannot be used for context dependent coloring so I would like to use a(
or a,
as an anchor for the regexp. But, I cannot find a way of controlling the color of the anchor! – Tore H-W Feb 22 '15 at 21:50moredelim=**[][]{}
causes string parsing inside the regexp, thereby forcing keyword substitution inside it. I do not want that so I tried to usemoredelim=[][]{}
but in this case I do not get hold of the entire string - my macro is called on every (sub)token identified bylistings
. – Tore H-W Feb 23 '15 at 8:30