latex - escape dollar sign inside lstlisting with [mathescape]

Johannes picture Johannes · Nov 23, 2015 · Viewed 7.2k times · Source

I have a problem escaping the dollar sign in an mathescaped lstlisting environment

\begin{lstlisting}[mathescape]
  $\delta$(Z, $\varepsilon$, $S) = (R, $\varepsilon$)
                             ^ 
\end{lstlisting}

With the help of an answer of a related question I got the idea to use another sign instead of the dollar sign like this:

\lstset{
  literate={\§}{{\textcolor{black}{\$}}}1
}

But when I used inside the listing I got \$ instead of $.

Answer

Werner picture Werner · Nov 24, 2015

You can use \$ within math-mode (under mathescape) or \mbox{\textdollar}:

enter image description here

\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[basicstyle=\ttfamily, mathescape]
$\delta$(Z, $\varepsilon$, $\mbox{\textdollar}$S) = (R, $\varepsilon$)
$\delta$(Z, $\varepsilon$, $\$$S) = (R, $\varepsilon$)
\end{lstlisting}
\end{document}