1

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}
jub0bs
  • 58,916
Holene
  • 6,920
  • 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? – jub0bs Sep 02 '15 at 07:07
  • I kinda thought just to highlight the asterisk, but I'm open to both solutions :p – Holene Sep 03 '15 at 13:54
  • Also, what should to asterisks that occur elsewhere than at the end of an environment's name? – jub0bs Sep 03 '15 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 – Holene Sep 03 '15 at 15:34

2 Answers2

2

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}

enter image description here

Arash Esbati
  • 7,416
2

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.

enter image description here

\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}
jub0bs
  • 58,916