# Dynamically created program listing

Is there a way to have a easy to change value in program listing? Something along these lines:

\newcommand{\variable}{2}


And then having somewhere

\begin{lstlisting}
...
i *= \variable;
...
\end{lstlisting}


I would like to keep the format, so I don't want to end and start another listing.

-

Yes. You should use the mathescape option provided by listings:

\begin{lstlisting}[mathescape=true]
...
i *= $\variable$;
...
\end{lstlisting}


This escapes back to LaTeX, where \variable has a different meaning than inside lstlisting. Here's a complete MWE showing the use:

\documentclass{article}
\usepackage{listings}% http://ctan.org/pkg/listings
\newcommand{\variable}{2}
\begin{document}
\begin{lstlisting}
...
i *= \variable;
...
\end{lstlisting}
\begin{lstlisting}[mathescape=true]
...
i *= $\variable$;
...
\end{lstlisting}
\end{document}

-
Thanks this is what I was looking for. One minor thing, the font of the escaped text is different from font of listing, are there any options to use the font of the listing in escaped text? One more thing, any chance of doing arithmetics? Lets say I assign a value "1" to command, could I add 1 to it a display it in program listing? –  user1335014 Feb 15 '13 at 8:45