Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 6 down vote accepted

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:

enter image description here

\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}
share|improve this answer
    
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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