# Listings WriteFile adds additional line if content contains two spaces between words

I use the listings latex package to write/read the environment body to a file. But if in the environment are two spaces between some words, there is an additional linebreak added at the beginning (I made it red to see it better in this example). How can I prevent this?

\documentclass{article}
\usepackage{listings}
\usepackage{color}

\makeatletter
\lst@RequireAspects{writefile}
\lstnewenvironment{testenv}{%
\lstset{aboveskip=0pt,belowskip=0pt,backgroundcolor=\color{red}}%
\lst@BeginWriteFile{\jobname.tst}%
}{%
\lst@EndWriteFile% closes output file
% do something
\input{\jobname.tst}
% do something
}%
\makeatother

\begin{document}
Something wrong begins.
\begin{testenv}
This is a text with two spaces  between  some words.
\end{testenv}
And it ends.

\begin{testenv}
This is a text with only one space between all words.
\end{testenv}

\end{document}


The output:

-
Welcome to TeX.sx! Please always use specific titles which already describe the problem. Generic titles like "XYZ problem" apply to many/all different problems with the same thing. – Martin Scharrer Jan 3 '13 at 12:08
I can acknowledge the issue. The \jobname.tst file does not contain any additional lines in both cases. The extra line seems to be caused by the \lst@BeginWriteFile .. \lst@EndWriteFile directly, which can be seen if you add something before the \input line. – Martin Scharrer Jan 3 '13 at 12:17

This seems to be some form of bug in listings. I actually remember now that I had the same issue when using listings WriteFile feature in my ydoc bundle. My workaround was to catch the typesetting output of it inside a box which is then never typeset. This can be done e.g. using \begin{lrbox}{0} .. \end{lrbox} where you use the temporary box #0 or maybe \@tempboxa, or use \setbox etc.

\documentclass{article}
\usepackage{listings}
\usepackage{color}

\makeatletter
\lst@RequireAspects{writefile}
\lstnewenvironment{testenv}{%
\lstset{aboveskip=0pt,belowskip=0pt,backgroundcolor=\color{red}}%
\setbox\@tempboxa\hbox\bgroup
\lst@BeginWriteFile{\jobname.tst}%
}{%
\lst@EndWriteFile% closes output file
\egroup
% do something
\input{\jobname.tst}%
% do something
}%
\makeatother

\begin{document}

11111111111111111111111
\begin{testenv}
text text text text text text text text text text text text text text text text
\end{testenv}
22222222222222222222222

11111111111111111111111
\begin{testenv}
text  text text text text text text text text text text text text text text text
\end{testenv}
22222222222222222222222

\end{document}

-