Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with creating a newenvironment in LaTeX

I am trying to implement this new environment in LaTeX:

\newenvironment{javacode}[2]
{\begin{lstlisting}[language=java, label=#1, caption=#2]}
{\end{lstlisting}}

And then use it like such:

\begin{javacode}{c}{some code}
int x = 5;
\end{javacode}

But I am getting the following error:

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

Can anyone help as regards fixing this problem?

[Update]

I tried it doing it like Red-nosed unicorn instructed, and it worked correctly.

But now I tried adding a \begin{singlespace} like such:

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

And I got the same error:

Overfull \hbox (6.0pt too wide) in paragraph at lines 6--6
[][][][][][][] 
[1]) [2] [3])
*
like image 614
Andreas Grech Avatar asked Apr 09 '10 10:04

Andreas Grech


2 Answers

This is a special case because the listings environment needs to parse ahead itself to find the end of itself. The reason is that macros inside the listings environment must not get expanded – that of course includes the end tag of the environment.

So basically it looks in each line if the line contains \end{lstlisting} – but in your case, no such line exists since the \end{javacode} macro has not yet been expanded. So listings continues to search until the end of the file.

Listings defines an own command to work around this. From the documentation:

\lstnewenvironment 
  {⟨name⟩}[⟨number⟩][⟨opt. default arg.⟩]
  {⟨starting code⟩}
  {⟨ending code⟩}

For example:

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

EDIT In response to your edited question: I tried to compile the following minimal “working” example. Actually, it’s not so much working – the latex processor just stops right in the middle and waits for a user input.

Since the listings documentation makes no mention of a special treatment of singlespace, I think you may have uncovered a bug. The best course of action is probably to get feedback from the maintainer of the listings package.

% mini.dvi
\documentclass{article}

\usepackage{listings}
\usepackage{setspace}
\doublespacing

\lstnewenvironment{javacode}
 {\begin{singlespace}
  \lstset{language=java}}
 {\end{singlespace}}

\begin{document}
\begin{javacode}
int a = 1;
int b = 2;
\end{javacode}
\end{document}
like image 179
Konrad Rudolph Avatar answered Nov 01 '22 05:11

Konrad Rudolph


Upon further research, I found this http://www.tug.org/pipermail/texhax/2009-June/012699.html

To workaround my solution, I need to use \singlespacing instead of the singlespace environment.

The following is now my working code:

\lstnewenvironment{javacode}[2]
{\singlespacing\lstset{language=java, label=#1, caption=#2}}
{}
like image 20
Andreas Grech Avatar answered Nov 01 '22 05:11

Andreas Grech