[Tex/LaTex] How to use mathematical symbols in verbatim mode

verbatim

How can I get mathematical symbols in verbatim mode? If I use them, for example \equiv, it is just reproduced as is in the pdf.

Best Answer

You can use alltt, fancyvrb or listings package for this purpose.

For fancyvrb, see manual "4.1.16 Catcode characters". Example:

\begin{Verbatim}[commandchars=\\\{\},
  codes={\catcode‘$=3\catcode‘^=7}]
x=1/sqrt(z**2) ! $\frac{1}{\sqrt{z^2}}$
\end{Verbatim}

It is easier to use listings package, see manual "4.14 Escaping to LaTeX". Example:

\begin{lstlisting}[mathescape]
// calculate $a_{ij}$
$a_{ij} = a_{jj}/a_{ij}$;
\end{lstlisting}