Search code examples
latextexlistings

latex - escape dollar sign inside lstlisting with [mathescape]


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 $.


Solution

  • 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}