# Subscript and superscript in lstlisting?

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 :-)

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.

• Perhaps it might be better to actually show subscripts and superscripts in your example, which is what the OP is asking for explicitly. – Michael Jun 14 '14 at 13:37
• I may elaborate the example with subscripts and (more) superscripts later today. The R$^\ast$ is a superscript. – Niel de Beaudrap Jun 14 '14 at 13:57