]> git.lyx.org Git - lyx.git/blobdiff - src/buffer.C
two patches from john
[lyx.git] / src / buffer.C
index f16af67f98e2491950c46cefb9252948b21d3a8e..3e6a4e3a2b11cf6e0d61de0627490985655117af 100644 (file)
 
 #include <config.h>
 
-#include <fstream>
-#include <iomanip>
-#include <map>
-#include <stack>
-#include <list>
-
-#include <cstdlib>
-#include <cmath>
-#include <unistd.h>
-#include <sys/types.h>
-#include <utime.h>
-
-#include <algorithm>
-
-#ifdef HAVE_LOCALE
-#include <locale>
-#endif
-
 #ifdef __GNUG__
 #pragma implementation
 #endif
 #include "bufferview_funcs.h"
 #include "lyxfont.h"
 #include "version.h"
+#include "LaTeX.h"
+#include "Chktex.h"
+#include "LyXView.h"
+#include "debug.h"
+#include "LaTeXFeatures.h"
+#include "lyxtext.h"
+#include "gettext.h"
+#include "language.h"
+#include "encoding.h"
+#include "exporter.h"
+#include "Lsstream.h"
+#include "converter.h"
+#include "BufferView.h"
+#include "ParagraphParameters.h"
+#include "iterators.h"
+#include "lyxtextclasslist.h"
+
 #include "mathed/formulamacro.h"
 #include "mathed/formula.h"
+
 #include "insets/inset.h"
 #include "insets/inseterror.h"
 #include "insets/insetlabel.h"
 #endif
 #include "insets/insetcaption.h"
 #include "insets/insetfloatlist.h"
+
+#include "frontends/Dialogs.h"
+#include "frontends/Alert.h"
+
 #include "support/textutils.h"
 #include "support/filetools.h"
 #include "support/path.h"
 #include "support/os.h"
-#include "LaTeX.h"
-#include "Chktex.h"
-#include "LyXView.h"
-#include "debug.h"
-#include "LaTeXFeatures.h"
 #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"
-#include "lyx_gui_misc.h"      // WarnReadonly()
-#include "frontends/Dialogs.h"
-#include "encoding.h"
-#include "exporter.h"
-#include "Lsstream.h"
-#include "converter.h"
-#include "BufferView.h"
-#include "ParagraphParameters.h"
-#include "iterators.h"
+#include "support/lyxalgo.h" // for lyx::count
+
+#include <fstream>
+#include <iomanip>
+#include <map>
+#include <stack>
+#include <list>
+#include <algorithm>
+
+#include <cstdlib>
+#include <cmath>
+#include <unistd.h>
+#include <sys/types.h>
+#include <utime.h>
+
+
+#ifdef HAVE_LOCALE
+#include <locale>
+#endif
+
 
 using std::ostream;
 using std::ofstream;
@@ -123,6 +130,10 @@ using std::set;
 using std::stack;
 using std::list;
 
+using lyx::pos_type;
+using lyx::layout_type;
+using lyx::textclass_type;
+
 // all these externs should eventually be removed.
 extern BufferList bufferlist;
 
@@ -138,21 +149,26 @@ extern int tex_code_break_column;
 
 
 Buffer::Buffer(string const & file, bool ronly)
+       : paragraph(0), lyx_clean(true), bak_clean(true),
+         unnamed(false), dep_clean(0), read_only(ronly),
+         filename_(file), users(0)
 {
        lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
-       filename = file;
-       filepath = OnlyPath(file);
-       paragraph = 0;
-       lyx_clean = true;
-       bak_clean = true;
-       dep_clean = 0;
-       read_only = ronly;
-       unnamed = false;
-       users = 0;
+//     filename = file;
+       filepath_ = OnlyPath(file);
+//     paragraph = 0;
+//     lyx_clean = true;
+//     bak_clean = true;
+//     dep_clean = 0;
+//     read_only = ronly;
+//     unnamed = false;
+//     users = 0;
        lyxvc.buffer(this);
-       if (read_only || (lyxrc.use_tempdir)) {
+       if (read_only || lyxrc.use_tempdir) {
                tmppath = CreateBufferTmpDir();
-       } else tmppath.erase();
+       } else {
+               tmppath.erase();
+       }
 }
 
 
@@ -184,7 +200,7 @@ Buffer::~Buffer()
 
 string const Buffer::getLatexName(bool no_path) const
 {
-       string name = ChangeExtension(MakeLatexName(filename), ".tex");
+       string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
        if (no_path)
                return OnlyFilename(name);
        else
@@ -234,25 +250,6 @@ void Buffer::setReadonly(bool flag)
                updateTitles();
                users->owner()->getDialogs()->updateBufferDependent(false);
        }
-       if (read_only) {
-               WarnReadonly(filename);
-       }
-}
-
-
-bool Buffer::saveParamsAsDefaults() // const
-{
-       string const fname = AddName(AddPath(user_lyxdir, "templates/"),
-                              "defaults.lyx");
-       Buffer defaults = Buffer(fname);
-       
-       // Use the current buffer's parameters as default
-       defaults.params = params;
-       
-       // add an empty paragraph. Is this enough?
-       defaults.paragraph = new Paragraph;
-
-       return defaults.writeFile(defaults.filename, false);
 }
 
 
@@ -260,7 +257,8 @@ bool Buffer::saveParamsAsDefaults() // const
 // Should work on a list
 void Buffer::updateTitles() const
 {
-       if (users) users->owner()->updateWindowTitle();
+       if (users)
+               users->owner()->updateWindowTitle();
 }
 
 
@@ -268,15 +266,16 @@ void Buffer::updateTitles() const
 // Should work on a list
 void Buffer::resetAutosaveTimers() const
 {
-       if (users) users->owner()->resetAutosaveTimer();
+       if (users)
+               users->owner()->resetAutosaveTimer();
 }
 
 
 void Buffer::setFileName(string const & newfile)
 {
-       filename = MakeAbsPath(newfile);
-       filepath = OnlyPath(filename);
-       setReadonly(IsFileWriteable(filename) == 0);
+       filename_ = MakeAbsPath(newfile);
+       filepath_ = OnlyPath(filename_);
+       setReadonly(IsFileWriteable(filename_) == 0);
        updateTitles();
 }
 
@@ -294,6 +293,7 @@ struct ErtComp
        string contents;
        bool active;
        bool in_tabular;
+       LyXFont font;
 };
 
 std::stack<ErtComp> ert_stack;
@@ -302,6 +302,7 @@ ErtComp ert_comp;
 
 #warning And _why_ is this here? (Lgb)
 int unknown_layouts;
+int unknown_tokens;
 
 } // anon
 
@@ -317,6 +318,7 @@ int unknown_layouts;
 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
 {
        unknown_layouts = 0;
+       unknown_tokens = 0;
 #ifndef NO_COMPABILITY
        ert_comp.contents.erase();
        ert_comp.active = false;
@@ -336,7 +338,7 @@ bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
        } else {
                // We are inserting into an existing document
                users->text->breakParagraph(users);
-               first_par = users->text->firstParagraph();
+               first_par = users->text->ownerParagraph();
                pos = 0;
                markDirty();
                // We don't want to adopt the parameters from the
@@ -379,23 +381,34 @@ bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
                        s += tostr(unknown_layouts);
                        s += _(" paragraphs");
                }
-               WriteAlert(_("Textclass Loading Error!"), s,
+               Alert::alert(_("Textclass Loading Error!"), s,
                           _("When reading " + fileName()));
-       }       
+       }
+
+       if (unknown_tokens > 0) {
+               string s = _("Encountered ");
+               if (unknown_tokens == 1) {
+                       s += _("one unknown token");
+               } else {
+                       s += tostr(unknown_tokens);
+                       s += _(" unknown tokens");
+               }
+               Alert::alert(_("Textclass Loading Error!"), s,
+                          _("When reading " + fileName()));
+       }
 
        return the_end_read;
 }
 
 
 #ifndef NO_COMPABILITY
-void Buffer::insertErtContents(Paragraph * par, int & pos,
-                              LyXFont const & font, bool set_inactive) 
+void Buffer::insertErtContents(Paragraph * par, int & pos, bool set_inactive) 
 {
        if (!ert_comp.contents.empty()) {
-               lyxerr[Debug::INSETS] << "ERT contents:\n"
-                      << ert_comp.contents << endl;
+               lyxerr[Debug::INSETS] << "ERT contents:\n'"
+                                     << ert_comp.contents << "'" << endl;
                Inset * inset = new InsetERT(ert_comp.contents, true);
-               par->insertInset(pos++, inset, font);
+               par->insertInset(pos++, inset, ert_comp.font);
                ert_comp.contents.erase();
        }
        if (set_inactive) {
@@ -448,17 +461,22 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
 #ifndef NO_COMPABILITY
                ert_comp.in_tabular = false;
                // Do the insetert.
-               insertErtContents(par, pos, font);
+               insertErtContents(par, pos);
 #endif
-                lex.eatLine();
-                string const layoutname = lex.getString();
-                pair<bool, LyXTextClass::LayoutList::size_type> pp
-                        = textclasslist.NumberOfLayout(params.textclass,
-                                                       layoutname);
+               lex.eatLine();
+               string const layoutname = lex.getString();
+               //lyxerr << "Looking for layout '"
+               // << layoutname << "'!" << endl;
+               
+               pair<bool, layout_type> pp
+                 = textclasslist.NumberOfLayout(params.textclass, layoutname);
 
+               //lyxerr << "Result: " << pp.first << "/" << pp.second << endl;
+               
 #ifndef NO_COMPABILITY
                if (compare_no_case(layoutname, "latex") == 0) {
                        ert_comp.active = true;
+                       ert_comp.font = font;
                }
 #endif
 #ifdef USE_CAPTION
@@ -529,13 +547,18 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                        } else {
                                // layout not found
                                // use default layout "Standard" (0)
+                               //lyxerr << "Layout '" << layoutname
+                               //       << "' was not found!" << endl;
+                               
                                par->layout = 0;
                                ++unknown_layouts;
                                string const s = _("Layout had to be changed from\n")
                                        + layoutname + _(" to ")
                                        + textclasslist.NameOfLayout(params.textclass, par->layout);
                                InsetError * new_inset = new InsetError(s);
-                               par->insertInset(0, new_inset);
+                               par->insertInset(0, new_inset, 
+                                                LyXFont(LyXFont::ALL_INHERIT,
+                                                        params.language));
                        }
                        // Test whether the layout is obsolete.
                        LyXLayout const & layout =
@@ -557,8 +580,8 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
 
 #ifndef NO_COMPABILITY
        } else if (token == "\\begin_float") {
-               insertErtContents(par, pos, font);
-               //insertErtContents(par, pos, font, false);
+               insertErtContents(par, pos);
+               //insertErtContents(par, pos, false);
                //ert_stack.push(ert_comp);
                //ert_comp = ErtComp();
                
@@ -648,7 +671,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                inset->read(this, nylex);
                par->insertInset(pos, inset, font);
                ++pos;
-               insertErtContents(par, pos, font);
+               insertErtContents(par, pos);
 #endif
        } else if (token == "\\begin_deeper") {
                ++depth;
@@ -663,24 +686,24 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                params.readPreamble(lex);
        } else if (token == "\\textclass") {
                lex.eatLine();
-               pair<bool, LyXTextClassList::size_type> pp = 
+               pair<bool, textclass_type> pp = 
                        textclasslist.NumberOfClass(lex.getString());
                if (pp.first) {
                        params.textclass = pp.second;
                } else {
-                       WriteAlert(string(_("Textclass error")), 
+                       Alert::alert(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)) {
-                               // if the textclass wasn't loaded properly
-                               // we need to either substitute another
-                               // or stop loading the file.
-                               // I can substitute but I don't see how I can
-                               // stop loading... ideas??  ARRae980418
-                       WriteAlert(_("Textclass Loading Error!"),
+                       // if the textclass wasn't loaded properly
+                       // we need to either substitute another
+                       // or stop loading the file.
+                       // I can substitute but I don't see how I can
+                       // stop loading... ideas??  ARRae980418
+                       Alert::alert(_("Textclass Loading Error!"),
                                   string(_("Can't load textclass ")) +
                                   textclasslist.NameOfClass(params.textclass),
                                   _("-- substituting default"));
@@ -719,21 +742,25 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                par->params().startOfAppendix(true);
        } else if (token == "\\paragraph_separation") {
                int tmpret = lex.findToken(string_paragraph_separation);
-               if (tmpret == -1) ++tmpret;
+               if (tmpret == -1)
+                       ++tmpret;
                if (tmpret != LYX_LAYOUT_DEFAULT) 
                        params.paragraph_separation =
                                static_cast<BufferParams::PARSEP>(tmpret);
        } else if (token == "\\defskip") {
                lex.nextToken();
                params.defskip = VSpace(lex.getString());
+#ifndef NO_COMPABILITY
        } else if (token == "\\epsfig") { // obsolete
                // Indeed it is obsolete, but we HAVE to be backwards
                // compatible until 0.14, because otherwise all figures
                // in existing documents are irretrivably lost. (Asger)
                params.readGraphicsDriver(lex);
+#endif
        } else if (token == "\\quotes_language") {
                int tmpret = lex.findToken(string_quotes_language);
-               if (tmpret == -1) ++tmpret;
+               if (tmpret == -1)
+                       ++tmpret;
                if (tmpret != LYX_LAYOUT_DEFAULT) {
                        InsetQuotes::quote_language tmpl = 
                                InsetQuotes::EnglishQ;
@@ -796,7 +823,8 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                params.use_numerical_citations = lex.getInteger();
        } else if (token == "\\paperorientation") {
                int tmpret = lex.findToken(string_orientation);
-               if (tmpret == -1) ++tmpret;
+               if (tmpret == -1)
+                       ++tmpret;
                if (tmpret != LYX_LAYOUT_DEFAULT) 
                        params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
        } else if (token == "\\paperwidth") {
@@ -868,6 +896,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                                //how can I put it back?
                }
        } else if (token == "\\bulletLaTeX") {
+               // The bullet class should be able to read this.
                lex.nextToken();
                int const index = lex.getInteger();
                lex.next();
@@ -884,6 +913,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                        lex.next();
                        temp_str = lex.getString();
                }
+
                params.user_defined_bullets[index].setText(sum_str);
                params.temp_bullets[index].setText(sum_str);
        } else if (token == "\\secnumdepth") {
@@ -954,12 +984,13 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                string const tok = lex.getString();
                if (tok == "no_latex") {
                        // Do the insetert.
-                       insertErtContents(par, pos, font);
+                       insertErtContents(par, pos);
                } else if (tok == "latex") {
                        ert_comp.active = true;
+                       ert_comp.font = font;
                } else if (tok == "default") {
                        // Do the insetert.
-                       insertErtContents(par, pos, font);
+                       insertErtContents(par, pos);
                } else {
                        lex.printError("Unknown LaTeX font flag "
                                       "`$$Token'");
@@ -1050,7 +1081,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                // the inset isn't it? Lgb.
        } else if (token == "\\begin_inset") {
 #ifndef NO_COMPABILITY
-               insertErtContents(par, pos, font, false);
+               insertErtContents(par, pos, false);
                ert_stack.push(ert_comp);
                ert_comp = ErtComp();
 #endif
@@ -1058,7 +1089,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
 #ifndef NO_COMPABILITY
                ert_comp = ert_stack.top();
                ert_stack.pop();
-               insertErtContents(par, pos, font);
+               insertErtContents(par, pos);
 #endif
        } else if (token == "\\SpecialChar") {
                LyXLayout const & layout =
@@ -1066,7 +1097,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                                            par->getLayout());
 
                // Insets don't make sense in a free-spacing context! ---Kayvan
-               if (layout.free_spacing) {
+               if (layout.free_spacing || par->isFreeSpacing()) {
                        if (lex.isOK()) {
                                lex.next();
                                string next_token = lex.getString();
@@ -1096,7 +1127,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                        // Since we cannot know it this is only a regular
                        // newline or a tabular cell delimter we have to
                        // handle the ERT here.
-                       insertErtContents(par, pos, font, false);
+                       insertErtContents(par, pos, false);
 
                        par->insertChar(pos, Paragraph::META_NEWLINE, font);
                        ++pos;
@@ -1124,7 +1155,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                        textclasslist.Style(params.textclass, 
                                            par->getLayout());
 
-               if (layout.free_spacing) {
+               if (layout.free_spacing || par->isFreeSpacing()) {
                        par->insertChar(pos, ' ', font);
                } else {
                        Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
@@ -1152,7 +1183,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
 #ifndef NO_COMPABILITY
                // If we still have some ert active here we have to insert
                // it so we don't loose it. (Lgb)
-               insertErtContents(par, pos, font);
+               insertErtContents(par, pos);
 #endif
                the_end_read = true;
 #ifndef NO_COMPABILITY
@@ -1167,14 +1198,15 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                } else {
 #endif
                // This should be insurance for the future: (Asger)
-               lex.printError("Unknown token `$$Token'. "
-                              "Inserting as text.");
-               string::const_iterator cit = token.begin();
-               string::const_iterator end = token.end();
-               for (; cit != end; ++cit) {
-                       par->insertChar(pos, (*cit), font);
-                       ++pos;
-               }
+               ++unknown_tokens;
+               lex.eatLine();
+               string const s = _("Unknown token: ") + token
+                       + " " + lex.text()  + "\n";
+
+               InsetError * new_inset = new InsetError(s);
+               par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
+                                                        params.language));
+
 #ifndef NO_COMPABILITY
                }
 #endif
@@ -1184,7 +1216,8 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
 #ifndef NO_PEXTRA_REALLY
        // I wonder if we could use this blanket fix for all the
        // checkminipage cases...
-       if (par && par->size()) {
+       // don't forget about ert paragraphs and compatibility read for'em
+       if (par && (par->size() || !ert_comp.contents.empty())) {
                // It is possible that this will check to often,
                // but that should not be an correctness issue.
                // Only a speed issue.
@@ -1198,6 +1231,7 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
        //
        // BEGIN pextra_minipage compability
        // This should be removed in 1.3.x (Lgb)
+       // I don't think we should remove this so fast (Jug)
        
        // This compability code is not perfect. In a couple
        // of rand cases it fails. When the minipage par is
@@ -1244,12 +1278,21 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                        }
                        InsetMinipage * mini = new InsetMinipage;
                        mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
-                       mini->width(par->params().pextraWidth());
+                       mini->pageWidth(LyXLength(par->params().pextraWidth()));
                        if (!par->params().pextraWidthp().empty()) {
-                           lyxerr << "WP:" << mini->width() << endl;
-                           mini->width(tostr(par->params().pextraWidthp())+"%");
+                           lyxerr << "WP:" << mini->pageWidth().asString() << endl;
+                           mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
                        }
+                       Paragraph * op = mini->firstParagraph();
                        mini->inset.paragraph(par);
+                       //
+                       // and free the old ones!
+                       //
+                       while(op) {
+                               Paragraph * pp = op->next();
+                               delete op;
+                               op = pp;
+                       }
                        // Insert the minipage last in the
                        // previous paragraph.
                        if (par->params().pextraHfill()) {
@@ -1286,6 +1329,8 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
                        tmp = tmp->next();
                }
                depth = parBeforeMinipage->params().depth();
+               // and set this depth on the par as it has not been set already
+               par->params().depth(depth);
                minipar = parBeforeMinipage = 0;
        } else if (!minipar &&
                   (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
@@ -1314,10 +1359,10 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
 
                InsetMinipage * mini = new InsetMinipage;
                mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
-               mini->width(minipar->params().pextraWidth());
+               mini->pageWidth(LyXLength(minipar->params().pextraWidth()));
                if (!par->params().pextraWidthp().empty()) {
-                   lyxerr << "WP:" << mini->width() << endl;
-                   mini->width(tostr(par->params().pextraWidthp())+"%");
+                   lyxerr << "WP:" << mini->pageWidth().asString() << endl;
+                   mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
                }
                mini->inset.paragraph(minipar);
                        
@@ -1339,12 +1384,14 @@ Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
 }
 
 // needed to insert the selection
-void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
-                                LyXFont const & font, 
-                                string const & str) const
+void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
+                                 LyXFont const & fn,string const & str) const
 {
        LyXLayout const & layout = textclasslist.Style(params.textclass, 
-                                                    par->getLayout());
+                                                      par->getLayout());
+       LyXFont font = fn;
+       
+       (void)par->checkInsertChar(font);
        // insert the string, don't insert doublespace
        bool space_inserted = true;
        for(string::const_iterator cit = str.begin(); 
@@ -1352,7 +1399,7 @@ void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
                if (*cit == '\n') {
                        if (par->size() || layout.keepempty) { 
                                par->breakParagraph(params, pos, 
-                                                   layout.isEnvironment());
+                                                   layout.isEnvironment());
                                par = par->next();
                                pos = 0;
                                space_inserted = true;
@@ -1360,19 +1407,20 @@ void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
                                continue;
                        }
                        // do not insert consecutive spaces if !free_spacing
-               } else if ((*cit == ' ' || *cit == '\t')
-                          && space_inserted && !layout.free_spacing) {
+               } else if ((*cit == ' ' || *cit == '\t') &&
+                          space_inserted && !layout.free_spacing &&
+                                  !par->isFreeSpacing())
+               {
                        continue;
                } else if (*cit == '\t') {
-                       if (!layout.free_spacing) {
+                       if (!layout.free_spacing && !par->isFreeSpacing()) {
                                // tabs are like spaces here
                                par->insertChar(pos, ' ', font);
                                ++pos;
                                space_inserted = true;
                        } else {
-                               const Paragraph::value_type nb = 8 - pos % 8;
-                               for (Paragraph::size_type a = 0; 
-                                    a < nb ; ++a) {
+                               const pos_type nb = 8 - pos % 8;
+                               for (pos_type a = 0; a < nb ; ++a) {
                                        par->insertChar(pos, ' ', font);
                                        ++pos;
                                }
@@ -1465,8 +1513,8 @@ void Buffer::readInset(LyXLex & lex, Paragraph *& par,
                } else if (tmptok == "Formula") {
                        inset = new InsetFormula;
                } else if (tmptok == "Figure") { // Backward compatibility
-                       inset = new InsetFig(100, 100, *this);
-                       //inset = new InsetGraphics;
+//                     inset = new InsetFig(100, 100, *this);
+                       inset = new InsetGraphics;
                } else if (tmptok == "Graphics") {
                        inset = new InsetGraphics;
                } else if (tmptok == "Info") {// backwards compatibility
@@ -1536,35 +1584,36 @@ bool Buffer::readFile(LyXLex & lex, Paragraph * par)
                                // current format
                        } else if (file_format > LYX_FORMAT) {
                                // future format
-                               WriteAlert(_("Warning!"),
+                               Alert::alert(_("Warning!"),
                                           _("LyX file format is newer that what"),
                                           _("is supported in this LyX version. Expect some problems."));
                                
                        } else if (file_format < LYX_FORMAT) {
                                // old formats
                                if (file_format < 200) {
-                                       WriteAlert(_("ERROR!"),
+                                       Alert::alert(_("ERROR!"),
                                                   _("Old LyX file format found. "
                                                     "Use LyX 0.10.x to read this!"));
                                        return false;
                                }
                        }
                        bool the_end = readLyXformat2(lex, par);
-                       setPaperStuff();
+                       params.setPaperStuff();
                        // the_end was added in 213
                        if (file_format < 213)
                                the_end = true;
 
-                       if (!the_end)
-                               WriteAlert(_("Warning!"),
+                       if (!the_end) {
+                               Alert::alert(_("Warning!"),
                                           _("Reading of document is not complete"),
                                           _("Maybe the document is truncated"));
+                       }
                        return true;
                } else { // "\\lyxformat" not found
-                       WriteAlert(_("ERROR!"), _("Not a LyX file!"));
+                       Alert::alert(_("ERROR!"), _("Not a LyX file!"));
                }
        } else
-               WriteAlert(_("ERROR!"), _("Unable to read file!"));
+               Alert::alert(_("ERROR!"), _("Unable to read file!"));
        return false;
 }
                    
@@ -1653,14 +1702,14 @@ bool Buffer::writeFile(string const & fname, bool flag) const
        // warnings, only cerr.
        // Needed for autosave in background or panic save (Matthias 120496)
 
-       if (read_only && (fname == filename)) {
+       if (read_only && (fname == fileName())) {
                // Here we should come with a question if we should
                // perform the write anyway.
                if (flag)
                        lyxerr << _("Error! Document is read-only: ")
                               << fname << endl;
                else
-                       WriteAlert(_("Error! Document is read-only: "),
+                       Alert::alert(_("Error! Document is read-only: "),
                                   fname);
                return false;
        }
@@ -1673,7 +1722,7 @@ bool Buffer::writeFile(string const & fname, bool flag) const
                        lyxerr << _("Error! Cannot write file: ")
                               << fname << endl;
                else
-                       WriteFSAlert(_("Error! Cannot write file: "),
+                       Alert::err_alert(_("Error! Cannot write file: "),
                                     fname);
                return false;
        }
@@ -1684,7 +1733,7 @@ bool Buffer::writeFile(string const & fname, bool flag) const
                        lyxerr << _("Error! Cannot open file: ")
                               << fname << endl;
                else
-                       WriteFSAlert(_("Error! Cannot open file: "),
+                       Alert::err_alert(_("Error! Cannot open file: "),
                                     fname);
                return false;
        }
@@ -1697,7 +1746,7 @@ bool Buffer::writeFile(string const & fname, bool flag) const
        // The top of the file should not be written by params.
 
        // write out a comment in the top of the file
-       ofs << '#' << LYX_DOCVERSION 
+       ofs << '#' << lyx_docversion 
            << " created this file. For more info see http://www.lyx.org/\n"
            << "\\lyxformat " << LYX_FORMAT << "\n";
 
@@ -1741,178 +1790,219 @@ bool Buffer::writeFile(string const & fname, bool flag) const
 
 
 string const Buffer::asciiParagraph(Paragraph const * par,
-                                   unsigned int linelen) const
+                                    unsigned int linelen,
+                                    bool noparbreak) const
 {
        ostringstream buffer;
+       ostringstream word;
        Paragraph::depth_type depth = 0;
        int ltype = 0;
        Paragraph::depth_type ltype_depth = 0;
-       unsigned int currlinelen = 0;
+       string::size_type currlinelen = 0;
        bool ref_printed = false;
-
-       int noparbreak = 0;
-       int islatex = 0;
-       if (!par->previous()) {
-               // begins or ends a deeper area ?
-               if (depth != par->params().depth()) {
-                       if (par->params().depth() > depth) {
-                               while (par->params().depth() > depth) {
-                                       ++depth;
-                               }
-                       } else {
-                               while (par->params().depth() < depth) {
-                                       --depth;
-                               }
+//     if (!par->previous()) {
+#if 0
+       // begins or ends a deeper area ?
+       if (depth != par->params().depth()) {
+               if (par->params().depth() > depth) {
+                       while (par->params().depth() > depth) {
+                               ++depth;
                        }
-               }
-               
-               // First write the layout
-               string const 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;
+                       while (par->params().depth() < depth) {
+                               --depth;
+                       }
                }
+       }
+#else
+       depth = par->params().depth();
+#endif
                
-               /* maybe some vertical spaces */ 
+       // First write the layout
+       string const 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;
+       }
                
-               /* the labelwidthstring used in lists */ 
+       /* maybe some vertical spaces */ 
                
-               /* some lines? */ 
+       /* the labelwidthstring used in lists */ 
                
-               /* some pagebreaks? */ 
+       /* some lines? */ 
                
-               /* noindent ? */ 
+       /* some pagebreaks? */ 
                
-               /* what about the alignment */ 
-       } else {
-               lyxerr << "Should this ever happen?" << endl;
-       }
-
-       for (Paragraph::size_type i = 0; i < par->size(); ++i) {
-               if (!i && !noparbreak) {
+       /* noindent ? */ 
+               
+       /* what about the alignment */ 
+//     } else {
+//             lyxerr << "Should this ever happen?" << endl;
+//     }
+
+       // linelen <= 0 is special and means we don't have pargraph breaks
+       if (!noparbreak) {
+               if (linelen > 0)
+                       buffer << "\n\n";
+               for (Paragraph::depth_type j = 0; j < depth; ++j)
+                       buffer << "  ";
+               currlinelen = depth * 2;
+               //--
+               // we should probably change to the paragraph language in the
+               // gettext here (if possible) so that strings are outputted in
+               // the correct language! (20012712 Jug)
+               //--    
+               switch (ltype) {
+               case 0: // Standard
+               case 4: // (Sub)Paragraph
+               case 5: // Description
+                       break;
+               case 6: // Abstract
                        if (linelen > 0)
-                               buffer << "\n\n";
-                       for (Paragraph::depth_type j = 0; j < depth; ++j)
-                               buffer << "  ";
-                       currlinelen = depth * 2;
-                       switch (ltype) {
-                       case 0: // Standard
-                       case 4: // (Sub)Paragraph
-                       case 5: // Description
-                               break;
-                       case 6: // Abstract
+                               buffer << _("Abstract") << "\n\n";
+                       else
+                               buffer << _("Abstract: ");
+                       break;
+               case 7: // Bibliography
+                       if (!ref_printed) {
                                if (linelen > 0)
-                                       buffer << "Abstract\n\n";
+                                       buffer << _("References") << "\n\n";
                                else
-                                       buffer << "Abstract: ";
-                               break;
-                       case 7: // Bibliography
-                               if (!ref_printed) {
-                                       if (linelen > 0)
-                                               buffer << "References\n\n";
-                                       else
-                                               buffer << "References: ";
-                                       ref_printed = true;
-                               }
-                               break;
-                       default:
-                               buffer << par->params().labelString() << " ";
-                               break;
+                                       buffer << _("References: ");
+                               ref_printed = true;
                        }
-                       if (ltype_depth > depth) {
-                               for (Paragraph::depth_type j = ltype_depth - 1; 
-                                    j > depth; --j)
-                                       buffer << "  ";
-                               currlinelen += (ltype_depth-depth)*2;
+                       break;
+               default:
+                       buffer << par->params().labelString() << " ";
+                       break;
+               }
+       }
+       string s = buffer.str();
+       if (s.rfind('\n') != string::npos) {
+               string dummy;
+               s = rsplit(buffer.str().c_str(), dummy, '\n');
+       }
+       currlinelen = s.length();
+       if (!currlinelen) {
+               for (Paragraph::depth_type j = 0; j < depth; ++j)
+                       buffer << "  ";
+               currlinelen = depth * 2;
+               if (ltype_depth > depth) {
+                       for (Paragraph::depth_type j = ltype_depth;
+                                j > depth; --j)
+                       {
+                               buffer << "  ";
                        }
+                       currlinelen += (ltype_depth-depth)*2;
                }
-               
+       }
+       // this is to change the linebreak to do it by word a bit more intelligent
+       // hopefully! (only in the case where we have a max linelenght!) (Jug)
+       for (pos_type i = 0; i < par->size(); ++i) {
                char c = par->getUChar(params, i);
-               if (islatex)
-                       continue;
                switch (c) {
                case Paragraph::META_INSET:
                {
                        Inset const * inset = par->getInset(i);
                        if (inset) {
-                               if (!inset->ascii(this, buffer)) {
+                               if (linelen > 0) {
+                                       buffer << word.str();
+                                       word.str("");
+                               }
+                               if (inset->ascii(this, buffer, linelen)) {
+                                       // to be sure it breaks paragraph
+                                       currlinelen += linelen;
+                               }
+#if 0
+                               else {
                                        string dummy;
                                        string const s =
                                                rsplit(buffer.str().c_str(),
                                                       dummy, '\n');
-                                       currlinelen += s.length();
-                               } else {
-                                       // to be sure it breaks paragraph
-                                       currlinelen += linelen;
+                                       currlinelen = s.length();
                                }
+#endif
                        }
                }
                break;
                
                case Paragraph::META_NEWLINE:
                        if (linelen > 0) {
-                               buffer << "\n";
+                               buffer << word.str() << "\n";
+                               word.str("");
                                for (Paragraph::depth_type j = 0; 
                                     j < depth; ++j)
                                        buffer << "  ";
-                       }
-                       currlinelen = depth * 2;
-                       if (ltype_depth > depth) {
-                               for (Paragraph::depth_type j = ltype_depth;
-                                    j > depth; --j)
-                                       buffer << "  ";
-                               currlinelen += (ltype_depth - depth) * 2;
+                               currlinelen = depth * 2;
+                               if (ltype_depth > depth) {
+                                       for (Paragraph::depth_type j = ltype_depth;
+                                                j > depth; --j)
+                                               buffer << "  ";
+                                       currlinelen += (ltype_depth - depth) * 2;
+                               }
                        }
                        break;
                        
-               case Paragraph::META_HFILL: 
-                       buffer << "\t";
+               case Paragraph::META_HFILL:
+                       buffer << word.str() << "\t";
+                       currlinelen += word.str().length() + 1;
+                       word.str("");
                        break;
 
                default:
-                       if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
-                           (c == ' ') && ((i + 2) < par->size()))
-                       {
-                               buffer << "\n";
-                               for (Paragraph::depth_type j = 0; 
-                                    j < depth; ++j)
-                                       buffer << "  ";
-                               currlinelen = depth * 2;
-                               if (ltype_depth > depth) {
-                                       for (Paragraph::depth_type j = ltype_depth;
-                                           j > depth; --j)
+                       if (c == ' ') {
+                               buffer << word.str() << ' ';
+                               currlinelen += word.str().length() + 1;
+                               word.str("");
+                       } else {
+                               if (c != '\0') {
+                                       word << c;
+                               } else {
+                                       lyxerr[Debug::INFO] <<
+                                               "writeAsciiFile: NULL char in structure." << endl;
+                               }
+                               if ((linelen > 0) &&
+                                       (currlinelen+word.str().length()) > linelen)
+                               {
+                                       buffer << "\n";
+                                       for (Paragraph::depth_type j = 0; j < depth; ++j)
                                                buffer << "  ";
-                                       currlinelen += (ltype_depth-depth)*2;
+                                       currlinelen = depth * 2;
+                                       if (ltype_depth > depth) {
+                                               for (Paragraph::depth_type j = ltype_depth;
+                                                        j > depth; --j)
+                                               {
+                                                       buffer << "  ";
+                                               }
+                                               currlinelen += (ltype_depth-depth)*2;
+                                       }
                                }
-                       } else if (c != '\0') {
-                               buffer << c;
-                               ++currlinelen;
-                       } else
-                               lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
+                       }
                        break;
                }
        }
+       buffer << word.str();
        return buffer.str().c_str();
 }
 
@@ -1921,7 +2011,7 @@ void Buffer::writeFileAscii(string const & fname, int linelen)
 {
        ofstream ofs(fname.c_str());
        if (!ofs) {
-               WriteFSAlert(_("Error: Cannot write file:"), fname);
+               Alert::err_alert(_("Error: Cannot write file:"), fname);
                return;
        }
        writeFileAscii(ofs, linelen);
@@ -1932,14 +2022,16 @@ void Buffer::writeFileAscii(ostream & ofs, int linelen)
 {
        Paragraph * par = paragraph;
        while (par) {
-               ofs << asciiParagraph(par, linelen);
+               ofs << asciiParagraph(par, linelen, par->previous() == 0);
                par = par->next();
        }
        ofs << "\n";
 }
 
+
 bool use_babel;
 
+
 void Buffer::makeLaTeXFile(string const & fname, 
                           string const & original_path,
                           bool nice, bool only_body)
@@ -1955,7 +2047,7 @@ void Buffer::makeLaTeXFile(string const & fname,
 
        ofstream ofs(fname.c_str());
        if (!ofs) {
-               WriteFSAlert(_("Error: Cannot open file: "), fname);
+               Alert::err_alert(_("Error: Cannot open file: "), fname);
                return;
        }
        
@@ -1971,7 +2063,7 @@ void Buffer::makeLaTeXFile(string const & fname,
        texrow.start(paragraph, 0);
 
        if (!only_body && nice) {
-               ofs << "%% " LYX_DOCVERSION " created this file.  "
+               ofs << "%% " << lyx_docversion << " created this file.  "
                        "For more info, see http://www.lyx.org/.\n"
                        "%% Do not edit unless you really know what "
                        "you are doing.\n";
@@ -2070,16 +2162,13 @@ void Buffer::makeLaTeXFile(string const & fname,
                if (params.language->babel() == "hebrew"
                    && default_language->babel() != "hebrew")
                         // This seems necessary
-                       features.UsedLanguages.insert(default_language);
+                       features.useLanguage(default_language);
 
                if (lyxrc.language_use_babel ||
                    params.language->lang() != lyxrc.default_language ||
-                   !features.UsedLanguages.empty()) {
+                   !features.hasLanguages()) {
                        use_babel = true;
-                       for (LaTeXFeatures::LanguageList::const_iterator cit =
-                                    features.UsedLanguages.begin();
-                            cit != features.UsedLanguages.end(); ++cit)
-                               language_options << (*cit)->babel() << ',';
+                       language_options << features.getLanguages();
                        language_options << params.language->babel();
                        if (lyxrc.language_global_options)
                                options << language_options.str() << ',';
@@ -2126,12 +2215,7 @@ void Buffer::makeLaTeXFile(string const & fname,
 
                        // Create a list with all the input encodings used 
                        // in the document
-                       set<string> encodings;
-                       for (LaTeXFeatures::LanguageList::const_iterator it =
-                                    features.UsedLanguages.begin();
-                            it != features.UsedLanguages.end(); ++it)
-                               if ((*it)->encoding()->LatexName() != doc_encoding)
-                                       encodings.insert((*it)->encoding()->LatexName());
+                       set<string> encodings = features.getEncodingSet(doc_encoding);
 
                        ofs << "\\usepackage[";
                        std::copy(encodings.begin(), encodings.end(),
@@ -2247,11 +2331,6 @@ void Buffer::makeLaTeXFile(string const & fname,
                        ofs << "}\n";
                        texrow.newline();
                }
-               if (features.amsstyle
-                   && !tclass.provides(LyXTextClass::amsmath)) {
-                       ofs << "\\usepackage{amsmath}\n";
-                       texrow.newline();
-               }
 
                if (tokenPos(tclass.opt_pagestyle(),
                             '|', params.pagestyle) >= 0) {
@@ -2263,19 +2342,6 @@ void Buffer::makeLaTeXFile(string const & fname,
                        texrow.newline();
                }
 
-               // We try to load babel late, in case it interferes
-               // with other packages.
-               if (use_babel) {
-                       string tmp = lyxrc.language_package;
-                       if (!lyxrc.language_global_options
-                           && tmp == "\\usepackage{babel}")
-                               tmp = string("\\usepackage[") +
-                                       language_options.str().c_str() +
-                                       "]{babel}";
-                       ofs << tmp << "\n";
-                       texrow.newline();
-               }
-
                if (params.secnumdepth != tclass.secnumdepth()) {
                        ofs << "\\setcounter{secnumdepth}{"
                            << params.secnumdepth
@@ -2384,12 +2450,27 @@ void Buffer::makeLaTeXFile(string const & fname,
                if (!bullets_def.empty())
                  preamble += bullets_def + "}\n\n";
 
-               for (int j = countChar(preamble, '\n'); j-- ;) {
+               int const nlines =
+                       int(lyx::count(preamble.begin(), preamble.end(), '\n'));
+               for (int j = 0; j != nlines; ++j) {
                        texrow.newline();
                }
 
                ofs << preamble;
 
+               // We try to load babel late, in case it interferes
+               // with other packages.
+               if (use_babel) {
+                       string tmp = lyxrc.language_package;
+                       if (!lyxrc.language_global_options
+                           && tmp == "\\usepackage{babel}")
+                               tmp = string("\\usepackage[") +
+                                       language_options.str().c_str() +
+                                       "]{babel}";
+                       ofs << tmp << "\n";
+                       texrow.newline();
+               }
+
                // make the body.
                ofs << "\\begin{document}\n";
                texrow.newline();
@@ -2441,6 +2522,7 @@ void Buffer::makeLaTeXFile(string const & fname,
        }
        
        lyxerr[Debug::INFO] << "Finished making latex file." << endl;
+       lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
 }
 
 
@@ -2448,33 +2530,41 @@ void Buffer::makeLaTeXFile(string const & fname,
 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
 //
 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
-                            Paragraph * endpar, TexRow & texrow) const
+                             Paragraph * endpar, TexRow & texrow) const
 {
        bool was_title = false;
        bool already_title = false;
 
        // if only_body
        while (par != endpar) {
-               LyXLayout const & layout =
-                       textclasslist.Style(params.textclass,
-                                           par->layout);
-           
-               if (layout.intitle) {
-                       if (already_title) {
-                               lyxerr <<"Error in latexParagraphs: You"
-                                       " should not mix title layouts"
-                                       " with normal ones." << endl;
-                       } else
-                               was_title = true;
-               } else if (was_title && !already_title) {
-                       ofs << "\\maketitle\n";
-                       texrow.newline();
-                       already_title = true;
-                       was_title = false;                  
-               }
-               
-               if (layout.isEnvironment()) {
-                       par = par->TeXEnvironment(this, params, ofs, texrow);
+               Inset * in = par->inInset();
+               // well we have to check if we are in an inset with unlimited
+               // lenght (all in one row) if that is true then we don't allow
+               // any special options in the paragraph and also we don't allow
+               // any environment other then "Standard" to be valid!
+               if ((in == 0) || !in->forceDefaultParagraphs(in)) {
+                       LyXLayout const & layout =
+                               textclasslist.Style(params.textclass, par->layout);
+                       
+                       if (layout.intitle) {
+                               if (already_title) {
+                                       lyxerr <<"Error in latexParagraphs: You"
+                                               " should not mix title layouts"
+                                               " with normal ones." << endl;
+                               } else
+                                       was_title = true;
+                       } else if (was_title && !already_title) {
+                               ofs << "\\maketitle\n";
+                               texrow.newline();
+                               already_title = true;
+                               was_title = false;                  
+                       }
+                       
+                       if (layout.isEnvironment()) {
+                               par = par->TeXEnvironment(this, params, ofs, texrow);
+                       } else {
+                               par = par->TeXOnePar(this, params, ofs, texrow, false);
+                       }
                } else {
                        par = par->TeXOnePar(this, params, ofs, texrow, false);
                }
@@ -2522,8 +2612,8 @@ void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
                         string const & latexname) const
 {
        if (!latexname.empty() && latexname != "!-- --")
-               os << "<!-- " << depth << " -->" << "<" << latexname << ">";
-       //os << string(depth, ' ') << "<" << latexname << ">\n";
+               //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
+               os << string(depth, ' ') << "<" << latexname << ">\n";
 }
 
 
@@ -2531,8 +2621,8 @@ void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
                          string const & latexname) const
 {
        if (!latexname.empty() && latexname != "!-- --")
-               os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
-       //os << string(depth, ' ') << "</" << latexname << ">\n";
+               //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
+               os << string(depth, ' ') << "</" << latexname << ">\n";
 }
 
 
@@ -2541,7 +2631,7 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
        ofstream ofs(fname.c_str());
 
        if (!ofs) {
-               WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
+               Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
                return;
        }
 
@@ -2558,14 +2648,16 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
        string top_element = textclasslist.LatexnameOfClass(params.textclass);
 
        if (!body_only) {
-               string sgml_includedfiles=features.getIncludedFiles(fname);
+               ofs << "<!doctype linuxdoc system";
 
-               if (params.preamble.empty() && sgml_includedfiles.empty()) {
-                       ofs << "<!doctype linuxdoc system>\n\n";
-               } else {
-                       ofs << "<!doctype linuxdoc system [ "
-                           << params.preamble << sgml_includedfiles << " \n]>\n\n";
+               string preamble = params.preamble;
+               preamble += features.getIncludedFiles(fname);
+               preamble += features.getLyXSGMLEntities();
+
+               if (!preamble.empty()) {
+                       ofs << " [ " << preamble << " ]";
                }
+               ofs << ">\n\n";
 
                if (params.options.empty())
                        sgmlOpenTag(ofs, 0, top_element);
@@ -2577,7 +2669,7 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
                }
        }
 
-       ofs << "<!-- "  << LYX_DOCVERSION 
+       ofs << "<!-- "  << lyx_docversion
            << " created this file. For more info see http://www.lyx.org/"
            << " -->\n";
 
@@ -2592,7 +2684,7 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
                                            par->layout);
 
                // treat <toc> as a special case for compatibility with old code
-               if (par->getChar(0) == Paragraph::META_INSET) {
+               if (par->isInset(0)) {
                        Inset * inset = par->getInset(0);
                        Inset::Code lyx_code = inset->lyxCode();
                        if (lyx_code == Inset::TOC_CODE){
@@ -2627,9 +2719,9 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
 
                case LATEX_COMMAND:
                        if (depth!= 0)
-                               linuxDocError(par, 0,
-                                             _("Error : Wrong depth for"
-                                               " LatexType Command.\n"));
+                               sgmlError(par, 0,
+                                         _("Error : Wrong depth for"
+                                           " LatexType Command.\n"));
 
                        if (!environment_stack[depth].empty()){
                                sgmlCloseTag(ofs, depth,
@@ -2715,35 +2807,11 @@ void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
 }
 
 
-void Buffer::docbookHandleCaption(ostream & os, string & inner_tag,
-                                 Paragraph::depth_type depth, int desc_on,
-                                 Paragraph * & par)
-{
-       Paragraph * tpar = par;
-       while (tpar
-              && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
-                                                               "Caption").second))
-               tpar = tpar->next();
-
-       if (tpar &&
-           tpar->layout == textclasslist.NumberOfLayout(params.textclass,
-                                                        "Caption").second) {
-               sgmlOpenTag(os, depth + 1, inner_tag);
-               string extra_par;
-               simpleDocBookOnePar(os, extra_par, tpar,
-                                   desc_on, depth + 2);
-               sgmlCloseTag(os, depth+1, inner_tag);
-               if (!extra_par.empty())
-                       os << extra_par;
-       }
-}
-
-
 // checks, if newcol chars should be put into this line
 // writes newline, if necessary.
 namespace {
 
-void linux_doc_line_break(ostream & os, string::size_type & colcount,
+void sgmlLineBreak(ostream & os, string::size_type & colcount,
                          string::size_type newcol)
 {
        colcount += newcol;
@@ -2794,8 +2862,6 @@ void reset(PAR_TAG & p1, PAR_TAG const & p2)
 } // namespace anon
 
 
-
-
 // Handle internal paragraph parsing -- layout already processed.
 void Buffer::simpleLinuxDocOnePar(ostream & os,
                                  Paragraph * par, 
@@ -2803,7 +2869,7 @@ void Buffer::simpleLinuxDocOnePar(ostream & os,
 {
        LyXLayout const & style = textclasslist.Style(params.textclass,
                                                      par->getLayout());
-        string::size_type char_line_count = 5;     // Heuristic choice ;-) 
+       string::size_type char_line_count = 5;     // Heuristic choice ;-) 
 
        // gets paragraph main font
        LyXFont font_old;
@@ -2823,7 +2889,7 @@ void Buffer::simpleLinuxDocOnePar(ostream & os,
 
        stack<PAR_TAG> tag_state;
        // parsing main loop
-       for (Paragraph::size_type i = 0; i < par->size(); ++i) {
+       for (pos_type i = 0; i < par->size(); ++i) {
 
                PAR_TAG tag_close = NONE;
                list < PAR_TAG > tag_open;
@@ -2915,7 +2981,7 @@ void Buffer::simpleLinuxDocOnePar(ostream & os,
                }
 
                list < PAR_TAG > temp;
-               while(!tag_state.empty() && tag_close ) {
+               while (!tag_state.empty() && tag_close ) {
                        PAR_TAG k =  tag_state.top();
                        tag_state.pop();
                        os << "</" << tag_name(k) << ">";
@@ -2953,18 +3019,19 @@ void Buffer::simpleLinuxDocOnePar(ostream & os,
                        ++char_line_count;
                } else {
                        string sgml_string;
-                       if (par->linuxDocConvertChar(c, sgml_string)
-                           && !style.free_spacing) { 
+                       if (par->sgmlConvertChar(c, sgml_string)
+                           && !style.free_spacing && !par->isFreeSpacing())
+                       { 
                                // in freespacing mode, spaces are
                                // non-breaking characters
                                if (desc_on) {// if char is ' ' then...
 
                                        ++char_line_count;
-                                       linux_doc_line_break(os, char_line_count, 6);
+                                       sgmlLineBreak(os, char_line_count, 6);
                                        os << "</tag>";
                                        desc_on = false;
                                } else  {
-                                       linux_doc_line_break(os, char_line_count, 1);
+                                       sgmlLineBreak(os, char_line_count, 1);
                                        os << c;
                                }
                        } else {
@@ -2983,19 +3050,20 @@ void Buffer::simpleLinuxDocOnePar(ostream & os,
        // resets description flag correctly
        if (desc_on) {
                // <tag> not closed...
-               linux_doc_line_break(os, char_line_count, 6);
+               sgmlLineBreak(os, char_line_count, 6);
                os << "</tag>";
        }
 }
 
 
 // Print an error message.
-void Buffer::linuxDocError(Paragraph * par, int pos,
-                          string const & message) 
+void Buffer::sgmlError(Paragraph * par, int pos,
+                      string const & message) const
 {
        // insert an error marker in text
        InsetError * new_inset = new InsetError(message);
-       par->insertInset(pos, new_inset);
+       par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT, 
+                                                params.language));
 }
 
 
@@ -3003,7 +3071,7 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
 {
        ofstream ofs(fname.c_str());
        if (!ofs) {
-               WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
+               Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
                return;
        }
 
@@ -3022,16 +3090,17 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
        string top_element = textclasslist.LatexnameOfClass(params.textclass);
 
        if (!only_body) {
-               string sgml_includedfiles = features.getIncludedFiles(fname);
+               ofs << "<!DOCTYPE " << top_element
+                   << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
 
-               ofs << "<!doctype " << top_element
-                   << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
+               string preamble = params.preamble;
+               preamble += features.getIncludedFiles(fname);
+               preamble += features.getLyXSGMLEntities();
 
-               if (params.preamble.empty() && sgml_includedfiles.empty())
-                       ofs << ">\n\n";
-               else
-                       ofs << "\n [ " << params.preamble 
-                           << sgml_includedfiles << " \n]>\n\n";
+               if (!preamble.empty()) {
+                       ofs << "\n [ " << preamble << " ]";
+               }
+               ofs << ">\n\n";
        }
 
        string top = top_element;       
@@ -3045,7 +3114,7 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
        }
        sgmlOpenTag(ofs, 0, top);
 
-       ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
+       ofs << "<!-- DocBook file was created by " << lyx_docversion
            << "\n  See http://www.lyx.org/ for more information -->\n";
 
        vector<string> environment_stack(10);
@@ -3116,9 +3185,9 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
 
                case LATEX_COMMAND:
                        if (depth != 0)
-                               linuxDocError(par, 0,
-                                             _("Error : Wrong depth for "
-                                               "LatexType Command.\n"));
+                               sgmlError(par, 0,
+                                         _("Error : Wrong depth for "
+                                           "LatexType Command.\n"));
                        
                        command_name = style.latexname();
                        
@@ -3148,7 +3217,9 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
 
                        // treat label as a special case for
                        // more WYSIWYM handling.
-                       if (par->getChar(0) == Paragraph::META_INSET) {
+                       // This is a hack while paragraphs can't have
+                       // attributes, like id in this case.
+                       if (par->isInset(0)) {
                                Inset * inset = par->getInset(0);
                                Inset::Code lyx_code = inset->lyxCode();
                                if (lyx_code == Inset::LABEL_CODE){
@@ -3233,9 +3304,7 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
                        break;
                }
 
-               string extra_par;
-               simpleDocBookOnePar(ofs, extra_par, par, desc_on,
-                                   depth + 1 + command_depth);
+               simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
                par = par->next();
 
                string end_tag;
@@ -3300,7 +3369,7 @@ void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
 }
 
 
-void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
+void Buffer::simpleDocBookOnePar(ostream & os,
                                 Paragraph * par, int & desc_on,
                                 Paragraph::depth_type depth) const
 {
@@ -3316,8 +3385,7 @@ void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
        //      os << string(depth,' ');
 
        // parsing main loop
-       for (Paragraph::size_type i = 0;
-            i < par->size(); ++i) {
+       for (pos_type i = 0; i < par->size(); ++i) {
                LyXFont font = par->getFont(params, i);
 
                // handle <emphasis> tag
@@ -3331,50 +3399,27 @@ void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
                        }
                }
       
-               char c = par->getChar(i);
 
-               if (c == Paragraph::META_INSET) {
+               if ( par->isInset(i) ) {
                        Inset * inset = par->getInset(i);
-                       ostringstream ost;
-                       inset->docbook(this, ost);
-                       string tmp_out = ost.str().c_str();
-
-                       //
-                       // This code needs some explanation:
-                       // Two insets are treated specially
-                       //   label if it is the first element in a command paragraph
-                       //         desc_on == 3
-                       //   graphics inside tables or figure floats can't go on
-                       //   title (the equivalente in latex for this case is caption
-                       //   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)
-                                               extra += frontStrip(tmp_out, '@');
-                                       else
-                                               os << frontStrip(tmp_out, '@');
-                               }
-                               else
-                                       os << tmp_out;
-                       }
+                       // don't print the inset in position 0 if desc_on == 3 (label)
+                       if ( i || desc_on != 3)
+                               inset->docbook(this, os);
                } else {
+                       char c = par->getChar(i);
                        string sgml_string;
-                       if (par->linuxDocConvertChar(c, sgml_string)
-                           && !style.free_spacing) { // in freespacing
-                                                    // mode, spaces are
-                                                    // non-breaking characters
-                               // char is ' '
-                               if (desc_on == 1) {
-                                       ++char_line_count;
-                                       os << "\n</term><listitem><para>";
-                                       desc_on = 2;
-                               } else {
-                                       os << c;
-                               }
+                       par->sgmlConvertChar(c, sgml_string);
+
+                       if (style.pass_thru) {
+                               os << c;
+                       } else if(style.free_spacing || par->isFreeSpacing() || c != ' ') {
+                                       os << sgml_string;
+                       } else if (desc_on ==1) {
+                               ++char_line_count;
+                               os << "\n</term><listitem><para>";
+                               desc_on = 2;
                        } else {
-                               os << sgml_string;
+                               os << ' ';
                        }
                }
                font_old = font;
@@ -3404,7 +3449,7 @@ int Buffer::runChktex()
 
        // get LaTeX-Filename
        string const name = getLatexName();
-       string path = OnlyPath(filename);
+       string path = filePath();
 
        string const org_path = path;
        if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
@@ -3421,11 +3466,11 @@ int Buffer::runChktex()
        makeLaTeXFile(name, org_path, false);
 
        TeXErrors terr;
-       Chktex chktex(lyxrc.chktex_command, name, filepath);
+       Chktex chktex(lyxrc.chktex_command, name, filePath());
        int res = chktex.run(terr); // run chktex
 
        if (res == -1) {
-               WriteAlert(_("chktex did not work!"),
+               Alert::alert(_("chktex did not work!"),
                           _("Could not run with file:"), name);
        } else if (res > 0) {
                // Insert all errors as errors boxes
@@ -3451,8 +3496,8 @@ void Buffer::validate(LaTeXFeatures & features) const
                textclasslist.TextClass(params.textclass);
     
         // AMS Style is at document level
-        features.amsstyle = (params.use_amsmath ||
-                            tclass.provides(LyXTextClass::amsmath));
+        if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
+               features.require("amsmath");
     
        while (par) {
                // We don't use "lyxerr.debug" because of speed. (Asger)
@@ -3481,12 +3526,12 @@ void Buffer::validate(LaTeXFeatures & features) const
                                   || c == 25
                                   || c == 26
                                   || c == 31) {
-                                       features.latexsym = true;
+                                       features.require("latexsym");
                                }
                        } else if (font == 1) {
-                               features.amssymb = true;
+                               features.require("amssymb");
                        } else if ((font >= 2 && font <= 5)) {
-                               features.pifont = true;
+                               features.require("pifont");
                        }
                }
        }
@@ -3497,33 +3542,6 @@ void Buffer::validate(LaTeXFeatures & features) const
 }
 
 
-void Buffer::setPaperStuff()
-{
-       params.papersize = BufferParams::PAPER_DEFAULT;
-       char const c1 = params.paperpackage;
-       if (c1 == BufferParams::PACKAGE_NONE) {
-               char const c2 = params.papersize2;
-               if (c2 == BufferParams::VM_PAPER_USLETTER)
-                       params.papersize = BufferParams::PAPER_USLETTER;
-               else if (c2 == BufferParams::VM_PAPER_USLEGAL)
-                       params.papersize = BufferParams::PAPER_LEGALPAPER;
-               else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
-                       params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
-               else if (c2 == BufferParams::VM_PAPER_A3)
-                       params.papersize = BufferParams::PAPER_A3PAPER;
-               else if (c2 == BufferParams::VM_PAPER_A4)
-                       params.papersize = BufferParams::PAPER_A4PAPER;
-               else if (c2 == BufferParams::VM_PAPER_A5)
-                       params.papersize = BufferParams::PAPER_A5PAPER;
-               else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
-                        (c2 == BufferParams::VM_PAPER_B5))
-                       params.papersize = BufferParams::PAPER_B5PAPER;
-       } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
-                  (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
-               params.papersize = BufferParams::PAPER_A4PAPER;
-}
-
-
 // This function should be in Buffer because it's a buffer's property (ale)
 string const Buffer::getIncludeonlyList(char delim)
 {
@@ -3572,16 +3590,16 @@ Buffer::Lists const Buffer::getLists() const
        Paragraph * par = paragraph;
 
 #if 1
-       std::pair<bool, LyXTextClassList::size_type> const tmp =
+       std::pair<bool, textclass_type> const tmp =
                textclasslist.NumberOfLayout(params.textclass, "Caption");
        bool const found = tmp.first;
-       LyXTextClassList::size_type const cap = tmp.second;
+       textclass_type const cap = tmp.second;
        
 #else
        // This is the prefered way to to this, but boost::tie can break
        // some compilers
        bool found;
-       LyXTextClassList::size_type cap;
+       textclass_type cap;
        boost::tie(found, cap) = textclasslist
                .NumberOfLayout(params.textclass, "Caption");
 #endif
@@ -3778,8 +3796,7 @@ bool Buffer::isMultiLingual()
 }
 
 
-Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
-                                      Paragraph::size_type pos)
+Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
        : par(paragraph)
 {
        it = par->InsetIterator(pos);