4

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.

  • 4
    You might try mathescape=true, literate={=}{$\leftarrow$}{1} in your listings definition. :) – Paulo Cereda Nov 18 '13 at 19:41
  • 2
    Furthermore, assuming that your language uses == for the equality relation (as opp. assignment), you could use literate={=}{$\leftarrow$}{1},{==}{$=$}{1}. – Niel de Beaudrap Nov 18 '13 at 20:31
  • @NieldeBeaudrap An answer? – jub0bs Sep 10 '14 at 15:17
  • 1
    @Jubobs: done. :-) – Niel de Beaudrap Sep 12 '14 at 12:56
3

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

Typeset output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.