[Tex/LaTex] Subscript and superscript in lstlisting

listingssubscriptssuperscripts

I need to use subscript and superscript in a lstlisting block. lstlisting can replace strings by Latex commands, but is it also possible to replace some kind of regular expression like

_<something> and ^<something>

to identify the strings, that shall be replaced?

Thanks 🙂

Best Answer

Probably the simplest way to do this is to use the option mathescape in a \lstset command. This will not only allow you to use superscripts and subscripts, but will also give you access to other things you can do in mathmode. It may also do subtle and strange things to your formatting, but you can perhaps account for this where it matters to you.

Example.

\documentclass{article}
\usepackage{listings}

\lstset{
  mathescape,         
  literate={->}{$\rightarrow$}{2}
           {ε}{$\varepsilon$}{1}
}

\begin{document}
\begin{lstlisting}
R -> ε | $\ell$ | (R|R) | (RR) | R$^\ast$
$\ell\,$ ->  a | b | c | $\cdots$
\end{lstlisting}
\end{document}

Result.

Example of using mathescape in a lstlisting