# Highlight asterisk in lstlisting

I would like to emphasise the asterisk used in \begin{equation*} in lstlisting. I have tried using emph, also including the alsoletter macro, but it doesn't work. Why not?

\documentclass{article}

\usepackage{listings,xcolor}

\begin{document}
\begin{lstlisting}[alsoletter={*},emph={*},emphstyle={\color{red}}]
% \usepackage{mhchem}

\begin{equation*}
\label{eq:chem}
\ce{CaCO3(s) <=>[H2O]
Ca2+(aq) + CO3^{2-}(aq)}
\end{equation*}
%
Some text
\end{lstlisting}
\end{document}

• The best approach depends on what you want. Do you want to highlight "equation" in the same style as the asterisk? Or should the asterisk have its own style? Sep 2, 2015 at 7:07
• I kinda thought just to highlight the asterisk, but I'm open to both solutions :p Sep 3, 2015 at 13:54
• Also, what should to asterisks that occur elsewhere than at the end of an environment's name? Sep 3, 2015 at 14:15
• Good question. My point is to emphasise the asterisks to make an unnumbered equation. My needs right now doesn't have other asterisks, but for a not-so-localised answer it would be nice to be able to have normal asterisks in the rest of the code Sep 3, 2015 at 15:34

There is no really robust way of doing that in listings. Declaring * as a letter will break highlighting of keywords that are immediately preceded or followed by * (e.g. int*). Here, I would abuse the literate key; see below.

For information, the test in my \processAsterisk macro is a hacky way of highlighting asterisks only in listings' "normal" mode, not within strings, comments, and other delimited stuff.

\documentclass{article}

\usepackage{listings}
\usepackage{xcolor}

\makeatletter
\newcommand\processAsterisk{%
\ifnum\lst@mode=\lst@Pmode\relax%
\textcolor{red}{*}%
\else
*%
\fi
}
\makeatother

\lstset{
basicstyle=\ttfamily,
literate={*}{\processAsterisk}1,
morecomment=[l]\%,
}

\begin{document}
\begin{lstlisting}
% \usepackage{mhchem}

\begin{equation*}
\label{eq:chem}
\ce{CaCO3(s) <=>[H2O]
Ca2+(aq) + CO3^{2-}(aq)} % 2 * 2 == 4
\end{equation*}
%
Some text
\end{lstlisting}
\end{document}


Another approach could be with moredelim key:

\documentclass{article}

\usepackage{listings,color}
\lstset{basicstyle=\ttfamily}
\lstdefinestyle{star}{%
moredelim=[is][\itshape\color{red}]{|}{|}}

\begin{document}

\begin{lstlisting}[style=star]
% \usepackage{mhchem}

\begin{equation|*|}
\label{eq:chem}
\ce{CaCO3(s) <=>[H2O]
Ca2+(aq) + CO3^{2-}(aq)}
\end{equation|*|}
%
Some text
\end{lstlisting}

\end{document}