# Changing code in listings dynamically

I need to change dynamically the code in the listing by adding just one key word to the code. I tried to do it like this:

\begin{lstlisting}[escapechar=|]
private |\only<3>{\alert{volatile}}| boolean stop = false;

public void run() {
while (!stop) {
doSomeWork();
}
}
public void setStop() {
this.stop = true;
}
}
\end{lstlisting}


It works ok, but there are two spaces between "private" and "boolean" when the "volatile" is not visible. Is there any other way to make what I want?

-
Could you make this into a minimal working example (MWE)? However, placing a space between the two braces and removing the one after the closing escape | seems to do. –  egreg Feb 1 at 11:52
I also thought of this. But the funny thing: when I do it like you said, then "boolean stop = false;" ends up on the next line. And when I do it like in example, it's on one line. –  damluar Feb 1 at 14:36
I will do MWE now –  damluar Feb 1 at 14:38
Ok, I got it working. I had two columns in a frame. Increasing width of the one, helped to avoid line break. You can put your comment to answers, thanks! –  damluar Feb 1 at 15:32

If you don't mind me changing your implementation slightly, here is my solution. Put your code in a separate file and then bring it in like the following example. By doing so, first you avoid any kind of unexpected behaviors like the one you are having now, and second, you can easily and simply add as many keywords as you want:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\begin{document}
\lstset{
language=Java,
tabsize=3,
%frame=lines,
caption=A test file,
label=code:test,
rulesepcolor=\color{gray},
xleftmargin=20pt,
framexleftmargin=15pt,
keywordstyle=\color{blue}\bf,
stringstyle=\color{red},
numbers=left,
numberstyle=\tiny,
numbersep=5pt,
breaklines=true,
showstringspaces=false,
basicstyle=\footnotesize,

The keywords are added in the last line of lstset (emph={volatile}). You can add more by separating them with ,