Basically I have a section that is describing my algorithm in a pseudo code kind of way, and so I want that text to look like the verbatim text except I still want to be able to use math symbols. Is there any way to do this? Or any other hacky way to get the result?
Asked
Active
Viewed 4.9k times
28
2 Answers
24
listings provides a mathescape option to escape to LaTeX within math mode (between $...$). There are other escapable options as well, details of which are contained within the listings documentation (section 4.14 Escaping to LaTeX, p 39).
Here is a quick example:

\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\lstset{
basicstyle=\ttfamily,
mathescape
}
\begin{document}
Here is some text.
\begin{lstlisting}
Some verbatim text and $f(x)=ax^2+bx+c$.
\end{lstlisting}
Here is some more text.
\begin{verbatim}
Some verbatim text and $f(x)=ax^2+bx+c$.
\end{verbatim}
Some final text.
\end{document}
Werner
- 603,163
-
1oh werner, this worked perfectly. thanks for the full answer, i have a deadline in 10 hours and ive been using latex only for an hour! thank you!! – garciaj Dec 12 '13 at 20:02
-
1@garciaj then I think it's not worth it using Latex, unless it's (relatively) simple. – Manuel Dec 12 '13 at 22:15
-
@Manuel, Its definitely worth using Latex, it is THE best thing ive come across lately! and half my essay is filled with equations so couldnt have done it without it – garciaj Dec 12 '13 at 23:18
-
3@garciaj Now it's the moment. But 10 hours before a deadline… it's not the optimum time. – Manuel Dec 13 '13 at 12:40
-
lstlisting does not work in xelatex. And alltt does not seem to admit Greek letters. – jjmerelo Dec 27 '16 at 20:57
-
1@jjmerelo:
listingsworks in XeLaTeX. If not, you're doing something wrong. – Werner Dec 27 '16 at 21:07 -
It does work, only it does funny things when Greek or other letters are included: http://tex.stackexchange.com/questions/81674/unicode-characters-changing-order-in-listings-xetex I still have the same problem. – jjmerelo Dec 27 '16 at 21:09
-
-
It's indeed fancy, but doesn't have an option to use a font that interprets those characters correctly. – jjmerelo Dec 28 '16 at 07:55
-
In fact, it was just a matter of adding
\setmonofont{DejaVu Sans Mono}, that is, a monospace font that includes Greek and other letters. The default ones don't. – jjmerelo Dec 28 '16 at 08:08
5
In XeLaTeX, which admits typing the Unicode symbols directly, the only thing you need is to select a mono font that can display them.
\usepackage{unicode-math}
\setmonofont{DejaVu Sans Mono}
And then
\begin{verbatim}
sin(π/3)² + cos(π/3)²
\end{verbatim}
jjmerelo
- 210

listingspackage which providesmathescape. This escapes to LaTeX within math, setting the symbols the way you want while still keeping the other content verbatim-like. – Werner Dec 12 '13 at 19:21