Problem creating a new environment 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 this:

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

But I get the following error:

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

Can anyone help to fix this problem?

[Update]

I tried to make it like a Red-nosed unicorn , and it worked correctly.

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

 \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]) * 
+7
latex
source share
2 answers

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

To get around my solution, I need to use \singlespacing instead of singlespace .

Below is my working code:

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

This is a special case because the list environment needs to parse ahead to find the end. The reason is that macros inside the list environment should not expand - this, of course, includes the end tag of the environment.

Basically, it looks on every line if the line contains \end{lstlisting} - but in your case such a line does not exist, since the macro \end{javacode} has not yet been expanded. Thus, the lists continue to search until the end of the file.

Lists define their own team to get 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. In fact, it doesn't work that much - the latex processor just stops right in the middle and waits for user input.

Since the listing documentation doesn’t mention special handling of singlespace , I think you might have discovered an error. The best course of action is probably to get feedback from the accompanying package of packages.

 % 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} 
+16
source share

All Articles