# Emphasize (color) contents between two delimiters in listings, but not the delimiters themselves

I want to typeset some LaTeX source code by listings. I've tried this:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\lstset{
delim = [s][\ttfamily\color{orange}]{$}{$}
}
\begin{document}
\begin{lstlisting}
\documentclass{article}
\usepackage{amsmath}
\begin{document}
$E = mc^2$
\end{document}
\end{lstlisting}
\end{document}


The equation turns orange. However, the two dollar signs are also highlighted as orange. If I just want contents in the two dollar signs turns orange, what should I do?

• @Jubobs Thx for the output. – Ch'en Meng Dec 1 '13 at 12:39

The following approach is directly adapted from David Carlisle's answer to Maintainable typesetting of placeholders in code snippets:

\documentclass{article}

\usepackage[usenames,dvipsnames]{xcolor}
\usepackage{listings}

\def\beginlstdelim#1#2#3%
{%
\def\endlstdelim{#2\egroup}%
\ttfamily#1\bgroup\color{#3}\aftergroup\endlstdelim%
}
\lstset
{%
moredelim = **[is][\beginlstdelim{\$}{\$}{orange}]{\$}{\$},
moredelim = **[is][\beginlstdelim{\{}{\}}{ForestGreen}]{\{}{\}},
moredelim = **[is][\beginlstdelim{[}{]}{red}]{[}{]},
}

\begin{document}
\begin{lstlisting}
\documentclass{article}
\usepackage{amsmath}
\begin{document}
$E = mc^2$
{E = mc^2}
[E = mc^2]
\end{document}
\end{lstlisting}
\end{document}

• I test it, and it works. Thanks! However, is there any more general solution that could handle other delimiters such as {} or ? – Ch'en Meng Dec 1 '13 at 12:50
• @Ch'enMeng See my edit. – jub0bs Dec 5 '13 at 15:19