10

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}

enter image description here

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?

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

1 Answer 1

12

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

enter image description here

\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}
2
  • 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, 2013 at 12:50
  • @Ch'enMeng See my edit.
    – jub0bs
    Dec 5, 2013 at 15:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .