]> git.lyx.org Git - lyx.git/blobdiff - src/buffer.C
More fixes to insettabular/text (and some missing features added).
[lyx.git] / src / buffer.C
index 67d59801bccc5fa8cdad4811f645d17d7f6f074f..d0b864ef9a9eb1cb287d85941835c1be66d9e774 100644 (file)
@@ -18,6 +18,7 @@
 #include <iomanip>
 
 #include <cstdlib>
+#include <cmath>
 #include <unistd.h>
 #include <sys/types.h>
 #include <utime.h>
@@ -77,7 +78,6 @@
 #include "support/filetools.h"
 #include "support/path.h"
 #include "LaTeX.h"
-#include "Literate.h"
 #include "Chktex.h"
 #include "LyXView.h"
 #include "debug.h"
@@ -85,6 +85,7 @@
 #include "support/syscall.h"
 #include "support/lyxlib.h"
 #include "support/FileInfo.h"
+#include "support/lyxmanip.h"
 #include "lyxtext.h"
 #include "gettext.h"
 #include "language.h"
@@ -105,7 +106,6 @@ using std::pair;
 using std::vector;
 using std::max;
 using std::set;
-using std::istringstream;
 
 // all these externs should eventually be removed.
 extern BufferList bufferlist;
@@ -179,7 +179,7 @@ void Buffer::setReadonly(bool flag)
        if (read_only != flag) {
                read_only = flag; 
                updateTitles();
-               users->owner()->getDialogs()->updateBufferDependent();
+               users->owner()->getDialogs()->updateBufferDependent(false);
        }
        if (read_only) {
                WarnReadonly(filename);
@@ -219,7 +219,7 @@ void Buffer::resetAutosaveTimers() const
 }
 
 
-void Buffer::fileName(string const & newfile)
+void Buffer::setFileName(string const & newfile)
 {
        filename = MakeAbsPath(newfile);
        filepath = OnlyPath(filename);
@@ -247,15 +247,15 @@ bool Buffer::readLyXformat2(LyXLex & lex, LyXParagraph * par)
        bool the_end_read = false;
 
        LyXParagraph * return_par = 0;
-       LyXFont font(LyXFont::ALL_INHERIT, params.language_info);
-       if (format < 2.16 && params.language == "hebrew")
+       LyXFont font(LyXFont::ALL_INHERIT, params.language);
+       if (format < 2.16 && params.language->lang() == "hebrew")
                font.setLanguage(default_language);
 
        // If we are inserting, we cheat and get a token in advance
        bool has_token = false;
        string pretoken;
 
-       if(!par) {
+       if (!par) {
                par = new LyXParagraph;
        } else {
                users->text->BreakParagraph(users);
@@ -364,8 +364,8 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
                par->footnotekind = footnotekind;
 #endif
                par->depth = depth;
-               font = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
-               if (format < 2.16 && params.language == "hebrew")
+               font = LyXFont(LyXFont::ALL_INHERIT, params.language);
+               if (format < 2.16 && params.language->lang() == "hebrew")
                        font.setLanguage(default_language);
 #ifndef NEW_INSETS
        } else if (token == "\\end_float") {
@@ -380,8 +380,8 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
                pos = 0;
                lex.EatLine();
                par->layout = LYX_DUMMY_LAYOUT;
-               font = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
-               if (format < 2.16 && params.language == "hebrew")
+               font = LyXFont(LyXFont::ALL_INHERIT, params.language);
+               if (format < 2.16 && params.language->lang() == "hebrew")
                        font.setLanguage(default_language);
        } else if (token == "\\begin_float") {
                int tmpret = lex.FindToken(string_footnotekinds);
@@ -485,7 +485,10 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
                if (pp.first) {
                        params.textclass = pp.second;
                } else {
-                 lex.printError("Unknown textclass `$$Token'");
+                       WriteAlert(string(_("Textclass error")), 
+                               string(_("The document uses an unknown textclass \"")) + 
+                               lex.GetString() + string("\"."),
+                               string(_("LyX will not be able to produce output correctly.")));
                        params.textclass = 0;
                }
                if (!textclasslist.Load(params.textclass)) {
@@ -551,7 +554,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
                if (tmpret != LYX_LAYOUT_DEFAULT) {
                        InsetQuotes::quote_language tmpl = 
                                InsetQuotes::EnglishQ;
-                       switch(tmpret) {
+                       switch (tmpret) {
                        case 0:
                                tmpl = InsetQuotes::EnglishQ;
                                break;
@@ -575,7 +578,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
                }
        } else if (token == "\\quotes_times") {
                lex.nextToken();
-               switch(lex.GetInteger()) {
+               switch (lex.GetInteger()) {
                case 1: 
                        params.quotes_times = InsetQuotes::SingleQ; 
                        break;
@@ -642,7 +645,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
                params.columns = lex.GetInteger();
        } else if (token == "\\papersides") {
                lex.nextToken();
-               switch(lex.GetInteger()) {
+               switch (lex.GetInteger()) {
                default:
                case 1: params.sides = LyXTextClass::OneSide; break;
                case 2: params.sides = LyXTextClass::TwoSides; break;
@@ -772,13 +775,16 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
        } else if (token == "\\lang") {
                lex.next();
                string const tok = lex.GetString();
-               Languages::iterator lit = languages.find(tok);
-               if (lit != languages.end()) {
-                       font.setLanguage(&(*lit).second);
+               Language const * lang = languages.getLanguage(tok);
+               if (lang) {
+                       font.setLanguage(lang);
                } else {
-                       font.setLanguage(params.language_info);
+                       font.setLanguage(params.language);
                        lex.printError("Unknown language `$$Token'");
                }
+       } else if (token == "\\numeric") {
+               lex.next();
+               font.setNumber(font.setLyXMisc(lex.GetString()));
        } else if (token == "\\emph") {
                lex.next();
                font.setEmph(font.setLyXMisc(lex.GetString()));
@@ -805,9 +811,14 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
                int tmpret = lex.FindToken(string_align);
                if (tmpret == -1) ++tmpret;
                if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
+#if 0
                        int tmpret2 = 1;
                        for (; tmpret > 0; --tmpret)
                                tmpret2 = tmpret2 * 2;
+#else
+                       int const tmpret2 = int(pow(2.0, tmpret));
+#endif
+                       //lyxerr << "Tmpret2 = " << tmpret2 << endl;
                        par->align = LyXAlignment(tmpret2);
                }
        } else if (token == "\\added_space_top") {
@@ -880,7 +891,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
                par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
                ++pos;
        } else if (token == "\\LyXTable") {
-               Inset * inset = new InsetTabular(this);
+               Inset * inset = new InsetTabular(*this);
                inset->Read(this, lex);
                par->InsertInset(pos, inset, font);
                ++pos;
@@ -919,7 +930,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, LyXParagraph *& par,
                               "Inserting as text.");
                string::const_iterator cit = token.begin();
                string::const_iterator end = token.end();
-               for(; cit != end; ++cit) {
+               for (; cit != end; ++cit) {
                        par->InsertChar(pos, (*cit), font);
                        ++pos;
                }
@@ -954,11 +965,11 @@ void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
                        lex.printError("Wrong place for bibitem");
                        inset = new InsetBibKey(inscmd);
                } else if (inscmd.getCmdName() == "BibTeX") {
-                       inset = new InsetBibtex(inscmd, this);
+                       inset = new InsetBibtex(inscmd);
                } else if (inscmd.getCmdName() == "index") {
                        inset = new InsetIndex(inscmd);
                } else if (inscmd.getCmdName() == "include") {
-                       inset = new InsetInclude(inscmd, this);
+                       inset = new InsetInclude(inscmd, *this);
                } else if (inscmd.getCmdName() == "label") {
                        inset = new InsetLabel(inscmd);
                } else if (inscmd.getCmdName() == "url"
@@ -971,7 +982,7 @@ void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
                           || inscmd.getCmdName() == "prettyref") {
                        if (!inscmd.getOptions().empty()
                            || !inscmd.getContents().empty()) {
-                               inset = new InsetRef(inscmd);
+                               inset = new InsetRef(inscmd, *this);
                        }
                } else if (inscmd.getCmdName() == "tableofcontents"
                           || inscmd.getCmdName() == "listofalgorithms"
@@ -981,7 +992,7 @@ void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
                } else if (inscmd.getCmdName() == "printindex") {
                        inset = new InsetPrintIndex(inscmd);
                } else if (inscmd.getCmdName() == "lyxparent") {
-                       inset = new InsetParent(inscmd, this);
+                       inset = new InsetParent(inscmd, *this);
                }
        } else {
                if (tmptok == "Quotes") {
@@ -993,16 +1004,16 @@ void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
                } else if (tmptok == "Formula") {
                        inset = new InsetFormula;
                } else if (tmptok == "Figure") {
-                       inset = new InsetFig(100, 100, this);
+                       inset = new InsetFig(100, 100, *this);
                } else if (tmptok == "Info") {
                        inset = new InsetInfo;
                } else if (tmptok == "Include") {
                        InsetCommandParams p( "Include" );
-                       inset = new InsetInclude(p, this);
+                       inset = new InsetInclude(p, *this);
                } else if (tmptok == "ERT") {
                        inset = new InsetERT;
                } else if (tmptok == "Tabular") {
-                       inset = new InsetTabular(this);
+                       inset = new InsetTabular(*this);
                } else if (tmptok == "Text") {
                        inset = new InsetText;
                } else if (tmptok == "Foot") {
@@ -1043,15 +1054,14 @@ bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
                if (token == "\\lyxformat") { // the first token _must_ be...
                        lex.EatLine();
                        format = lex.GetFloat();
-                       if (format > 1) {
+                       if (format > 1.0) {
                                if (LYX_FORMAT - format > 0.05) {
-                                       
-                                       printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
-                                              LYX_FORMAT, format);
+                                       lyxerr << fmt(_("Warning: need lyxformat %.2f but found %.2f"),
+                                                     LYX_FORMAT, format) << endl;
                                }
                                if (format - LYX_FORMAT > 0.05) {
-                                       printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
-                                              LYX_FORMAT, format);
+                                       lyxerr << fmt(_("ERROR: need lyxformat %.2f but found %.2f"),
+                                                     LYX_FORMAT, format) << endl;
                                }
                                bool the_end = readLyXformat2(lex, par);
                                // Formats >= 2.13 support "\the_end" marker
@@ -1067,7 +1077,7 @@ bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
                                // We simulate a safe reading anyways to allow
                                // users to take the chance... (Asger)
                                return true;
-                       } // format < 1
+                       } // format < 1.0
                        else {
                                WriteAlert(_("ERROR!"),
                                           _("Old LyX file format found. "
@@ -1236,243 +1246,49 @@ bool Buffer::writeFile(string const & fname, bool flag) const
 
        // Write marker that shows file is complete
        ofs << "\n\\the_end" << endl;
-       ofs.close();
-       // how to check if close went ok?
-       return true;
-}
 
+       ofs.close();
 
+       // how to check if close went ok?
+       // Following is an attempt... (BE 20001011)
+       
+       // good() returns false if any error occured, including some
+       //        formatting error.
+       // bad()  returns true if something bad happened in the buffer,
+       //        which should include file system full errors.
+
+       bool status = true;
+       if (!ofs.good()) {
+               status = false;
 #if 0
-void Buffer::writeFileAscii(string const & fname, int linelen) 
-{
-       Inset * inset;
-       char c;
-       char footnoteflag = 0;
-       char depth = 0;
-       string tmp;
-       LyXParagraph::size_type i;
-       int j;
-       int ltype = 0;
-       int ltype_depth = 0;
-       int actcell = 0;
-       int actpos = 0;
-       int currlinelen = 0;
-       long fpos = 0;
-       bool ref_printed = false;
-
-       ofstream ofs(fname.c_str());
-       if (!ofs) {
-               WriteFSAlert(_("Error: Cannot write file:"), fname);
-               return;
-       }
-
-       string const fname1 = TmpFileName();
-       LyXParagraph * par = paragraph;
-       while (par) {
-               int noparbreak = 0;
-               int islatex = 0;
-               if (
-#ifndef NEW_INSETS
-                       par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
-#endif
-                   !par->previous
-#ifndef NEW_INSETS
-                   || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
-#endif
-                       ){
-
-#ifndef NEW_INSETS
-                       /* begins a footnote environment ? */ 
-                       if (footnoteflag != par->footnoteflag) {
-                               footnoteflag = par->footnoteflag;
-                               if (footnoteflag) {
-                                       j = strlen(string_footnotekinds[par->footnotekind])+4;
-                                       if (currlinelen + j > linelen)
-                                               ofs << "\n";
-                                       ofs << "(["
-                                           << string_footnotekinds[par->footnotekind] << "] ";
-                                       currlinelen += j;
-                               }
-                       }
-#endif
-        
-                       /* begins or ends a deeper area ?*/ 
-                       if (depth != par->depth) {
-                               if (par->depth > depth) {
-                                       while (par->depth > depth) {
-                                               ++depth;
-                                       }
-                               }
-                               else {
-                                       while (par->depth < depth) {
-                                               --depth;
-                                       }
-                               }
-                       }
-        
-                       /* First write the layout */
-                       tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
-                       if (tmp == "Itemize") {
-                               ltype = 1;
-                               ltype_depth = depth+1;
-                       } else if (tmp == "Enumerate") {
-                               ltype = 2;
-                               ltype_depth = depth+1;
-                       } else if (contains(tmp, "ection")) {
-                               ltype = 3;
-                               ltype_depth = depth+1;
-                       } else if (contains(tmp, "aragraph")) {
-                               ltype = 4;
-                               ltype_depth = depth+1;
-                       } else if (tmp == "Description") {
-                               ltype = 5;
-                               ltype_depth = depth+1;
-                       } else if (tmp == "Abstract") {
-                               ltype = 6;
-                               ltype_depth = 0;
-                       } else if (tmp == "Bibliography") {
-                               ltype = 7;
-                               ltype_depth = 0;
-                       } else {
-                               ltype = 0;
-                               ltype_depth = 0;
-                       }
-        
-                       /* maybe some vertical spaces */ 
-
-                       /* the labelwidthstring used in lists */ 
-        
-                       /* some lines? */ 
-        
-                       /* some pagebreaks? */ 
-        
-                       /* noindent ? */ 
-        
-                       /* what about the alignment */ 
+               if (ofs.bad()) {
+                       lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
                } else {
-#ifndef NEW_INSETS
-                       /* dummy layout, that means a footnote ended */ 
-                       footnoteflag = LyXParagraph::NO_FOOTNOTE;
-                       ofs << ") ";
-                       noparbreak = 1;
-#else
-                       lyxerr << "Should this ever happen?" << endl;
-#endif
-               }
-      
-               LyXFont font1 =
-                       LyXFont(LyXFont::ALL_INHERIT, params.language_info);
-                actcell = 0;
-               for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
-                       if (!i && !footnoteflag && !noparbreak){
-                               ofs << "\n\n";
-                               for(j = 0; j < depth; ++j)
-                                       ofs << "  ";
-                               currlinelen = depth * 2;
-                               switch(ltype) {
-                               case 0: /* Standard */
-                               case 4: /* (Sub)Paragraph */
-                                case 5: /* Description */
-                                       break;
-                               case 6: /* Abstract */
-                                       ofs << "Abstract\n\n";
-                                       break;
-                               case 7: /* Bibliography */
-                                       if (!ref_printed) {
-                                               ofs << "References\n\n";
-                                               ref_printed = true;
-                                       }
-                                       break;
-                               default:
-                                       ofs << par->labelstring << " ";
-                                       break;
-                               }
-                               if (ltype_depth > depth) {
-                                       for(j = ltype_depth - 1; j > depth; --j)
-                                               ofs << "  ";
-                                       currlinelen += (ltype_depth-depth)*2;
-                               }
-                       }
-                       LyXFont font2 = par->GetFontSettings(params, i);
-                       if (font1.latex() != font2.latex()) {
-                               if (font2.latex() == LyXFont::OFF)
-                                       islatex = 0;
-                               else
-                                       islatex = 1;
-                       } else {
-                               islatex = 0;
-                       }
-                       c = par->GetChar(i);
-                       if (islatex)
-                               continue;
-                       switch (c) {
-                       case LyXParagraph::META_INSET:
-                               if ((inset = par->GetInset(i))) {
-                                       fpos = ofs.tellp();
-                                       inset->Ascii(this, ofs);
-                                       currlinelen += (ofs.tellp() - fpos);
-                                       actpos += (ofs.tellp() - fpos) - 1;
-                               }
-                               break;
-                       case LyXParagraph::META_NEWLINE:
-                               ofs << "\n";
-                               for(j = 0; j < depth; ++j)
-                                       ofs << "  ";
-                               currlinelen = depth * 2;
-                               if (ltype_depth > depth) {
-                                       for(j = ltype_depth;
-                                           j > depth; --j)
-                                               ofs << "  ";
-                                       currlinelen += (ltype_depth - depth) * 2;
-                               }
-                               break;
-                       case LyXParagraph::META_HFILL: 
-                               ofs << "\t";
-                               break;
-                       case '\\':
-                               ofs << "\\";
-                               break;
-                       default:
-                               if (currlinelen > linelen - 10
-                                    && c == ' ' && i + 2 < par->size()) {
-                                       ofs << "\n";
-                                       for(j = 0; j < depth; ++j)
-                                               ofs << "  ";
-                                       currlinelen = depth * 2;
-                                       if (ltype_depth > depth) {
-                                               for(j = ltype_depth;
-                                                   j > depth; --j)
-                                                       ofs << "  ";
-                                               currlinelen += (ltype_depth-depth)*2;
-                                       }
-                               } else if (c != '\0')
-                                       ofs << c;
-                               else if (c == '\0')
-                                       lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
-                               ++currlinelen;
-                               break;
-                       }
+                       lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
+                              << endl;
                }
-               par = par->next;
+#endif
        }
-   
-       ofs << "\n";
+       
+       return status;
 }
-//----------------------------------------------------------------------------
-#else
-//----------------------------------------------------------------------------
-string const Buffer::asciiParagraph(LyXParagraph const * par, int linelen) const
+
+
+string const Buffer::asciiParagraph(LyXParagraph const * par,
+                                   unsigned int linelen) const
 {
        ostringstream buffer;
-       LyXFont font1, font2;
+       LyXFont font1;
+       LyXFont font2;
        Inset const * inset;
-       char c, footnoteflag = 0, depth = 0;
-       string tmp;
-       LyXParagraph::size_type i;
-       int j;
+       char c;
+#ifndef NEW_INSETS
+       LyXParagraph::footnote_flag footnoteflag = LyXParagraph::NO_FOOTNOTE;
+#endif
+       char depth = 0;
        int ltype = 0;
        int ltype_depth = 0;
-       int currlinelen = 0;
+       unsigned int currlinelen = 0;
        bool ref_printed = false;
 
        int noparbreak = 0;
@@ -1491,16 +1307,15 @@ string const Buffer::asciiParagraph(LyXParagraph const * par, int linelen) const
                if (footnoteflag != par->footnoteflag) {
                        footnoteflag = par->footnoteflag;
                        if (footnoteflag) {
-                               j = strlen(string_footnotekinds[par->footnotekind])+4;
+                               size_t const j = strlen(string_footnotekinds[par->footnotekind]) + 4;
                                if ((linelen > 0) &&
                                    ((currlinelen + j) > linelen)) {
                                        buffer << "\n";
                                        currlinelen = 0;
                                }
-                               buffer <<
-                                   "([" <<
-                                   string_footnotekinds[par->footnotekind] <<
-                                   "] ";
+                               buffer << "(["
+                                      << string_footnotekinds[par->footnotekind]
+                                      << "] ";
                                currlinelen += j;
                        }
                }
@@ -1520,7 +1335,7 @@ string const Buffer::asciiParagraph(LyXParagraph const * par, int linelen) const
                }
                
                /* First write the layout */
-               tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
+               string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
                if (tmp == "Itemize") {
                        ltype = 1;
                        ltype_depth = depth+1;
@@ -1569,24 +1384,35 @@ string const Buffer::asciiParagraph(LyXParagraph const * par, int linelen) const
 #endif
        }
       
-       font1 = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
-       for (i = 0; i < par->size(); ++i) {
-               if (!i && !footnoteflag && !noparbreak){
-                       buffer << "\n\n";
-                       for(j = 0; j < depth; ++j)
+       font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
+       for (LyXParagraph::size_type i = 0; i < par->size(); ++i) {
+               if (!i &&
+#ifndef NEW_INSETS
+                   !footnoteflag &&
+#endif
+                   !noparbreak) {
+                       if (linelen > 0)
+                               buffer << "\n\n";
+                       for (char j = 0; j < depth; ++j)
                                buffer << "  ";
                        currlinelen = depth * 2;
-                       switch(ltype) {
+                       switch (ltype) {
                        case 0: /* Standard */
                        case 4: /* (Sub)Paragraph */
                        case 5: /* Description */
                                break;
                        case 6: /* Abstract */
-                               buffer << "Abstract\n\n";
+                               if (linelen > 0)
+                                       buffer << "Abstract\n\n";
+                               else
+                                       buffer << "Abstract: ";
                                break;
                        case 7: /* Bibliography */
                                if (!ref_printed) {
-                                       buffer << "References\n\n";
+                                       if (linelen > 0)
+                                               buffer << "References\n\n";
+                                       else
+                                               buffer << "References: ";
                                        ref_printed = true;
                                }
                                break;
@@ -1595,7 +1421,7 @@ string const Buffer::asciiParagraph(LyXParagraph const * par, int linelen) const
                                break;
                        }
                        if (ltype_depth > depth) {
-                               for(j = ltype_depth - 1; j > depth; --j)
+                               for (char j = ltype_depth - 1; j > depth; --j)
                                        buffer << "  ";
                                currlinelen += (ltype_depth-depth)*2;
                        }
@@ -1617,7 +1443,7 @@ string const Buffer::asciiParagraph(LyXParagraph const * par, int linelen) const
                        if ((inset = par->GetInset(i))) {
                                if (!inset->Ascii(this, buffer)) {
                                        string dummy;
-                                       string s = rsplit(buffer.str(),
+                                       string s = rsplit(buffer.str().c_str(),
                                                          dummy, '\n');
                                        currlinelen += s.length();
                                } else {
@@ -1627,12 +1453,14 @@ string const Buffer::asciiParagraph(LyXParagraph const * par, int linelen) const
                        }
                        break;
                case LyXParagraph::META_NEWLINE:
-                       buffer << "\n";
-                       for(j = 0; j < depth; ++j)
-                               buffer << "  ";
+                       if (linelen > 0) {
+                               buffer << "\n";
+                               for (char j = 0; j < depth; ++j)
+                                       buffer << "  ";
+                       }
                        currlinelen = depth * 2;
                        if (ltype_depth > depth) {
-                               for(j = ltype_depth;
+                               for (char j = ltype_depth;
                                    j > depth; --j)
                                        buffer << "  ";
                                currlinelen += (ltype_depth - depth) * 2;
@@ -1649,11 +1477,11 @@ string const Buffer::asciiParagraph(LyXParagraph const * par, int linelen) const
                            (c == ' ') && ((i + 2) < par->size()))
                        {
                                buffer << "\n";
-                               for(j = 0; j < depth; ++j)
+                               for (char j = 0; j < depth; ++j)
                                        buffer << "  ";
                                currlinelen = depth * 2;
                                if (ltype_depth > depth) {
-                                       for(j = ltype_depth;
+                                       for (char j = ltype_depth;
                                            j > depth; --j)
                                                buffer << "  ";
                                        currlinelen += (ltype_depth-depth)*2;
@@ -1666,7 +1494,7 @@ string const Buffer::asciiParagraph(LyXParagraph const * par, int linelen) const
                        break;
                }
        }
-       return buffer.str();
+       return buffer.str().c_str();
 }
 
 
@@ -1690,7 +1518,7 @@ void Buffer::writeFileAscii(ostream & ofs, int linelen)
        }
        ofs << "\n";
 }
-#endif
+
 
 void Buffer::makeLaTeXFile(string const & fname, 
                           string const & original_path,
@@ -1820,17 +1648,21 @@ void Buffer::makeLaTeXFile(string const & fname,
                
                // language should be a parameter to \documentclass
                bool use_babel = false;
-               if (params.language_info->lang() == "hebrew") // This seems necessary
+               if (params.language->babel() == "hebrew") // This seems necessary
                        features.UsedLanguages.insert(default_language);
-               if (params.language != "default" ||
-                   !features.UsedLanguages.empty() ) {
+#ifdef DO_USE_DEFAULT_LANGUAGE
+               if (params.language->lang() != "default" ||
+                   !features.UsedLanguages.empty()) {
+#endif
                        use_babel = true;
                        for (LaTeXFeatures::LanguageList::const_iterator cit =
                                     features.UsedLanguages.begin();
                             cit != features.UsedLanguages.end(); ++cit)
-                               options += (*cit)->lang() + ",";
-                       options += params.language_info->lang() + ',';
+                               options += (*cit)->babel() + ",";
+                       options += params.language->babel() + ',';
+#ifdef DO_USE_DEFAULT_LANGUAGE
                }
+#endif
 
                // the user-defined options
                if (!params.options.empty()) {
@@ -1862,7 +1694,7 @@ void Buffer::makeLaTeXFile(string const & fname,
 
                if (params.inputenc == "auto") {
                        string const doc_encoding =
-                               params.language_info->encoding()->LatexName();
+                               params.language->encoding()->LatexName();
 
                        // Create a list with all the input encodings used 
                        // in the document
@@ -1874,9 +1706,8 @@ void Buffer::makeLaTeXFile(string const & fname,
                                        encodings.insert((*it)->encoding()->LatexName());
 
                        ofs << "\\usepackage[";
-                       for (set<string>::const_iterator it = encodings.begin();
-                            it != encodings.end(); ++it)
-                               ofs << *it << ",";
+                       std::copy(encodings.begin(), encodings.end(),
+                                 std::ostream_iterator<string>(ofs, ","));
                        ofs << doc_encoding << "]{inputenc}\n";
                        texrow.newline();
                } else if (params.inputenc != "default") {
@@ -2130,9 +1961,13 @@ void Buffer::makeLaTeXFile(string const & fname,
                texrow.newline();
        } // only_body
        lyxerr.debug() << "preamble finished, now the body." << endl;
-       if (!lyxrc.language_auto_begin && params.language != "default") {
+#ifdef DO_USE_DEFAULT_LANGUAGE
+       if (!lyxrc.language_auto_begin && params.language->lang() != "default") {
+#else
+       if (!lyxrc.language_auto_begin) {
+#endif
                ofs << subst(lyxrc.language_command_begin, "$$lang",
-                            params.language)
+                            params.language->babel())
                    << endl;
                texrow.newline();
        }
@@ -2143,9 +1978,13 @@ void Buffer::makeLaTeXFile(string const & fname,
        ofs << endl;
        texrow.newline();
 
-       if (!lyxrc.language_auto_end && params.language != "default") {
+#ifdef DO_USE_DEFAULT_LANGUAGE
+       if (!lyxrc.language_auto_end && params.language->lang() != "default") {
+#else
+               if (!lyxrc.language_auto_end) {
+#endif
                ofs << subst(lyxrc.language_command_end, "$$lang",
-                            params.language)
+                            params.language->babel())
                    << endl;
                texrow.newline();
        }
@@ -2293,14 +2132,16 @@ bool Buffer::isSGML() const
 void Buffer::sgmlOpenTag(ostream & os, int depth,
                         string const & latexname) const
 {
-       os << string(depth, ' ') << "<" << latexname << ">\n";
+       if (latexname != "!-- --")
+               os << string(depth, ' ') << "<" << latexname << ">\n";
 }
 
 
 void Buffer::sgmlCloseTag(ostream & os, int depth,
                          string const & latexname) const
 {
-       os << string(depth, ' ') << "</" << latexname << ">\n";
+       if (latexname != "!-- --")
+               os << string(depth, ' ') << "</" << latexname << ">\n";
 }
 
 
@@ -2329,7 +2170,7 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
        LaTeXFeatures features(params, tclass.numLayouts());
        validate(features);
 
-       //if(nice)
+       //if (nice)
        tex_code_break_column = lyxrc.ascii_linelen;
        //else
        //tex_code_break_column = 0;
@@ -2337,7 +2178,7 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
        texrow.reset();
 
        if (!body_only) {
-               string sgml_includedfiles=features.getIncludedFiles();
+               string sgml_includedfiles=features.getIncludedFiles(fname);
 
                if (params.preamble.empty() && sgml_includedfiles.empty()) {
                        ofs << "<!doctype linuxdoc system>\n\n";
@@ -2346,7 +2187,7 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
                            << params.preamble << sgml_includedfiles << " \n]>\n\n";
                }
 
-               if(params.options.empty())
+               if (params.options.empty())
                        sgmlOpenTag(ofs, 0, top_element);
                else {
                        string top = top_element;
@@ -2391,11 +2232,11 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
                // write opening SGML tags
                switch (style.latextype) {
                case LATEX_PARAGRAPH:
-                       if(depth == par->depth 
+                       if (depth == par->depth 
                           && !environment_stack[depth].empty()) {
                                sgmlCloseTag(ofs, depth, environment_stack[depth]);
                                environment_stack[depth].erase();
-                               if(depth) 
+                               if (depth) 
                                        --depth;
                                else
                                        ofs << "</p>";
@@ -2434,7 +2275,7 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
                               environment_stack[depth].erase();
                        }
                        if (environment_stack[depth] != style.latexname()) {
-                               if(depth == 0) {
+                               if (depth == 0) {
                                        string const temp = "p";
                                        sgmlOpenTag(ofs, depth, temp);
                                }
@@ -2442,11 +2283,11 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
                                sgmlOpenTag(ofs, depth,
                                            environment_stack[depth]);
                        }
-                       if(style.latextype == LATEX_ENVIRONMENT) break;
+                       if (style.latextype == LATEX_ENVIRONMENT) break;
 
                        desc_on = (style.labeltype == LABEL_MANUAL);
 
-                       if(desc_on)
+                       if (desc_on)
                                item_name = "tag";
                        else
                                item_name = "item";
@@ -2472,7 +2313,7 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
 
                ofs << "\n";
                // write closing SGML tags
-               switch(style.latextype) {
+               switch (style.latextype) {
                case LATEX_COMMAND:
                case LATEX_ENVIRONMENT:
                case LATEX_ITEM_ENVIRONMENT:
@@ -2484,10 +2325,10 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
        }
    
        // Close open tags
-       for(; depth > 0; --depth)
+       for (; depth > 0; --depth)
                sgmlCloseTag(ofs, depth, environment_stack[depth]);
 
-       if(!environment_stack[depth].empty())
+       if (!environment_stack[depth].empty())
                sgmlCloseTag(ofs, depth, environment_stack[depth]);
 
        if (!body_only) {
@@ -2502,7 +2343,7 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
 
 #ifndef NEW_INSETS
 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
-                                   int const depth)
+                                   int depth)
 {
        string const tag = "footnote";
 
@@ -2517,7 +2358,7 @@ void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
 
 
 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
-                                 int const depth, int desc_on,
+                                 int depth, int desc_on,
                                  LyXParagraph * & par)
 {
        LyXParagraph * tpar = par;
@@ -2536,7 +2377,7 @@ void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
                SimpleDocBookOnePar(os, extra_par, tpar,
                                    desc_on, depth + 2);
                sgmlCloseTag(os, depth+1, inner_tag);
-               if(!extra_par.empty())
+               if (!extra_par.empty())
                        os << extra_par;
        }
 }
@@ -2544,7 +2385,7 @@ void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
 
 #ifndef NEW_INSETS
 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
-                                  int const depth)
+                                  int depth)
 {
        string tag, inner_tag;
        string tmp_par, extra_par;
@@ -2635,9 +2476,9 @@ void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
                par = par->next;
        }
        os << tmp_par;
-       if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
-       if(!extra_par.empty()) os << extra_par;
-       if(!tag.empty()) sgmlCloseTag(os, depth, tag);
+       if (!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
+       if (!extra_par.empty()) os << extra_par;
+       if (!tag.empty()) sgmlCloseTag(os, depth, tag);
 }
 #endif
 
@@ -2646,7 +2487,9 @@ void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
 void Buffer::push_tag(ostream & os, string const & tag,
                      int & pos, char stack[5][3])
 {
+#ifdef WITH_WARNINGS
 #warning Use a real stack! (Lgb)
+#endif
        // pop all previous tags
        for (int j = pos; j >= 0; --j)
                os << "</" << stack[j] << ">";
@@ -2667,7 +2510,9 @@ void Buffer::pop_tag(ostream & os, string const & tag,
 #warning Use a real stack! (Lgb)
 #endif
        // Please, Lars, do not remove the global variable. I already
-       // had to reintroduce it twice! (JMarc) 
+       // had to reintroduce it twice! (JMarc)
+       // but...but... I'll remove it anyway. (well not quite) (Lgb)
+#if 0
        int j;
        
         // pop all tags till specified one
@@ -2680,9 +2525,25 @@ void Buffer::pop_tag(ostream & os, string const & tag,
         // push all tags, but the specified one
         for (j = j + 1; j <= pos; ++j) {
                 os << "<" << stack[j] << ">";
-                strcpy(stack[j-1], stack[j]);
+                strcpy(stack[j - 1], stack[j]);
+        }
+        --pos;
+#else
+        // pop all tags till specified one
+       int j = pos;
+        for (int j = pos; (j >= 0) && (strcmp(stack[j], tag.c_str())); --j)
+                os << "</" << stack[j] << ">";
+
+        // closes the tag
+        os << "</" << tag << ">";
+       
+        // push all tags, but the specified one
+        for (int i = j + 1; i <= pos; ++i) {
+                os << "<" << stack[i] << ">";
+                strcpy(stack[i - 1], stack[i]);
         }
         --pos;
+#endif
 }
 
 
@@ -2691,8 +2552,8 @@ void Buffer::pop_tag(ostream & os, string const & tag,
 // checks, if newcol chars should be put into this line
 // writes newline, if necessary.
 static
-void linux_doc_line_break(ostream & os, unsigned int & colcount,
-                         const unsigned int newcol)
+void linux_doc_line_break(ostream & os, string::size_type & colcount,
+                         string::size_type newcol)
 {
        colcount += newcol;
        if (colcount > lyxrc.ascii_linelen) {
@@ -2703,7 +2564,7 @@ void linux_doc_line_break(ostream & os, unsigned int & colcount,
 
 
 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
-                                 int desc_on, int const /*depth*/)
+                                 int desc_on, int /*depth*/)
 {
        LyXFont font1;
        char c;
@@ -2721,7 +2582,7 @@ void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
        int stack_num = -1;          // style stack position
        // Can this be rewritten to use a std::stack, please. (Lgb)
        char stack[5][3];            // style stack 
-        unsigned int char_line_count = 5;     // Heuristic choice ;-) 
+        string::size_type char_line_count = 5;     // Heuristic choice ;-) 
 
        if (style.labeltype != LABEL_MANUAL)
                main_body = 0;
@@ -2752,7 +2613,7 @@ void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
                LyXFont const font2 = par->getFont(params, i);
 
                if (font1.family() != font2.family()) {
-                       switch(family_type) {
+                       switch (family_type) {
                        case 0:
                                if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
                                        push_tag(os, "tt", stack_num, stack);
@@ -2796,7 +2657,7 @@ void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
 
                // handle italic and slanted fonts
                if (font1.shape() != font2.shape()) {
-                       switch(shape_type) {
+                       switch (shape_type) {
                        case 0:
                                if (font2.shape() == LyXFont::ITALIC_SHAPE) {
                                        push_tag(os, "it", stack_num, stack);
@@ -2886,7 +2747,7 @@ void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
        }
 
        // resets description flag correctly
-       switch(desc_on){
+       switch (desc_on){
        case 1:
                // <tag> not closed...
                linux_doc_line_break(os, char_line_count, 6);
@@ -2941,7 +2802,7 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
        LaTeXFeatures features(params, tclass.numLayouts());
        validate(features);
 
-       //if(nice)
+       //if (nice)
        tex_code_break_column = lyxrc.ascii_linelen;
        //else
        //tex_code_break_column = 0;
@@ -2954,8 +2815,8 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
    
        texrow.reset();
 
-       if(!only_body) {
-               string sgml_includedfiles=features.getIncludedFiles();
+       if (!only_body) {
+               string sgml_includedfiles=features.getIncludedFiles(fname);
 
                ofs << "<!doctype " << top_element
                    << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
@@ -2965,15 +2826,15 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
                else
                        ofs << "\n [ " << params.preamble 
                            << sgml_includedfiles << " \n]>\n\n";
+       }
 
-               if(params.options.empty())
-                       sgmlOpenTag(ofs, 0, top_element);
-               else {
-                       string top = top_element;
-                       top += " ";
-                       top += params.options;
-                       sgmlOpenTag(ofs, 0, top);
-               }
+       if (params.options.empty())
+               sgmlOpenTag(ofs, 0, top_element);
+       else {
+               string top = top_element;
+               top += " ";
+               top += params.options;
+               sgmlOpenTag(ofs, 0, top);
        }
 
        ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
@@ -2986,12 +2847,12 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
                                            par->layout);
 
                // environment tag closing
-               for; depth > par->depth; --depth) {
-                       if(environment_inner[depth] != "!-- --") {
+               for (; depth > par->depth; --depth) {
+                       if (environment_inner[depth] != "!-- --") {
                                item_name= "listitem";
                                sgmlCloseTag(ofs, command_depth + depth,
                                             item_name);
-                               ifenvironment_inner[depth] == "varlistentry")
+                               if (environment_inner[depth] == "varlistentry")
                                        sgmlCloseTag(ofs, depth+command_depth,
                                                     environment_inner[depth]);
                        }
@@ -3001,14 +2862,14 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
                        environment_inner[depth].erase();
                }
 
-               if(depth == par->depth
+               if (depth == par->depth
                   && environment_stack[depth] != style.latexname()
                   && !environment_stack[depth].empty()) {
-                       if(environment_inner[depth] != "!-- --") {
+                       if (environment_inner[depth] != "!-- --") {
                                item_name= "listitem";
                                sgmlCloseTag(ofs, command_depth+depth,
                                             item_name);
-                               ifenvironment_inner[depth] == "varlistentry")
+                               if (environment_inner[depth] == "varlistentry")
                                        sgmlCloseTag(ofs,
                                                     depth + command_depth,
                                                     environment_inner[depth]);
@@ -3022,11 +2883,9 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
                 }
 
                // Write opening SGML tags.
-               switch(style.latextype) {
+               switch (style.latextype) {
                case LATEX_PARAGRAPH:
-                       if(style.latexname() != "dummy")
-                               sgmlOpenTag(ofs, depth+command_depth,
-                                           style.latexname());
+                       sgmlOpenTag(ofs, depth+command_depth, style.latexname());
                        break;
 
                case LATEX_COMMAND:
@@ -3042,18 +2901,18 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
                        
                        cmd_depth= lyx::atoi(c_depth);
                        
-                       if(command_flag) {
-                               if(cmd_depth<command_base) {
-                                       for(int j = command_depth;
+                       if (command_flag) {
+                               if (cmd_depth<command_base) {
+                                       for (int j = command_depth;
                                            j >= command_base; --j)
-                                               if(!command_stack[j].empty())
+                                               if (!command_stack[j].empty())
                                                        sgmlCloseTag(ofs, j, command_stack[j]);
                                        command_depth= command_base= cmd_depth;
-                               } else if(cmd_depth <= command_depth) {
-                                       for(int j = command_depth;
+                               } else if (cmd_depth <= command_depth) {
+                                       for (int j = command_depth;
                                            j >= cmd_depth; --j)
 
-                                               if(!command_stack[j].empty())
+                                               if (!command_stack[j].empty())
                                                        sgmlCloseTag(ofs, j, command_stack[j]);
                                        command_depth= cmd_depth;
                                } else
@@ -3079,7 +2938,8 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
 
                        sgmlOpenTag(ofs, depth + command_depth, command_name);
                        item_name = "title";
-                       sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
+                       if (command_name != "!-- --")
+                               sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
                        break;
 
                case LATEX_ENVIRONMENT:
@@ -3095,7 +2955,7 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
                                sgmlOpenTag(ofs, depth + command_depth,
                                            environment_stack[depth]);
                        } else {
-                               if(environment_inner[depth] != "!-- --") {
+                               if (environment_inner[depth] != "!-- --") {
                                        item_name= "listitem";
                                        sgmlCloseTag(ofs,
                                                     command_depth + depth,
@@ -3107,8 +2967,8 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
                                }
                        }
                        
-                       if(style.latextype == LATEX_ENVIRONMENT) {
-                               if(!style.latexparam().empty())
+                       if (style.latextype == LATEX_ENVIRONMENT) {
+                               if (!style.latexparam().empty())
                                        sgmlOpenTag(ofs, depth + command_depth,
                                                    style.latexparam());
                                break;
@@ -3116,7 +2976,7 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
 
                        desc_on = (style.labeltype == LABEL_MANUAL);
 
-                       if(desc_on)
+                       if (desc_on)
                                environment_inner[depth]= "varlistentry";
                        else
                                environment_inner[depth]= "listitem";
@@ -3124,7 +2984,7 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
                        sgmlOpenTag(ofs, depth + 1 + command_depth,
                                    environment_inner[depth]);
 
-                       if(desc_on) {
+                       if (desc_on) {
                                item_name= "term";
                                sgmlOpenTag(ofs, depth + 1 + command_depth,
                                            item_name);
@@ -3155,41 +3015,39 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
 #endif
                string end_tag;
                // write closing SGML tags
-               switch(style.latextype) {
+               switch (style.latextype) {
                case LATEX_COMMAND:
                        end_tag = "title";
-                       sgmlCloseTag(ofs, depth + command_depth, end_tag);
+                       if (command_name != "!-- --")
+                               sgmlCloseTag(ofs, depth + command_depth, end_tag);
                        break;
                case LATEX_ENVIRONMENT:
-                       if(!style.latexparam().empty())
+                       if (!style.latexparam().empty())
                                sgmlCloseTag(ofs, depth + command_depth,
                                             style.latexparam());
                        break;
                case LATEX_ITEM_ENVIRONMENT:
-                       if(desc_on == 1) break;
+                       if (desc_on == 1) break;
                        end_tag= "para";
                        sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
                        break;
                case LATEX_PARAGRAPH:
-                       if(style.latexname() != "dummy")
-                               sgmlCloseTag(ofs, depth + command_depth,
-                                            style.latexname());
+                       sgmlCloseTag(ofs, depth + command_depth, style.latexname());
                        break;
                default:
-                       sgmlCloseTag(ofs, depth + command_depth,
-                                    style.latexname());
+                       sgmlCloseTag(ofs, depth + command_depth, style.latexname());
                        break;
                }
        }
 
        // Close open tags
-       for(; depth >= 0; --depth) {
-               if(!environment_stack[depth].empty()) {
-                       if(environment_inner[depth] != "!-- --") {
+       for (; depth >= 0; --depth) {
+               if (!environment_stack[depth].empty()) {
+                       if (environment_inner[depth] != "!-- --") {
                                item_name= "listitem";
                                sgmlCloseTag(ofs, command_depth + depth,
                                             item_name);
-                               ifenvironment_inner[depth] == "varlistentry")
+                               if (environment_inner[depth] == "varlistentry")
                                       sgmlCloseTag(ofs, depth + command_depth,
                                                    environment_inner[depth]);
                        }
@@ -3199,14 +3057,12 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
                }
        }
        
-       for(int j = command_depth; j >= command_base; --j)
-               if(!command_stack[j].empty())
+       for (int j = command_depth; j >= command_base; --j)
+               if (!command_stack[j].empty())
                        sgmlCloseTag(ofs, j, command_stack[j]);
 
-       if (!only_body) {
-               ofs << "\n\n";
-               sgmlCloseTag(ofs, 0, top_element);
-       }
+       ofs << "\n\n";
+       sgmlCloseTag(ofs, 0, top_element);
 
        ofs.close();
        // How to check for successful close
@@ -3215,7 +3071,7 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
 
 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
                                 LyXParagraph * par, int & desc_on,
-                                int const depth) 
+                                int depth) const
 {
        bool emph_flag = false;
 
@@ -3232,7 +3088,7 @@ void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
        LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
        
        int char_line_count = depth;
-       if(!style.free_spacing)
+       if (!style.free_spacing)
                for (int j = 0; j < depth; ++j)
                        os << ' ';
 
@@ -3270,9 +3126,9 @@ void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
                        //   and title should come first
                        //         desc_on == 4
                        //
-                       if(desc_on!= 3 || i!= 0) {
-                               if(!tmp_out.empty() && tmp_out[0] == '@') {
-                                       if(desc_on == 4)
+                       if (desc_on!= 3 || i!= 0) {
+                               if (!tmp_out.empty() && tmp_out[0] == '@') {
+                                       if (desc_on == 4)
                                                extra += frontStrip(tmp_out, '@');
                                        else
                                                os << frontStrip(tmp_out, '@');
@@ -3315,7 +3171,7 @@ void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
        }
        
        // resets description flag correctly
-       switch(desc_on){
+       switch (desc_on){
        case 1:
                // <term> not closed...
                os << "</term>";
@@ -3325,144 +3181,6 @@ void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
 }
 
 
-int Buffer::runLiterate()
-{
-       if (!users->text) return 0;
-
-       ProhibitInput(users);
-
-       // get LaTeX-Filename
-       string name = getLatexName();
-        // get Literate-Filename
-        string lit_name = OnlyFilename(ChangeExtension (getLatexName(), 
-                                          lyxrc.literate_extension));
-
-       string path = OnlyPath(filename);
-
-       string org_path = path;
-       if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
-               path = tmppath;  
-       }
-
-       Path p(path); // path to Literate file
-       users->owner()->getMiniBuffer()->Set(_("Running Literate..."));   
-
-       // Remove all error insets
-       bool removedErrorInsets = users->removeAutoInsets();
-
-       // generate the Literate file if necessary
-       makeLaTeXFile(lit_name, org_path, false);
-
-       string latex_command = lyxrc.pdf_mode ?
-               lyxrc.pdflatex_command : lyxrc.latex_command;
-        Literate literate(latex_command, name, filepath, 
-                         lit_name,
-                         lyxrc.literate_command, lyxrc.literate_error_filter,
-                         lyxrc.build_command, lyxrc.build_error_filter);
-       TeXErrors terr;
-       int res = literate.weave(terr, users->owner()->getMiniBuffer());
-
-       // check return value from literate.weave().
-       if ((res & Literate::NO_LOGFILE)) {
-               WriteAlert(_("Literate command did not work!"),
-                          _("Missing log file:"), name);
-       } else if ((res & Literate::ERRORS)) {
-               users->owner()->getMiniBuffer()->Set(_("Done"));
-               // Insert all errors as errors boxes
-               users->insertErrors(terr);
-               
-               // Dvi should also be kept dirty if the latex run
-               // ends up with errors. However it should be possible
-               // to view a dirty dvi too.
-       } else {
-               //no errors or any other things to think about so:
-               users->owner()->getMiniBuffer()->Set(_("Done"));
-       }
-
-       // if we removed error insets before we ran LaTeX or if we inserted
-       // error insets after we ran LaTeX this must be run:
-        if (removedErrorInsets || (res & Literate::ERRORS)){
-                users->redraw();
-                users->fitCursor();
-                //users->updateScrollbar();
-        }
-        AllowInput(users);
-        return literate.getNumErrors();
-}
-
-
-int Buffer::buildProgram()
-{
-        if (!users->text) return 0;
-        ProhibitInput(users);
-        // get LaTeX-Filename
-        string name = getLatexName();
-        // get Literate-Filename
-        string lit_name = OnlyFilename(ChangeExtension(getLatexName(), 
-                                                      lyxrc.literate_extension));
-        string path = OnlyPath(filename);
-        string org_path = path;
-        if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
-                path = tmppath;  
-        }
-        Path p(path); // path to Literate file
-        users->owner()->getMiniBuffer()->Set(_("Building Program..."));   
-        // Remove all error insets
-        bool removedErrorInsets = users->removeAutoInsets();
-        // generate the LaTeX file if necessary
-        if (!isNwClean() || removedErrorInsets) {
-                makeLaTeXFile(lit_name, org_path, false);
-                markNwDirty();
-        }
-
-       string latex_command = lyxrc.pdf_mode ?
-               lyxrc.pdflatex_command : lyxrc.latex_command;
-        Literate literate(latex_command, name, filepath, 
-                         lit_name,
-                         lyxrc.literate_command, lyxrc.literate_error_filter,
-                         lyxrc.build_command, lyxrc.build_error_filter);
-        TeXErrors terr;
-        int const res = literate.build(terr, users->owner()->getMiniBuffer());
-        // check return value from literate.build().
-        if ((res & Literate::NO_LOGFILE)) {
-                WriteAlert(_("Build did not work!"),
-                           _("Missing log file:"), name);
-        } else if ((res & Literate::ERRORS)) {
-                users->owner()->getMiniBuffer()->Set(_("Done"));
-                // Insert all errors as errors boxes
-               users->insertErrors(terr);
-                
-                // Literate files should also be kept dirty if the literate 
-                // command run ends up with errors.
-        } else {
-                //no errors or any other things to think about so:
-                users->owner()->getMiniBuffer()->Set(_("Done"));
-                markNwClean();
-        }
-        // if we removed error insets before we ran Literate/Build or
-       // if we inserted error insets after we ran Literate/Build this
-       // must be run:
-       if (removedErrorInsets || (res & Literate::ERRORS)){
-               users->redraw();
-               users->fitCursor();
-               //users->updateScrollbar();
-       }
-       AllowInput(users);
-
-       return literate.getNumErrors();
-}
-
-
 // This should be enabled when the Chktex class is implemented. (Asger)
 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
 // Other flags: -wall -v0 -x
@@ -3506,8 +3224,7 @@ int Buffer::runChktex()
        // error insets after we ran chktex, this must be run:
        if (removedErrorInsets || res){
                users->redraw();
-               users->fitCursor();
-               //users->updateScrollbar();
+               users->fitCursor(users->text);
        }
        AllowInput(users);
 
@@ -3641,6 +3358,9 @@ vector<string> const Buffer::getLabelList()
 
 vector<vector<Buffer::TocItem> > const Buffer::getTocList()
 {
+       int figs = 0;
+       int tables = 0;
+       int algs = 0;
        vector<vector<TocItem> > l(4);
        LyXParagraph * par = paragraph;
        while (par) {
@@ -3656,13 +3376,19 @@ vector<vector<Buffer::TocItem> > const Buffer::getTocList()
                                switch (par->footnotekind) {
                                case LyXParagraph::FIG:
                                case LyXParagraph::WIDE_FIG:
+                                       tmp.str = tostr(++figs) + ". "
+                                               + tmp.str;
                                        l[TOC_LOF].push_back(tmp);
                                        break;
                                case LyXParagraph::TAB:
                                case LyXParagraph::WIDE_TAB:
+                                       tmp.str = tostr(++tables) + ". "
+                                               + tmp.str;
                                        l[TOC_LOT].push_back(tmp);
                                        break;
                                case LyXParagraph::ALGORITHM:
+                                       tmp.str = tostr(++algs) + ". "
+                                               + tmp.str;
                                        l[TOC_LOA].push_back(tmp);
                                        break;
                                case LyXParagraph::FOOTNOTE:
@@ -3723,7 +3449,7 @@ vector<pair<string,string> > const Buffer::getBibkeyList()
                        // Search for Bibtex or Include inset
                        if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
                                vector<pair<string,string> > tmp =
-                                       static_cast<InsetBibtex*>(*it)->getKeys();
+                                       static_cast<InsetBibtex*>(*it)->getKeys(this);
                                keys.insert(keys.end(), tmp.begin(), tmp.end());
                        } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
                                vector<pair<string,string> > const tmp =
@@ -3808,7 +3534,7 @@ void Buffer::resizeInsets(BufferView * bv)
 {
        /// then remove all LyXText in text-insets
        LyXParagraph * par = paragraph;
-       for(; par; par = par->next) {
+       for (; par; par = par->next) {
            par->resizeInsetsLyXText(bv);
        }
 }