# Figure environment not working with included file (extra } or forgotten endgroup)

I've spent hours on this issue. I hope someone can help me. I'm running into some kind of interference when I try to use the figure environment (Likewise for table, might be related to floats). I finally narrowed the problem down to one line-- where I include another file in the preamble that allows me to later include python code and have Latex color code it. The code I'm trying to compile is:

\documentclass[10pt]{article}
\include{pythonperfect}
\usepackage{graphicx}
\begin{document}
\begin{figure}
blah blah blah
\end{figure}
\end{document}


where "pythonperfect" is:

\usepackage{color}
\usepackage[procnames]{listings}
\usepackage{textcomp}
\usepackage{setspace}
\usepackage{palatino}
\renewcommand{\lstlistlistingname}{Code Listings}
\renewcommand{\lstlistingname}{Code Listing}
\definecolor{gray}{gray}{0.5}
\definecolor{green}{rgb}{0,0.5,0}
\definecolor{lightgreen}{rgb}{0,0.7,0}
\definecolor{purple}{rgb}{0.5,0,0.5}
\definecolor{darkred}{rgb}{0.5,0,0}
\definecolor{orange}{rgb}{1,0.5,0}
%\lstnewenvironment{python}[1][]{
\lstset{
language=python,
basicstyle=\ttfamily\small\setstretch{1},
stringstyle=\color{green},
showstringspaces=false,
alsoletter={1234567890},
otherkeywords={\ , \}, \{},
keywordstyle=\color{blue},
emph={access,and,as,break,class,continue,def,del,elif,else,%
except,exec,finally,for,from,global,if,import,in,is,%
lambda,not,or,pass,print,raise,return,try,while,assert},
emphstyle=\color{orange}\bfseries,
emph={[2]self},
emphstyle=[2]\color{gray},
emph={[4]ArithmeticError,AssertionError,AttributeError,BaseException,%
DeprecationWarning,EOFError,Ellipsis,EnvironmentError,Exception,%
False,FloatingPointError,FutureWarning,GeneratorExit,IOError,%
ImportError,ImportWarning,IndentationError,IndexError,KeyError,%
KeyboardInterrupt,LookupError,MemoryError,NameError,None,%
NotImplemented,NotImplementedError,OSError,OverflowError,%
PendingDeprecationWarning,ReferenceError,RuntimeError,RuntimeWarning,%
StandardError,StopIteration,SyntaxError,SyntaxWarning,SystemError,%
SystemExit,TabError,True,TypeError,UnboundLocalError,UnicodeDecodeError,%
UnicodeEncodeError,UnicodeError,UnicodeTranslateError,UnicodeWarning,%
UserWarning,ValueError,Warning,ZeroDivisionError,abs,all,any,apply,%
basestring,bool,buffer,callable,chr,classmethod,cmp,coerce,compile,%
execfile,exit,file,filter,float,frozenset,getattr,globals,hasattr,%
hash,help,hex,id,input,int,intern,isinstance,issubclass,iter,len,%
slice,sorted,staticmethod,str,sum,super,tuple,type,unichr,unicode,%
vars,xrange,zip},
emphstyle=[4]\color{purple}\bfseries,
upquote=true,
morecomment=[s][\color{lightgreen}]{"""}{"""},
literate={>>>}{\textbf{\textcolor{darkred}{>{>}>}}}3%
{...}{{\textcolor{gray}{...}}}3,
procnamekeys={def,class},
procnamestyle=\color{blue}\textbf,
%rulesepcolor=\color{blue},
breaklines=true,
}{}


The error I get is:

! Too many }'s.
\color@endbox->\color@endgroup \egroup
l.10 \end{figure}
You've closed more groups than you opened.
Such booboos are generally harmless, so keep going.
! LaTeX Error: \begin{document} ended by \end{figure}.


In any case, I've used "pythonperfect" for a while, and never ran into an issue until today when I tried to include a figure. The problem is that I don't really understand most of what's happening in that file, I found it somewhere on the web (I don't remember where) and made a few changes to make it work for me. But I don't really understand it. So I can't figure out what's wrong.

I'd really appreciate any help. Thank you very much.

-
The minimal example compiles for me without errors with a freshly updated TeXLive installation. What versions of the used packages are you using? You can display that in the .log file using \listfiles in the preamble. –  Martin Scharrer Mar 15 '11 at 8:22

As Martin Scharrer mentioned in his comment, the example works. However, I think the problem starts in the moment you use the newly defined environment \lstnewenvironment.

There was a closing } missing and when you used

\begin{python}

\end{python}


the error message came up. Have a look at this file's very last line. I also un-commented the new environment definition.

\usepackage{color}
\usepackage[procnames]{listings}
\usepackage{textcomp}
\usepackage{setspace}
\usepackage{palatino}
\renewcommand{\lstlistlistingname}{Code Listings}
\renewcommand{\lstlistingname}{Code Listing}
\definecolor{gray}{gray}{0.5}
\definecolor{green}{rgb}{0,0.5,0}
\definecolor{lightgreen}{rgb}{0,0.7,0}
\definecolor{purple}{rgb}{0.5,0,0.5}
\definecolor{darkred}{rgb}{0.5,0,0}
\definecolor{orange}{rgb}{1,0.5,0}
\lstnewenvironment{python}[1][]{%%%% Included this
\lstset{
language=python,
basicstyle=\ttfamily\small\setstretch{1},
stringstyle=\color{green},
showstringspaces=false,
alsoletter={1234567890},
otherkeywords={\ , \}, \{},
keywordstyle=\color{blue},
emph={access,and,as,break,class,continue,def,del,elif,else,%
except,exec,finally,for,from,global,if,import,in,is,%
lambda,not,or,pass,print,raise,return,try,while,assert},
emphstyle=\color{orange}\bfseries,
emph={[2]self},
emphstyle=[2]\color{gray},
emph={[4]ArithmeticError,AssertionError,AttributeError,BaseException,%
DeprecationWarning,EOFError,Ellipsis,EnvironmentError,Exception,%
False,FloatingPointError,FutureWarning,GeneratorExit,IOError,%
ImportError,ImportWarning,IndentationError,IndexError,KeyError,%
KeyboardInterrupt,LookupError,MemoryError,NameError,None,%
NotImplemented,NotImplementedError,OSError,OverflowError,%
PendingDeprecationWarning,ReferenceError,RuntimeError,RuntimeWarning,%
StandardError,StopIteration,SyntaxError,SyntaxWarning,SystemError,%
SystemExit,TabError,True,TypeError,UnboundLocalError,UnicodeDecodeError,%
UnicodeEncodeError,UnicodeError,UnicodeTranslateError,UnicodeWarning,%
UserWarning,ValueError,Warning,ZeroDivisionError,abs,all,any,apply,%
basestring,bool,buffer,callable,chr,classmethod,cmp,coerce,compile,%
execfile,exit,file,filter,float,frozenset,getattr,globals,hasattr,%
hash,help,hex,id,input,int,intern,isinstance,issubclass,iter,len,%
slice,sorted,staticmethod,str,sum,super,tuple,type,unichr,unicode,%
vars,xrange,zip},
emphstyle=[4]\color{purple}\bfseries,
upquote=true,
morecomment=[s][\color{lightgreen}]{"""}{"""},
literate={>>>}{\textbf{\textcolor{darkred}{>{>}>}}}3%
{...}{{\textcolor{gray}{...}}}3,
procnamekeys={def,class},
procnamestyle=\color{blue}\textbf,
rulesepcolor=\color{blue},
breaklines=true,
#1
}}{}%%%%Here it was missing }


And the example

\documentclass[10pt]{article}
\input{pythonperfect}%input better than include here
\usepackage{graphicx}
\begin{document}
\begin{figure}
blah blah blah
\end{figure}

\begin{python}
for a
\end{python}

\end{document}


-
I've marked your inline code with backticks . (Sorry for the edit clash; I actually made my changes twice.) –  Hendrik Vogt Mar 15 '11 at 8:47
I keep on doing the code bit wrong don't I :) Also I made about 5 edits because of things I missed. No worries –  Martin H Mar 15 '11 at 9:11
Hendrik: Thank you both. I tried to compile the code Hendrik posted, and that didn't run either. It's obviously a problem with my install. I'm going to update the packages (I think I'll do a full TexLive install from scratch, to fix any other problems while I'm at it). Then I'll try again. Thanks. –  Aaron Mar 17 '11 at 6:11
@Aaron: It's not my code but Martin's code. I just gave Martin's answer some minor polishing. –  Hendrik Vogt Mar 17 '11 at 9:21

Well, I played with this for quite a few hours, and I guess it's only fair to share my findings with anyone else who might be interested.

Here's what I found: Martin's code works great if you want to use the python environment, with \begin{python}...\end{python}. He uncommented a line:

\lstnewenvironment{python}[1][]{


Then he stuck in a #1 at the end (to use the option), and added a }. But that brace is not the brace the LaTeX is talking about in the error. It's only needed after you add the aforementioned line, where you open a brace.

The problem with this is that it only works if you want to use the python environment. But if you want to use listings to include complete python files, as I do, this does not work. \lstnewenvironment overrides \lstinputlisting, which is why I had it commented out in the first place.

In any case, you can use it if you want the environment, or you can leave it out. Or figure out a way to use both at the same time.

After installing a new install of TexLive-full, I got the the thing to work--but only in the sterile environment of a trial document. When I put it into the document I'm working on, I ran into the same issues I started with. Evidently, it's some kind of clash with something else in the document.

Lots of trial and error tells me that it's the use of the setspace package that's interfering with... something. I can't for the life of me figure out what. It does work in a simple document. Weird.

In any case, taking out setspace means you have to also take out \setstretch{1}, but it's not such a big deal.

Thanks to those who answered. I appreciate it. And Martin, good point about \input vs. \include. I didn't realize that.

-
Now I've marked also your inline code with backticks . Looks nicer like this, doesn't it? :-) –  Hendrik Vogt Mar 17 '11 at 9:29
Yes, posting you own final solution as answer is good and encouraged. –  Martin Scharrer Mar 17 '11 at 10:56