# Lstlistings: Getting pretty equations in display mode

I am currently trying to print my algorithms using the listings package. For clarity I always try to display the more complex mathematical expressions as formula instead of plain code. This results in having to escape to latex for my formula, incase it gets to big for an inline formula. In theory, everything is working just fine with the following code:

\begin{lstlisting}[escapeinside={/*@}{@*/}]
for (j = 1; j <= p; j++) {
for (m = 0; m <= p-j ; m++) {/*@
\begin{equation*}\begin{split}
c &= \frac{t - t_{i - m}}{t_{i - m + p - j+1} - t_{i-m}};\\
d^{(j)}_m &= (1-c)\cdot d^{(j-1)}_{m+1} + c\cdot d^{(j-1)}_m;
\end{split}\end{equation*}\stepcounter{lstnumber}\stepcounter{lstnumber}@*/
}
}
\end{lstlisting}


This gives me the following output: As you can see, the result is not that pretty.

Now my question(s):

• Do you know a more elegant way to insert the equations to listings?
• If not, it would be a huge gain if it is possible just to shift the equations to the left (which I remember having seen somewhere, but I do not remember how to do it...)
• The perfect solution would be reached if you also know a way how to insert the line numbers (and may it even be inserting them manually and placing them by "hand")

Thank you for all your ideas.

P.S.: In case you wonder: The code is part of the algorithm of de Boor.

listing has an option to allow math mode inside the listing :

\begin{lstlisting}[mathescape]
for (j = 1; j <= p; j++) {
for (m = 0; m <= p-j ; m++) {
$\displaystyle c = \frac{t - t_{i - m}}{t_{i - m + p - j+1} - t_{i-m}};$
$\displaystyle d^{(j)}_m = (1-c)\cdot d^{(j-1)}_{m+1} + c\cdot d^{(j-1)}_m;$

}
}
\end{lstlisting}


This should give you a result that is easier on the eye.

You do lose the alignment on the = sign, but it now looks a lot more like it's part of the code.

• Yes and no. The problem with mathescape is that the equations are typeset in \textstyle. ... wait ... not really. Who says you can't use $\displaystyle \frac{a}{b}$. Short test - works as expected. Thank you so much for giving me the idea that has been around the corner all the time. – Thilo Jul 8 '11 at 19:47
• Edited your post to incorporate that change - hope you don't mind. – Thilo Jul 8 '11 at 19:49
• Not at all, glad I could help :) – Lexiel Jul 8 '11 at 19:50
• Last addition, in case somebody else looks at this: The spacing between the lines is not really perfect. You can increase line hight for example by adding \phantom{\Bigg|} to both equations. This gives pretty solid results. – Thilo Jul 8 '11 at 20:16