7

my listings are syntax highlighted using \lstset with escapechar=$ and commentstyle=\color[rgb]{0,0.5,0}. Now my C-code looks like int16_t speed; // calculated speed in $\(\frac{cm}{s}\)$ and the comment is printed green except the math-part:

math no color

How do I apply the color on the escaped math-part?

Thank in advance

9

You have to add the color specification also in the formula:

$\color{lstgreen}\(\frac{cm}{s}\)$

Complete example (please, try to include complete examples in questions):

\documentclass[11pt,a4paper]{article}
\usepackage{xcolor}
\usepackage{listings}

% color definition
\definecolor{lstgreen}{rgb}{0,0.5,0}

\lstset{escapechar=$, %$
keywordstyle=\color{blue}\ttfamily,
commentstyle=\color{lstgreen}\ttfamily,
basicstyle=\ttfamily,
language=C,
morekeywords={int16_t}
}

\begin{document}

\begin{lstlisting}
int16_t speed; // calculated speed in $\color{lstgreen}\(\frac{cm}{s}\)$
int16_t something_else;
\end{lstlisting}
\end{document}

The result:

enter image description here

0
4

Sometimes there are many pieces of escaped LaTeX which should be colored (using the same color). In this case I think using escapebegin=\color{...} in \lstset might be useful, as you do not have to repeat the color in the every piece of escaped code.

This way the example by Claudio Fiandrino could be written like this:

\documentclass[11pt,a4paper]{article}
\usepackage{xcolor}
\usepackage{listings}

% color definition
\definecolor{lstgreen}{rgb}{0,0.5,0}

\lstset{escapechar=$, %$
keywordstyle=\color{blue}\ttfamily,
commentstyle=\color{lstgreen}\ttfamily,
escapebegin=\color{lstgreen},
basicstyle=\ttfamily,
language=C,
morekeywords={int16_t}
}

\begin{document}

\begin{lstlisting}
int16_t speed; // calculated speed in $\(\frac{cm}{s}\)$
int16_t something_else;
\end{lstlisting}    
\end{document}

(the result should look the same)

This does also work for math that is escaped using mathescape=true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.