Saturday, April 10, 2010

Using the singlespace environment in an lstnewenvironment, in LaTeX

I was working on a LaTeX document and I had \linespread{1.6} set for double line spacing. But then I added some code snippets to the document with the listings package and I wanted my code to have single line spacing, rather than double line spacing. So, I tried putting them both in a new listings environment to abstract them into a single environment:

\lstnewenvironment{javacode}[2]
{
\begin{singlespace}
\lstset{language=java, label=#1, caption=#2}}
{
\end{singlespace}
}

But upon compiling, I was getting the following 'error':

Overfull \hbox (6.0pt too wide) in paragraph at lines 6--6
[][][][][][][] 
[1]) [2] [3])
*

The Fix

Upon some research, I found the following question which provided a solution to my problem.

The solution to the singlespace environment problem, as suggested by that answer, is to not use the singlespace environment but instead to use \singlespacing instead.

Therefore, this is my final working code:

\lstnewenvironment{javacode}[2]
{
\singlespacing
\lstset{language=java, label=#1, caption=#2}}
{}