Inside my lstlisting
environment I want to make the assignment symbol an arrow instead of =
. How can I do that? Adding just \leftarrow
doesn't work, because then the whole word is displayed.
1 Answer
As requested by Jubobs, here is a simple document elaborating on the comments, showing how to use math literals to use \leftarrow
for assignment in a lstlistings
environment.
Preamble
\documentclass{article}
\usepackage{listings}
\lstset{columns=fullflexible,
mathescape=true,
literate=
{=}{$\leftarrow{}$}{1}
{==}{$={}$}{1},
morekeywords={if,then,else,return}
}
Here, we use \lstset
to change the settings for all lstlisting
environments in the document. You could put these options in the argument to an individual argument if you prefer. I've set the columns to fullflexible
for the sake of presentation, and added keywords because I haven't chosen any language. The setting mathescape=true
will allow us to use math-mode to typeset special character combinations.
The list of 'literates' (note: no commas separating the items in the list!) tells listings
how to typeset special character combinations. Here, assignment (=
) is being typeset with \leftarrow
, and equality testing (==
) is being typeset with the equality symbol. The {}
after the symbols is necessary for correct spacing in the fullflexible
column option: it has no effect with fixed
. Note the comma after the last literal, before the morekeywords
option.
Sample document
\begin{document}
\begin{lstlisting}
a = 1;
if (a == 0)
then do not panic, Citizen, everything is under control!
else rest easy, Citizen, everything is fine!
return to your daily business!
\end{lstlisting}
\end{document}
Output
mathescape=true, literate={=}{$\leftarrow$}{1}
in yourlistings
definition.:)
==
for the equality relation (as opp. assignment), you could useliterate={=}{$\leftarrow$}{1},{==}{$=$}{1}
.