]> git.lyx.org Git - lyx.git/blob - src/buffer.C
prepare infrastructure for multicell selection
[lyx.git] / src / buffer.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  *           This file is Copyright 1996-2001
10  *           Lars Gullik Bjønnes
11  *
12  * ====================================================== 
13  */
14
15 #include <config.h>
16
17 #include <fstream>
18 #include <iomanip>
19 #include <map>
20 #include <stack>
21 #include <list>
22
23 #include <cstdlib>
24 #include <cmath>
25 #include <unistd.h>
26 #include <sys/types.h>
27 #include <utime.h>
28
29 #include <algorithm>
30
31 #ifdef HAVE_LOCALE
32 #include <locale>
33 #endif
34
35 #ifdef __GNUG__
36 #pragma implementation
37 #endif
38
39 #include "buffer.h"
40 #include "bufferlist.h"
41 #include "lyx_main.h"
42 #include "lyx_gui_misc.h"
43 #include "LyXAction.h"
44 #include "lyxrc.h"
45 #include "lyxlex.h"
46 #include "tex-strings.h"
47 #include "layout.h"
48 #include "bufferview_funcs.h"
49 #include "lyxfont.h"
50 #include "version.h"
51 #include "mathed/formulamacro.h"
52 #include "mathed/formula.h"
53 #include "insets/inset.h"
54 #include "insets/inseterror.h"
55 #include "insets/insetlabel.h"
56 #include "insets/insetref.h"
57 #include "insets/inseturl.h"
58 #include "insets/insetinfo.h"
59 #include "insets/insetquotes.h"
60 #include "insets/insetlatexaccent.h"
61 #include "insets/insetbib.h" 
62 #include "insets/insetcite.h" 
63 #include "insets/insetexternal.h"
64 #include "insets/insetindex.h" 
65 #include "insets/insetinclude.h"
66 #include "insets/insettoc.h"
67 #include "insets/insetparent.h"
68 #include "insets/insetspecialchar.h"
69 #include "insets/figinset.h"
70 #include "insets/insettext.h"
71 #include "insets/insetert.h"
72 #include "insets/insetgraphics.h"
73 #include "insets/insetfoot.h"
74 #include "insets/insetmarginal.h"
75 #include "insets/insetminipage.h"
76 #include "insets/insetfloat.h"
77 #include "insets/insetlist.h"
78 #include "insets/insettabular.h"
79 #include "insets/insettheorem.h"
80 #include "insets/insetcaption.h"
81 #include "insets/insetfloatlist.h"
82 #include "support/filetools.h"
83 #include "support/path.h"
84 #include "support/os.h"
85 #include "LaTeX.h"
86 #include "Chktex.h"
87 #include "LyXView.h"
88 #include "debug.h"
89 #include "LaTeXFeatures.h"
90 #include "support/syscall.h"
91 #include "support/lyxlib.h"
92 #include "support/FileInfo.h"
93 #include "support/lyxmanip.h"
94 #include "lyxtext.h"
95 #include "gettext.h"
96 #include "language.h"
97 #include "lyx_gui_misc.h"       // WarnReadonly()
98 #include "frontends/Dialogs.h"
99 #include "encoding.h"
100 #include "exporter.h"
101 #include "Lsstream.h"
102 #include "converter.h"
103 #include "BufferView.h"
104 #include "ParagraphParameters.h"
105
106 using std::ostream;
107 using std::ofstream;
108 using std::ifstream;
109 using std::fstream;
110 using std::ios;
111 using std::setw;
112 using std::endl;
113 using std::pair;
114 using std::make_pair;
115 using std::vector;
116 using std::map;
117 using std::max;
118 using std::set;
119 using std::stack;
120 using std::list;
121
122 // all these externs should eventually be removed.
123 extern BufferList bufferlist;
124
125 extern LyXAction lyxaction;
126
127 namespace {
128
129 const int LYX_FORMAT = 220;
130
131 } // namespace anon
132
133 extern int tex_code_break_column;
134
135
136 Buffer::Buffer(string const & file, bool ronly)
137 {
138         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
139         filename = file;
140         filepath = OnlyPath(file);
141         paragraph = 0;
142         lyx_clean = true;
143         bak_clean = true;
144         dep_clean = 0;
145         read_only = ronly;
146         unnamed = false;
147         users = 0;
148         lyxvc.buffer(this);
149         if (read_only || (lyxrc.use_tempdir)) {
150                 tmppath = CreateBufferTmpDir();
151         } else tmppath.erase();
152 }
153
154
155 Buffer::~Buffer()
156 {
157         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
158         // here the buffer should take care that it is
159         // saved properly, before it goes into the void.
160
161         // make sure that views using this buffer
162         // forgets it.
163         if (users)
164                 users->buffer(0);
165         
166         if (!tmppath.empty()) {
167                 DestroyBufferTmpDir(tmppath);
168         }
169         
170         Paragraph * par = paragraph;
171         Paragraph * tmppar;
172         while (par) {
173                 tmppar = par->next();
174                 delete par;
175                 par = tmppar;
176         }
177         paragraph = 0;
178 }
179
180
181 string const Buffer::getLatexName(bool no_path) const
182 {
183         string name = ChangeExtension(MakeLatexName(filename), ".tex");
184         if (no_path)
185                 return OnlyFilename(name);
186         else
187                 return name;
188 }
189
190
191 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
192 {
193         string const filename = getLatexName(false);
194
195         if (filename.empty())
196                 return make_pair(Buffer::latexlog, string());
197
198         string path = OnlyPath(filename);
199
200         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1))
201                 path = tmppath;
202
203         string const fname = AddName(path,
204                                      OnlyFilename(ChangeExtension(filename,
205                                                                   ".log")));
206         string const bname =
207                 AddName(path, OnlyFilename(
208                         ChangeExtension(filename,
209                                         formats.Extension("literate") + ".out")));
210
211         // If no Latex log or Build log is newer, show Build log
212
213         FileInfo const f_fi(fname);
214         FileInfo const b_fi(bname);
215
216         if (b_fi.exist() &&
217             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
218                 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
219                 return make_pair(Buffer::buildlog, bname);
220         }
221         lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
222         return make_pair(Buffer::latexlog, fname);
223 }
224
225
226 void Buffer::setReadonly(bool flag)
227 {
228         if (read_only != flag) {
229                 read_only = flag; 
230                 updateTitles();
231                 users->owner()->getDialogs()->updateBufferDependent(false);
232         }
233         if (read_only) {
234                 WarnReadonly(filename);
235         }
236 }
237
238
239 bool Buffer::saveParamsAsDefaults() // const
240 {
241         string const fname = AddName(AddPath(user_lyxdir, "templates/"),
242                                "defaults.lyx");
243         Buffer defaults = Buffer(fname);
244         
245         // Use the current buffer's parameters as default
246         defaults.params = params;
247         
248         // add an empty paragraph. Is this enough?
249         defaults.paragraph = new Paragraph;
250
251         return defaults.writeFile(defaults.filename, false);
252 }
253
254
255 /// Update window titles of all users
256 // Should work on a list
257 void Buffer::updateTitles() const
258 {
259         if (users) users->owner()->updateWindowTitle();
260 }
261
262
263 /// Reset autosave timer of all users
264 // Should work on a list
265 void Buffer::resetAutosaveTimers() const
266 {
267         if (users) users->owner()->resetAutosaveTimer();
268 }
269
270
271 void Buffer::setFileName(string const & newfile)
272 {
273         filename = MakeAbsPath(newfile);
274         filepath = OnlyPath(filename);
275         setReadonly(IsFileWriteable(filename) == 0);
276         updateTitles();
277 }
278
279
280 // We'll remove this later. (Lgb)
281 namespace {
282
283 string last_inset_read;
284
285 struct ErtComp 
286 {
287         ErtComp() : active(false), in_tabular(false) {
288         }
289         string contents;
290         bool active;
291         bool in_tabular;
292 };
293
294 std::stack<ErtComp> ert_stack;
295 ErtComp ert_comp;
296
297
298 } // anon
299
300
301
302 // candidate for move to BufferView
303 // (at least some parts in the beginning of the func)
304 //
305 // Uwe C. Schroeder
306 // changed to be public and have one parameter
307 // if par = 0 normal behavior
308 // else insert behavior
309 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
310 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
311 {
312 #ifdef NO_LATEX
313         ert_comp.contents.erase();
314         ert_comp.active = false;
315         ert_comp.in_tabular = false;
316 #endif
317         
318         int pos = 0;
319         Paragraph::depth_type depth = 0; 
320         bool the_end_read = false;
321
322         Paragraph * first_par = 0;
323         LyXFont font(LyXFont::ALL_INHERIT, params.language);
324         if (file_format < 216 && params.language->lang() == "hebrew")
325                 font.setLanguage(default_language);
326
327         if (!par) {
328                 par = new Paragraph;
329         } else {
330                 // We are inserting into an existing document
331                 users->text->breakParagraph(users);
332                 first_par = users->text->firstParagraph();
333                 pos = 0;
334                 markDirty();
335                 // We don't want to adopt the parameters from the
336                 // document we insert, so we skip until the text begins:
337                 while (lex.IsOK()) {
338                         lex.nextToken();
339                         string const pretoken = lex.GetString();
340                         if (pretoken == "\\layout") {
341                                 lex.pushToken(pretoken);
342                                 break;
343                         }
344                 }
345         }
346
347         while (lex.IsOK()) {
348                 lex.nextToken();
349                 string const token = lex.GetString();
350
351                 if (token.empty()) continue;
352
353                 lyxerr[Debug::PARSER] << "Handling token: `"
354                                       << token << "'" << endl;
355                 
356                 the_end_read =
357                         parseSingleLyXformat2Token(lex, par, first_par,
358                                                    token, pos, depth,
359                                                    font);
360         }
361    
362         if (!first_par)
363                 first_par = par;
364
365         paragraph = first_par;
366         
367         return the_end_read;
368 }
369
370
371 void Buffer::insertErtContents(Paragraph * par, int & pos,
372                                LyXFont const & font, bool set_inactive) 
373 {
374         if (!ert_comp.contents.empty()) {
375                 lyxerr[Debug::INSETS] << "ERT contents:\n"
376                        << ert_comp.contents << endl;
377                 Inset * inset = new InsetERT(ert_comp.contents);
378                 par->insertInset(pos++, inset, font);
379                 ert_comp.contents.erase();
380         }
381         if (set_inactive) {
382                 ert_comp.active = false;
383         }
384 }
385
386
387 bool
388 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
389                                    Paragraph *& first_par,
390                                    string const & token, int & pos,
391                                    Paragraph::depth_type & depth, 
392                                    LyXFont & font
393         )
394 {
395         bool the_end_read = false;
396 #ifndef NO_PEXTRA_REALLY
397         // This is super temporary but is needed to get the compability
398         // mode for minipages work correctly together with new tabulars.
399         static int call_depth;
400         ++call_depth;
401         bool checkminipage = false;
402         static Paragraph * minipar;
403         static Paragraph * parBeforeMinipage;
404 #endif
405         
406         if (token[0] != '\\') {
407 #ifdef NO_LATEX
408                 if (ert_comp.active) {
409                         ert_comp.contents += token;
410                 } else {
411 #endif
412                 for (string::const_iterator cit = token.begin();
413                      cit != token.end(); ++cit) {
414                         par->insertChar(pos, (*cit), font);
415                         ++pos;
416                 }
417                 checkminipage = true;
418 #ifdef NO_LATEX
419                 }
420 #endif
421         } else if (token == "\\i") {
422                 Inset * inset = new InsetLatexAccent;
423                 inset->read(this, lex);
424                 par->insertInset(pos, inset, font);
425                 ++pos;
426         } else if (token == "\\layout") {
427 #ifdef NO_LATEX
428                 ert_comp.in_tabular = false;
429                 // Do the insetert.
430                 insertErtContents(par, pos, font);
431 #endif
432                 lex.EatLine();
433                 string const layoutname = lex.GetString();
434                 pair<bool, LyXTextClass::LayoutList::size_type> pp
435                         = textclasslist.NumberOfLayout(params.textclass,
436                                                        layoutname);
437
438 #ifdef NO_LATEX
439                 if (compare_no_case(layoutname, "latex") == 0) {
440                         ert_comp.active = true;
441                 }
442 #endif
443 #ifdef USE_CAPTION
444                 // The is the compability reading of layout caption.
445                 // It can be removed in LyX version 1.3.0. (Lgb)
446                 if (compare_no_case(layoutname, "caption") == 0) {
447                         // We expect that the par we are now working on is
448                         // really inside a InsetText inside a InsetFloat.
449                         // We also know that captions can only be
450                         // one paragraph. (Lgb)
451                         
452                         // We should now read until the next "\layout"
453                         // is reached.
454                         // This is probably not good enough, what if the
455                         // caption is the last par in the document (Lgb)
456                         istream & ist = lex.getStream();
457                         stringstream ss;
458                         string line;
459                         int begin = 0;
460                         while (true) {
461                                 getline(ist, line);
462                                 if (prefixIs(line, "\\layout")) {
463                                         lex.pushToken(line);
464                                         break;
465                                 }
466                                 if (prefixIs(line, "\\begin_inset"))
467                                         ++begin;
468                                 if (prefixIs(line, "\\end_inset")) {
469                                         if (begin)
470                                                 --begin;
471                                         else {
472                                                 lex.pushToken(line);
473                                                 break;
474                                         }
475                                 }
476                                 
477                                 ss << line << '\n';
478                         }
479                         // Now we should have the whole layout in ss
480                         // we should now be able to give this to the
481                         // caption inset.
482                         ss << "\\end_inset\n";
483                         
484                         // This seems like a bug in stringstream.
485                         // We really should be able to use ss
486                         // directly. (Lgb)
487                         istringstream is(ss.str());
488                         LyXLex tmplex(0, 0);
489                         tmplex.setStream(is);
490                         Inset * inset = new InsetCaption;
491                         inset->Read(this, tmplex);
492                         par->InsertInset(pos, inset, font);
493                         ++pos;
494                 } else {
495 #endif
496                         if (!first_par)
497                                 first_par = par;
498                         else {
499                                 par = new Paragraph(par);
500                         }
501                         pos = 0;
502                         if (pp.first) {
503                                 par->layout = pp.second;
504                         } else {
505                                 // layout not found
506                                 // use default layout "Standard" (0)
507                                 par->layout = 0;
508                         }
509                         // Test whether the layout is obsolete.
510                         LyXLayout const & layout =
511                                 textclasslist.Style(params.textclass,
512                                                     par->layout);
513                         if (!layout.obsoleted_by().empty())
514                                 par->layout = textclasslist
515                                         .NumberOfLayout(params.textclass,
516                                                         layout.obsoleted_by())
517                                         .second;
518                         par->params().depth(depth);
519                         font = LyXFont(LyXFont::ALL_INHERIT, params.language);
520                         if (file_format < 216
521                             && params.language->lang() == "hebrew")
522                                 font.setLanguage(default_language);
523 #if USE_CAPTION
524                 }
525 #endif
526
527         } else if (token == "\\begin_float") {
528                 // This is the compability reader. It can be removed in
529                 // LyX version 1.3.0. (Lgb)
530                 lex.next();
531                 string const tmptok = lex.GetString();
532                 //lyxerr << "old float: " << tmptok << endl;
533                 
534                 Inset * inset = 0;
535                 stringstream old_float;
536                 
537                 if (tmptok == "footnote") {
538                         inset = new InsetFoot;
539                 } else if (tmptok == "margin") {
540                         inset = new InsetMarginal;
541                 } else if (tmptok == "fig") {
542                         inset = new InsetFloat("figure");
543                         old_float << "placement htbp\n"
544                                   << "wide false\n";
545                 } else if (tmptok == "tab") {
546                         inset = new InsetFloat("table");
547                         old_float << "placement htbp\n"
548                                   << "wide false\n";
549                 } else if (tmptok == "alg") {
550                         inset = new InsetFloat("algorithm");
551                         old_float << "placement htbp\n"
552                                   << "wide false\n";
553                 } else if (tmptok == "wide-fig") {
554                         inset = new InsetFloat("figure");
555                         //InsetFloat * tmp = new InsetFloat("figure");
556                         //tmp->wide(true);
557                         //inset = tmp;
558                         old_float << "placement htbp\n"
559                                   << "wide true\n";
560                 } else if (tmptok == "wide-tab") {
561                         inset = new InsetFloat("table");
562                         //InsetFloat * tmp = new InsetFloat("table");
563                         //tmp->wide(true);
564                         //inset = tmp;
565                         old_float << "placement htbp\n"
566                                   << "wide true\n";
567                 }
568
569                 if (!inset) {
570                         --call_depth;
571                         return false; // no end read yet
572                 }
573                 
574                 old_float << "collapsed true\n";
575
576                 // Here we need to check for \end_deeper and handle that
577                 // before we do the footnote parsing.
578                 // This _is_ a hack! (Lgb)
579                 while (true) {
580                         lex.next();
581                         string const tmp = lex.GetString();
582                         if (tmp == "\\end_deeper") {
583                                 //lyxerr << "\\end_deeper caught!" << endl;
584                                 if (!depth) {
585                                         lex.printError("\\end_deeper: "
586                                                        "depth is already null");
587                                 } else
588                                         --depth;
589                                 
590                         } else {
591                                 old_float << tmp << ' ';
592                                 break;
593                         }
594                 }
595                 
596                 old_float << lex.getLongString("\\end_float")
597                           << "\n\\end_inset\n";
598                 //lyxerr << "Float Body:\n" << old_float.str() << endl;
599                 // That this does not work seems like a bug
600                 // in stringstream. (Lgb)
601                 istringstream istr(old_float.str());
602                 LyXLex nylex(0, 0);
603                 nylex.setStream(istr);
604                 inset->read(this, nylex);
605                 par->insertInset(pos, inset, font);
606                 ++pos;
607         } else if (token == "\\begin_deeper") {
608                 ++depth;
609         } else if (token == "\\end_deeper") {
610                 if (!depth) {
611                         lex.printError("\\end_deeper: "
612                                        "depth is already null");
613                 }
614                 else
615                         --depth;
616         } else if (token == "\\begin_preamble") {
617                 params.readPreamble(lex);
618         } else if (token == "\\textclass") {
619                 lex.EatLine();
620                 pair<bool, LyXTextClassList::size_type> pp = 
621                         textclasslist.NumberOfClass(lex.GetString());
622                 if (pp.first) {
623                         params.textclass = pp.second;
624                 } else {
625                         WriteAlert(string(_("Textclass error")), 
626                                 string(_("The document uses an unknown textclass \"")) + 
627                                 lex.GetString() + string("\"."),
628                                 string(_("LyX will not be able to produce output correctly.")));
629                         params.textclass = 0;
630                 }
631                 if (!textclasslist.Load(params.textclass)) {
632                                 // if the textclass wasn't loaded properly
633                                 // we need to either substitute another
634                                 // or stop loading the file.
635                                 // I can substitute but I don't see how I can
636                                 // stop loading... ideas??  ARRae980418
637                         WriteAlert(_("Textclass Loading Error!"),
638                                    string(_("Can't load textclass ")) +
639                                    textclasslist.NameOfClass(params.textclass),
640                                    _("-- substituting default"));
641                         params.textclass = 0;
642                 }
643         } else if (token == "\\options") {
644                 lex.EatLine();
645                 params.options = lex.GetString();
646         } else if (token == "\\language") {
647                 params.readLanguage(lex);    
648         } else if (token == "\\fontencoding") {
649                 lex.EatLine();
650         } else if (token == "\\inputencoding") {
651                 lex.EatLine();
652                 params.inputenc = lex.GetString();
653         } else if (token == "\\graphics") {
654                 params.readGraphicsDriver(lex);
655         } else if (token == "\\fontscheme") {
656                 lex.EatLine();
657                 params.fonts = lex.GetString();
658         } else if (token == "\\noindent") {
659                 par->params().noindent(true);
660         } else if (token == "\\fill_top") {
661                 par->params().spaceTop(VSpace(VSpace::VFILL));
662         } else if (token == "\\fill_bottom") {
663                 par->params().spaceBottom(VSpace(VSpace::VFILL));
664         } else if (token == "\\line_top") {
665                 par->params().lineTop(true);
666         } else if (token == "\\line_bottom") {
667                 par->params().lineBottom(true);
668         } else if (token == "\\pagebreak_top") {
669                 par->params().pagebreakTop(true);
670         } else if (token == "\\pagebreak_bottom") {
671                 par->params().pagebreakBottom(true);
672         } else if (token == "\\start_of_appendix") {
673                 par->params().startOfAppendix(true);
674         } else if (token == "\\paragraph_separation") {
675                 int tmpret = lex.FindToken(string_paragraph_separation);
676                 if (tmpret == -1) ++tmpret;
677                 if (tmpret != LYX_LAYOUT_DEFAULT) 
678                         params.paragraph_separation =
679                                 static_cast<BufferParams::PARSEP>(tmpret);
680         } else if (token == "\\defskip") {
681                 lex.nextToken();
682                 params.defskip = VSpace(lex.GetString());
683         } else if (token == "\\epsfig") { // obsolete
684                 // Indeed it is obsolete, but we HAVE to be backwards
685                 // compatible until 0.14, because otherwise all figures
686                 // in existing documents are irretrivably lost. (Asger)
687                 params.readGraphicsDriver(lex);
688         } else if (token == "\\quotes_language") {
689                 int tmpret = lex.FindToken(string_quotes_language);
690                 if (tmpret == -1) ++tmpret;
691                 if (tmpret != LYX_LAYOUT_DEFAULT) {
692                         InsetQuotes::quote_language tmpl = 
693                                 InsetQuotes::EnglishQ;
694                         switch (tmpret) {
695                         case 0:
696                                 tmpl = InsetQuotes::EnglishQ;
697                                 break;
698                         case 1:
699                                 tmpl = InsetQuotes::SwedishQ;
700                                 break;
701                         case 2:
702                                 tmpl = InsetQuotes::GermanQ;
703                                 break;
704                         case 3:
705                                 tmpl = InsetQuotes::PolishQ;
706                                 break;
707                         case 4:
708                                 tmpl = InsetQuotes::FrenchQ;
709                                 break;
710                         case 5:
711                                 tmpl = InsetQuotes::DanishQ;
712                                 break;  
713                         }
714                         params.quotes_language = tmpl;
715                 }
716         } else if (token == "\\quotes_times") {
717                 lex.nextToken();
718                 switch (lex.GetInteger()) {
719                 case 1: 
720                         params.quotes_times = InsetQuotes::SingleQ; 
721                         break;
722                 case 2: 
723                         params.quotes_times = InsetQuotes::DoubleQ; 
724                         break;
725                 }
726         } else if (token == "\\papersize") {
727                 int tmpret = lex.FindToken(string_papersize);
728                 if (tmpret == -1)
729                         ++tmpret;
730                 else
731                         params.papersize2 = tmpret;
732         } else if (token == "\\paperpackage") {
733                 int tmpret = lex.FindToken(string_paperpackages);
734                 if (tmpret == -1) {
735                         ++tmpret;
736                         params.paperpackage = BufferParams::PACKAGE_NONE;
737                 } else
738                         params.paperpackage = tmpret;
739         } else if (token == "\\use_geometry") {
740                 lex.nextToken();
741                 params.use_geometry = lex.GetInteger();
742         } else if (token == "\\use_amsmath") {
743                 lex.nextToken();
744                 params.use_amsmath = lex.GetInteger();
745         } else if (token == "\\paperorientation") {
746                 int tmpret = lex.FindToken(string_orientation);
747                 if (tmpret == -1) ++tmpret;
748                 if (tmpret != LYX_LAYOUT_DEFAULT) 
749                         params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
750         } else if (token == "\\paperwidth") {
751                 lex.next();
752                 params.paperwidth = lex.GetString();
753         } else if (token == "\\paperheight") {
754                 lex.next();
755                 params.paperheight = lex.GetString();
756         } else if (token == "\\leftmargin") {
757                 lex.next();
758                 params.leftmargin = lex.GetString();
759         } else if (token == "\\topmargin") {
760                 lex.next();
761                 params.topmargin = lex.GetString();
762         } else if (token == "\\rightmargin") {
763                 lex.next();
764                 params.rightmargin = lex.GetString();
765         } else if (token == "\\bottommargin") {
766                 lex.next();
767                 params.bottommargin = lex.GetString();
768         } else if (token == "\\headheight") {
769                 lex.next();
770                 params.headheight = lex.GetString();
771         } else if (token == "\\headsep") {
772                 lex.next();
773                 params.headsep = lex.GetString();
774         } else if (token == "\\footskip") {
775                 lex.next();
776                 params.footskip = lex.GetString();
777         } else if (token == "\\paperfontsize") {
778                 lex.nextToken();
779                 params.fontsize = strip(lex.GetString());
780         } else if (token == "\\papercolumns") {
781                 lex.nextToken();
782                 params.columns = lex.GetInteger();
783         } else if (token == "\\papersides") {
784                 lex.nextToken();
785                 switch (lex.GetInteger()) {
786                 default:
787                 case 1: params.sides = LyXTextClass::OneSide; break;
788                 case 2: params.sides = LyXTextClass::TwoSides; break;
789                 }
790         } else if (token == "\\paperpagestyle") {
791                 lex.nextToken();
792                 params.pagestyle = strip(lex.GetString());
793         } else if (token == "\\bullet") {
794                 lex.nextToken();
795                 int const index = lex.GetInteger();
796                 lex.nextToken();
797                 int temp_int = lex.GetInteger();
798                 params.user_defined_bullets[index].setFont(temp_int);
799                 params.temp_bullets[index].setFont(temp_int);
800                 lex.nextToken();
801                 temp_int = lex.GetInteger();
802                 params.user_defined_bullets[index].setCharacter(temp_int);
803                 params.temp_bullets[index].setCharacter(temp_int);
804                 lex.nextToken();
805                 temp_int = lex.GetInteger();
806                 params.user_defined_bullets[index].setSize(temp_int);
807                 params.temp_bullets[index].setSize(temp_int);
808                 lex.nextToken();
809                 string const temp_str = lex.GetString();
810                 if (temp_str != "\\end_bullet") {
811                                 // this element isn't really necessary for
812                                 // parsing but is easier for humans
813                                 // to understand bullets. Put it back and
814                                 // set a debug message?
815                         lex.printError("\\end_bullet expected, got" + temp_str);
816                                 //how can I put it back?
817                 }
818         } else if (token == "\\bulletLaTeX") {
819                 lex.nextToken();
820                 int const index = lex.GetInteger();
821                 lex.next();
822                 string temp_str = lex.GetString();
823                 string sum_str;
824                 while (temp_str != "\\end_bullet") {
825                                 // this loop structure is needed when user
826                                 // enters an empty string since the first
827                                 // thing returned will be the \\end_bullet
828                                 // OR
829                                 // if the LaTeX entry has spaces. Each element
830                                 // therefore needs to be read in turn
831                         sum_str += temp_str;
832                         lex.next();
833                         temp_str = lex.GetString();
834                 }
835                 params.user_defined_bullets[index].setText(sum_str);
836                 params.temp_bullets[index].setText(sum_str);
837         } else if (token == "\\secnumdepth") {
838                 lex.nextToken();
839                 params.secnumdepth = lex.GetInteger();
840         } else if (token == "\\tocdepth") {
841                 lex.nextToken();
842                 params.tocdepth = lex.GetInteger();
843         } else if (token == "\\spacing") {
844                 lex.next();
845                 string const tmp = strip(lex.GetString());
846                 Spacing::Space tmp_space = Spacing::Default;
847                 float tmp_val = 0.0;
848                 if (tmp == "single") {
849                         tmp_space = Spacing::Single;
850                 } else if (tmp == "onehalf") {
851                         tmp_space = Spacing::Onehalf;
852                 } else if (tmp == "double") {
853                         tmp_space = Spacing::Double;
854                 } else if (tmp == "other") {
855                         lex.next();
856                         tmp_space = Spacing::Other;
857                         tmp_val = lex.GetFloat();
858                 } else {
859                         lex.printError("Unknown spacing token: '$$Token'");
860                 }
861                 // Small hack so that files written with klyx will be
862                 // parsed correctly.
863                 if (first_par) {
864                         par->params().spacing(Spacing(tmp_space, tmp_val));
865                 } else {
866                         params.spacing.set(tmp_space, tmp_val);
867                 }
868         } else if (token == "\\paragraph_spacing") {
869                 lex.next();
870                 string const tmp = strip(lex.GetString());
871                 if (tmp == "single") {
872                         par->params().spacing(Spacing(Spacing::Single));
873                 } else if (tmp == "onehalf") {
874                         par->params().spacing(Spacing(Spacing::Onehalf));
875                 } else if (tmp == "double") {
876                         par->params().spacing(Spacing(Spacing::Double));
877                 } else if (tmp == "other") {
878                         lex.next();
879                         par->params().spacing(Spacing(Spacing::Other,
880                                          lex.GetFloat()));
881                 } else {
882                         lex.printError("Unknown spacing token: '$$Token'");
883                 }
884         } else if (token == "\\float_placement") {
885                 lex.nextToken();
886                 params.float_placement = lex.GetString();
887         } else if (token == "\\family") { 
888                 lex.next();
889                 font.setLyXFamily(lex.GetString());
890         } else if (token == "\\series") {
891                 lex.next();
892                 font.setLyXSeries(lex.GetString());
893         } else if (token == "\\shape") {
894                 lex.next();
895                 font.setLyXShape(lex.GetString());
896         } else if (token == "\\size") {
897                 lex.next();
898                 font.setLyXSize(lex.GetString());
899 #ifndef NO_LATEX
900 #ifdef WITH_WARNINGS
901 #warning compatability hack needed
902 #endif
903         } else if (token == "\\latex") {
904                 lex.next();
905                 string const tok = lex.GetString();
906                 // This is dirty, but gone with LyX3. (Asger)
907                 if (tok == "no_latex")
908                         font.setLatex(LyXFont::OFF);
909                 else if (tok == "latex")
910                         font.setLatex(LyXFont::ON);
911                 else if (tok == "default")
912                         font.setLatex(LyXFont::INHERIT);
913                 else
914                         lex.printError("Unknown LaTeX font flag "
915                                        "`$$Token'");
916 #else
917         } else if (token == "\\latex") {
918                 lex.next();
919                 string const tok = lex.GetString();
920                 if (tok == "no_latex") {
921                         // Do the insetert.
922                         insertErtContents(par, pos, font);
923                 } else if (tok == "latex") {
924                         ert_comp.active = true;
925                 } else if (tok == "default") {
926                         // Do the insetert.
927                         insertErtContents(par, pos, font);
928                 } else {
929                         lex.printError("Unknown LaTeX font flag "
930                                        "`$$Token'");
931                 }
932 #endif
933         } else if (token == "\\lang") {
934                 lex.next();
935                 string const tok = lex.GetString();
936                 Language const * lang = languages.getLanguage(tok);
937                 if (lang) {
938                         font.setLanguage(lang);
939                 } else {
940                         font.setLanguage(params.language);
941                         lex.printError("Unknown language `$$Token'");
942                 }
943         } else if (token == "\\numeric") {
944                 lex.next();
945                 font.setNumber(font.setLyXMisc(lex.GetString()));
946         } else if (token == "\\emph") {
947                 lex.next();
948                 font.setEmph(font.setLyXMisc(lex.GetString()));
949         } else if (token == "\\bar") {
950                 lex.next();
951                 string const tok = lex.GetString();
952                 // This is dirty, but gone with LyX3. (Asger)
953                 if (tok == "under")
954                         font.setUnderbar(LyXFont::ON);
955                 else if (tok == "no")
956                         font.setUnderbar(LyXFont::OFF);
957                 else if (tok == "default")
958                         font.setUnderbar(LyXFont::INHERIT);
959                 else
960                         lex.printError("Unknown bar font flag "
961                                        "`$$Token'");
962         } else if (token == "\\noun") {
963                 lex.next();
964                 font.setNoun(font.setLyXMisc(lex.GetString()));
965         } else if (token == "\\color") {
966                 lex.next();
967                 font.setLyXColor(lex.GetString());
968         } else if (token == "\\align") {
969                 int tmpret = lex.FindToken(string_align);
970                 if (tmpret == -1) ++tmpret;
971                 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
972                         int const tmpret2 = int(pow(2.0, tmpret));
973                         //lyxerr << "Tmpret2 = " << tmpret2 << endl;
974                         par->params().align(LyXAlignment(tmpret2));
975                 }
976         } else if (token == "\\added_space_top") {
977                 lex.nextToken();
978                 par->params().spaceTop(VSpace(lex.GetString()));
979         } else if (token == "\\added_space_bottom") {
980                 lex.nextToken();
981                 par->params().spaceBottom(VSpace(lex.GetString()));
982 #ifndef NO_PEXTRA_REALLY
983         } else if (token == "\\pextra_type") {
984                 lex.nextToken();
985                 par->params().pextraType(lex.GetInteger());
986         } else if (token == "\\pextra_width") {
987                 lex.nextToken();
988                 par->params().pextraWidth(lex.GetString());
989         } else if (token == "\\pextra_widthp") {
990                 lex.nextToken();
991                 par->params().pextraWidthp(lex.GetString());
992         } else if (token == "\\pextra_alignment") {
993                 lex.nextToken();
994                 par->params().pextraAlignment(lex.GetInteger());
995         } else if (token == "\\pextra_hfill") {
996                 lex.nextToken();
997                 par->params().pextraHfill(lex.GetInteger());
998         } else if (token == "\\pextra_start_minipage") {
999                 lex.nextToken();
1000                 par->params().pextraStartMinipage(lex.GetInteger());
1001 #endif
1002         } else if (token == "\\labelwidthstring") {
1003                 lex.EatLine();
1004                 par->params().labelWidthString(lex.GetString());
1005                 // do not delete this token, it is still needed!
1006         } else if (token == "\\end_inset") {
1007                 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1008                        << "Last inset read was: " << last_inset_read
1009                        << endl;
1010                 // Simply ignore this. The insets do not have
1011                 // to read this.
1012                 // But insets should read it, it is a part of
1013                 // the inset isn't it? Lgb.
1014         } else if (token == "\\begin_inset") {
1015 #ifdef NO_LATEX
1016                 insertErtContents(par, pos, font, false);
1017                 ert_stack.push(ert_comp);
1018                 ert_comp = ErtComp();
1019 #endif
1020                 readInset(lex, par, pos, font);
1021 #ifdef NO_LATEX
1022                 ert_comp = ert_stack.top();
1023                 ert_stack.pop();
1024 #endif
1025         } else if (token == "\\SpecialChar") {
1026                 LyXLayout const & layout =
1027                         textclasslist.Style(params.textclass, 
1028                                             par->getLayout());
1029
1030                 // Insets don't make sense in a free-spacing context! ---Kayvan
1031                 if (layout.free_spacing) {
1032                         if (lex.IsOK()) {
1033                                 lex.next();
1034                                 string next_token = lex.GetString();
1035                                 if (next_token == "\\-") {
1036                                         par->insertChar(pos, '-', font);
1037                                 } else if (next_token == "\\protected_separator"
1038                                         || next_token == "~") {
1039                                         par->insertChar(pos, ' ', font);
1040                                 } else {
1041                                         lex.printError("Token `$$Token' "
1042                                                        "is in free space "
1043                                                        "paragraph layout!");
1044                                         --pos;
1045                                 }
1046                         }
1047                 } else {
1048                         Inset * inset = new InsetSpecialChar;
1049                         inset->read(this, lex);
1050                         par->insertInset(pos, inset, font);
1051                 }
1052                 ++pos;
1053         } else if (token == "\\newline") {
1054 #ifdef NO_LATEX
1055
1056                 if (!ert_comp.in_tabular && ert_comp.active) {
1057                         ert_comp.contents += char(Paragraph::META_NEWLINE);
1058                 } else {
1059                         // Since we cannot know it this is only a regular
1060                         // newline or a tabular cell delimter we have to
1061                         // handle the ERT here.
1062                         insertErtContents(par, pos, font, false);
1063
1064                         par->insertChar(pos, Paragraph::META_NEWLINE, font);
1065                         ++pos;
1066                 }
1067 #else
1068                 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1069                 ++pos;
1070 #endif
1071         } else if (token == "\\LyXTable") {
1072 #ifdef NO_LATEX
1073                 ert_comp.in_tabular = true;
1074 #endif
1075                 Inset * inset = new InsetTabular(*this);
1076                 inset->read(this, lex);
1077                 par->insertInset(pos, inset, font);
1078                 ++pos;
1079                 // because of OLD_TABULAR_READ where tabulars have been
1080                 // one paragraph.
1081                 checkminipage = true;
1082         } else if (token == "\\hfill") {
1083                 par->insertChar(pos, Paragraph::META_HFILL, font);
1084                 ++pos;
1085         } else if (token == "\\protected_separator") { // obsolete
1086                 // This is a backward compability thingie. (Lgb)
1087                 // Remove it later some time...introduced with fileformat
1088                 // 2.16. (Lgb)
1089                 LyXLayout const & layout =
1090                         textclasslist.Style(params.textclass, 
1091                                             par->getLayout());
1092
1093                 if (layout.free_spacing) {
1094                         par->insertChar(pos, ' ', font);
1095                 } else {
1096                         Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1097                         par->insertInset(pos, inset, font);
1098                 }
1099                 ++pos;
1100         } else if (token == "\\bibitem") {  // ale970302
1101                 if (!par->bibkey) {
1102                         InsetCommandParams p("bibitem", "dummy");
1103                         par->bibkey = new InsetBibKey(p);
1104                 }
1105                 par->bibkey->read(this, lex);                   
1106         } else if (token == "\\backslash") {
1107 #ifdef NO_LATEX
1108                 if (ert_comp.active) {
1109                         ert_comp.contents += "\\";
1110                 } else {
1111 #endif
1112                 par->insertChar(pos, '\\', font);
1113                 ++pos;
1114 #ifdef NO_LATEX
1115                 }
1116 #endif
1117         } else if (token == "\\the_end") {
1118 #ifdef NO_LATEX
1119                 // If we still have some ert active here we have to insert
1120                 // it so we don't loose it. (Lgb)
1121                 insertErtContents(par, pos, font);
1122 #endif
1123                 the_end_read = true;
1124                 minipar = parBeforeMinipage = 0;
1125         } else {
1126 #ifdef NO_LATEX
1127                 if (ert_comp.active) {
1128                         ert_comp.contents += token;
1129                 } else {
1130 #endif
1131                 // This should be insurance for the future: (Asger)
1132                 lex.printError("Unknown token `$$Token'. "
1133                                "Inserting as text.");
1134                 string::const_iterator cit = token.begin();
1135                 string::const_iterator end = token.end();
1136                 for (; cit != end; ++cit) {
1137                         par->insertChar(pos, (*cit), font);
1138                         ++pos;
1139                 }
1140 #ifdef NO_LATEX
1141                 }
1142 #endif
1143         }
1144 #ifndef NO_PEXTRA_REALLY
1145         // now check if we have a minipage paragraph as at this
1146         // point we already read all the necessary data!
1147         // this cannot be done in layout because there we did
1148         // not read yet the paragraph PEXTRA-params (Jug)
1149         //
1150         // BEGIN pextra_minipage compability
1151         // This should be removed in 1.3.x (Lgb)
1152         
1153         // This compability code is not perfect. In a couple
1154         // of rand cases it fails. When the minipage par is
1155         // the first par in the document, and when there are
1156         // none or only one regular paragraphs after the
1157         // minipage. Currently I am not investing any effort
1158         // in fixing those cases.
1159
1160         //lyxerr << "Call depth: " << call_depth << endl;
1161         if (checkminipage && (call_depth == 1)) {
1162         checkminipage = false;
1163         if (minipar && (minipar != par) &&
1164             (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1165         {
1166                 lyxerr << "minipages in a row" << endl;
1167                 if (par->params().pextraStartMinipage()) {
1168                         lyxerr << "start new minipage" << endl;
1169                         // minipages in a row
1170                         par->previous()->next(0);
1171                         par->previous(0);
1172                                 
1173                         Paragraph * tmp = minipar;
1174                         while (tmp) {
1175                                 tmp->params().pextraType(0);
1176                                 tmp->params().pextraWidth(string());
1177                                 tmp->params().pextraWidthp(string());
1178                                 tmp->params().pextraAlignment(0);
1179                                 tmp->params().pextraHfill(false);
1180                                 tmp->params().pextraStartMinipage(false);
1181                                 tmp = tmp->next();
1182                         }
1183                         // create a new paragraph to insert the
1184                         // minipages in the following case
1185                         if (par->params().pextraStartMinipage() &&
1186                             !par->params().pextraHfill())
1187                         {
1188                                 Paragraph * p = new Paragraph;
1189                                 p->layout = 0;
1190                                 p->previous(parBeforeMinipage);
1191                                 parBeforeMinipage->next(p);
1192                                 p->next(0);
1193                                 p->params().depth(parBeforeMinipage->params().depth());
1194                                 parBeforeMinipage = p;
1195                         }
1196                         InsetMinipage * mini = new InsetMinipage;
1197                         mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1198                         mini->width(par->params().pextraWidth());
1199                         if (!par->params().pextraWidthp().empty()) {
1200                             lyxerr << "WP:" << mini->width() << endl;
1201                             mini->width(tostr(par->params().pextraWidthp())+"%");
1202                         }
1203                         mini->inset.paragraph(par);
1204                         // Insert the minipage last in the
1205                         // previous paragraph.
1206                         if (par->params().pextraHfill()) {
1207                                 parBeforeMinipage->insertChar
1208                                         (parBeforeMinipage->size(), Paragraph::META_HFILL);
1209                         }
1210                         parBeforeMinipage->insertInset
1211                                 (parBeforeMinipage->size(), mini);
1212                                 
1213                         minipar = par;
1214                 } else {
1215                         lyxerr << "new minipage par" << endl;
1216                         //nothing to do just continue reading
1217                 }
1218                         
1219         } else if (minipar && (minipar != par)) {
1220                 lyxerr << "last minipage par read" << endl;
1221                 // The last paragraph read was not part of a
1222                 // minipage but the par linked list is...
1223                 // So we need to remove the last par from the
1224                 // rest
1225                 if (par->previous())
1226                         par->previous()->next(0);
1227                 par->previous(parBeforeMinipage);
1228                 parBeforeMinipage->next(par);
1229                 Paragraph * tmp = minipar;
1230                 while (tmp) {
1231                         tmp->params().pextraType(0);
1232                         tmp->params().pextraWidth(string());
1233                         tmp->params().pextraWidthp(string());
1234                         tmp->params().pextraAlignment(0);
1235                         tmp->params().pextraHfill(false);
1236                         tmp->params().pextraStartMinipage(false);
1237                         tmp = tmp->next();
1238                 }
1239                 depth = parBeforeMinipage->params().depth();
1240                 minipar = parBeforeMinipage = 0;
1241         } else if (!minipar &&
1242                    (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1243         {
1244                 // par is the first paragraph in a minipage
1245                 lyxerr << "begin minipage" << endl;
1246                 // To minimize problems for
1247                 // the users we will insert
1248                 // the first minipage in
1249                 // a sequence of minipages
1250                 // in its own paragraph.
1251                 Paragraph * p = new Paragraph;
1252                 p->layout = 0;
1253                 p->previous(par->previous());
1254                 p->next(0);
1255                 p->params().depth(depth);
1256                 par->params().depth(0);
1257                 depth = 0;
1258                 if (par->previous())
1259                         par->previous()->next(p);
1260                 par->previous(0);
1261                 parBeforeMinipage = p;
1262                 minipar = par;
1263                 if (!first_par || (first_par == par))
1264                         first_par = p;
1265
1266                 InsetMinipage * mini = new InsetMinipage;
1267                 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1268                 mini->width(minipar->params().pextraWidth());
1269                 if (!par->params().pextraWidthp().empty()) {
1270                     lyxerr << "WP:" << mini->width() << endl;
1271                     mini->width(tostr(par->params().pextraWidthp())+"%");
1272                 }
1273                 mini->inset.paragraph(minipar);
1274                         
1275                 // Insert the minipage last in the
1276                 // previous paragraph.
1277                 if (minipar->params().pextraHfill()) {
1278                         parBeforeMinipage->insertChar
1279                                 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1280                 }
1281                 parBeforeMinipage->insertInset
1282                         (parBeforeMinipage->size(), mini);
1283         }
1284         }
1285         // End of pextra_minipage compability
1286 #endif
1287         --call_depth;
1288         return the_end_read;
1289 }
1290
1291
1292 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1293                        int & pos, LyXFont & font)
1294 {
1295         // consistency check
1296         if (lex.GetString() != "\\begin_inset") {
1297                 lyxerr << "Buffer::readInset: Consistency check failed."
1298                        << endl;
1299         }
1300         
1301         Inset * inset = 0;
1302
1303         lex.next();
1304         string const tmptok = lex.GetString();
1305         last_inset_read = tmptok;
1306
1307         // test the different insets
1308         if (tmptok == "LatexCommand") {
1309                 InsetCommandParams inscmd;
1310                 inscmd.read(lex);
1311
1312                 string const cmdName = inscmd.getCmdName();
1313                 
1314                 if (cmdName == "cite") {
1315                         inset = new InsetCitation(inscmd);
1316                 } else if (cmdName == "bibitem") {
1317                         lex.printError("Wrong place for bibitem");
1318                         inset = new InsetBibKey(inscmd);
1319                 } else if (cmdName == "BibTeX") {
1320                         inset = new InsetBibtex(inscmd);
1321                 } else if (cmdName == "index") {
1322                         inset = new InsetIndex(inscmd);
1323                 } else if (cmdName == "include") {
1324                         inset = new InsetInclude(inscmd, *this);
1325                 } else if (cmdName == "label") {
1326                         inset = new InsetLabel(inscmd);
1327                 } else if (cmdName == "url"
1328                            || cmdName == "htmlurl") {
1329                         inset = new InsetUrl(inscmd);
1330                 } else if (cmdName == "ref"
1331                            || cmdName == "pageref"
1332                            || cmdName == "vref"
1333                            || cmdName == "vpageref"
1334                            || cmdName == "prettyref") {
1335                         if (!inscmd.getOptions().empty()
1336                             || !inscmd.getContents().empty()) {
1337                                 inset = new InsetRef(inscmd, *this);
1338                         }
1339                 } else if (cmdName == "tableofcontents") {
1340                         inset = new InsetTOC(inscmd);
1341                 } else if (cmdName == "listofalgorithms") {
1342                         inset = new InsetFloatList("algorithm");
1343                 } else if (cmdName == "listoffigures") {
1344                         inset = new InsetFloatList("figure");
1345                 } else if (cmdName == "listoftables") {
1346                         inset = new InsetFloatList("table");
1347                 } else if (cmdName == "printindex") {
1348                         inset = new InsetPrintIndex(inscmd);
1349                 } else if (cmdName == "lyxparent") {
1350                         inset = new InsetParent(inscmd, *this);
1351                 }
1352         } else {
1353                 if (tmptok == "Quotes") {
1354                         inset = new InsetQuotes;
1355                 } else if (tmptok == "External") {
1356                         inset = new InsetExternal;
1357                 } else if (tmptok == "FormulaMacro") {
1358                         inset = new InsetFormulaMacro;
1359                 } else if (tmptok == "Formula") {
1360                         inset = new InsetFormula;
1361                 } else if (tmptok == "Figure") {
1362                         inset = new InsetFig(100, 100, *this);
1363                 } else if (tmptok == "Info") {
1364                         inset = new InsetInfo;
1365                 } else if (tmptok == "Include") {
1366                         InsetCommandParams p( "Include" );
1367                         inset = new InsetInclude(p, *this);
1368                 } else if (tmptok == "ERT") {
1369                         inset = new InsetERT;
1370                 } else if (tmptok == "Tabular") {
1371                         inset = new InsetTabular(*this);
1372                 } else if (tmptok == "Text") {
1373                         inset = new InsetText;
1374                 } else if (tmptok == "Foot") {
1375                         inset = new InsetFoot;
1376                 } else if (tmptok == "Marginal") {
1377                         inset = new InsetMarginal;
1378                 } else if (tmptok == "Minipage") {
1379                         inset = new InsetMinipage;
1380                 } else if (tmptok == "Float") {
1381                         lex.next();
1382                         string tmptok = lex.GetString();
1383                         inset = new InsetFloat(tmptok);
1384                 } else if (tmptok == "List") {
1385                         inset = new InsetList;
1386                 } else if (tmptok == "Theorem") {
1387                         inset = new InsetList;
1388                 } else if (tmptok == "Caption") {
1389                         inset = new InsetCaption;
1390                 } else if (tmptok == "GRAPHICS") {
1391                         inset = new InsetGraphics;
1392                 } else if (tmptok == "FloatList") {
1393                         inset = new InsetFloatList;
1394                 }
1395                 
1396                 if (inset) inset->read(this, lex);
1397         }
1398         
1399         if (inset) {
1400                 par->insertInset(pos, inset, font);
1401                 ++pos;
1402         }
1403 }
1404
1405
1406 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1407 {
1408         if (lex.IsOK()) {
1409                 lex.next();
1410                 string const token(lex.GetString());
1411                 if (token == "\\lyxformat") { // the first token _must_ be...
1412                         lex.EatLine();
1413                         string tmp_format = lex.GetString();
1414                         //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1415                         // if present remove ".," from string.
1416                         string::size_type dot = tmp_format.find_first_of(".,");
1417                         //lyxerr << "           dot found at " << dot << endl;
1418                         if (dot != string::npos)
1419                                 tmp_format.erase(dot, 1);
1420                         file_format = strToInt(tmp_format);
1421                         if (file_format == LYX_FORMAT) {
1422                                 // current format
1423                         } else if (file_format > LYX_FORMAT) {
1424                                 // future format
1425                                 WriteAlert(_("Warning!"),
1426                                            _("LyX file format is newer that what"),
1427                                            _("is supported in this LyX version. Expect some problems."));
1428                                 
1429                         } else if (file_format < LYX_FORMAT) {
1430                                 // old formats
1431                                 if (file_format < 200) {
1432                                         WriteAlert(_("ERROR!"),
1433                                                    _("Old LyX file format found. "
1434                                                      "Use LyX 0.10.x to read this!"));
1435                                         return false;
1436                                 }
1437                         }
1438                         bool the_end = readLyXformat2(lex, par);
1439                         setPaperStuff();
1440                         // the_end was added in 213
1441                         if (file_format < 213)
1442                                 the_end = true;
1443
1444                         if (!the_end)
1445                                 WriteAlert(_("Warning!"),
1446                                            _("Reading of document is not complete"),
1447                                            _("Maybe the document is truncated"));
1448                         return true;
1449                 } else { // "\\lyxformat" not found
1450                         WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1451                 }
1452         } else
1453                 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1454         return false;
1455 }
1456                     
1457
1458 // Should probably be moved to somewhere else: BufferView? LyXView?
1459 bool Buffer::save() const
1460 {
1461         // We don't need autosaves in the immediate future. (Asger)
1462         resetAutosaveTimers();
1463
1464         // make a backup
1465         string s;
1466         if (lyxrc.make_backup) {
1467                 s = fileName() + '~';
1468                 if (!lyxrc.backupdir_path.empty())
1469                         s = AddName(lyxrc.backupdir_path,
1470                                     subst(os::slashify_path(s),'/','!'));
1471
1472                 // Rename is the wrong way of making a backup,
1473                 // this is the correct way.
1474                 /* truss cp fil fil2:
1475                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1476                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1477                    open("LyXVC.lyx", O_RDONLY)                     = 3
1478                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1479                    fstat(4, 0xEFFFF508)                            = 0
1480                    fstat(3, 0xEFFFF508)                            = 0
1481                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1482                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1483                    read(3, 0xEFFFD4A0, 8192)                       = 0
1484                    close(4)                                        = 0
1485                    close(3)                                        = 0
1486                    chmod("LyXVC3.lyx", 0100644)                    = 0
1487                    lseek(0, 0, SEEK_CUR)                           = 46440
1488                    _exit(0)
1489                 */
1490
1491                 // Should probably have some more error checking here.
1492                 // Should be cleaned up in 0.13, at least a bit.
1493                 // Doing it this way, also makes the inodes stay the same.
1494                 // This is still not a very good solution, in particular we
1495                 // might loose the owner of the backup.
1496                 FileInfo finfo(fileName());
1497                 if (finfo.exist()) {
1498                         mode_t fmode = finfo.getMode();
1499                         struct utimbuf times = {
1500                                 finfo.getAccessTime(),
1501                                 finfo.getModificationTime() };
1502
1503                         ifstream ifs(fileName().c_str());
1504                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1505                         if (ifs && ofs) {
1506                                 ofs << ifs.rdbuf();
1507                                 ifs.close();
1508                                 ofs.close();
1509                                 ::chmod(s.c_str(), fmode);
1510                                 
1511                                 if (::utime(s.c_str(), &times)) {
1512                                         lyxerr << "utime error." << endl;
1513                                 }
1514                         } else {
1515                                 lyxerr << "LyX was not able to make "
1516                                         "backup copy. Beware." << endl;
1517                         }
1518                 }
1519         }
1520         
1521         if (writeFile(fileName(), false)) {
1522                 markLyxClean();
1523                 removeAutosaveFile(fileName());
1524         } else {
1525                 // Saving failed, so backup is not backup
1526                 if (lyxrc.make_backup) {
1527                         lyx::rename(s, fileName());
1528                 }
1529                 return false;
1530         }
1531         return true;
1532 }
1533
1534
1535 // Returns false if unsuccesful
1536 bool Buffer::writeFile(string const & fname, bool flag) const
1537 {
1538         // if flag is false writeFile will not create any GUI
1539         // warnings, only cerr.
1540         // Needed for autosave in background or panic save (Matthias 120496)
1541
1542         if (read_only && (fname == filename)) {
1543                 // Here we should come with a question if we should
1544                 // perform the write anyway.
1545                 if (flag)
1546                         lyxerr << _("Error! Document is read-only: ")
1547                                << fname << endl;
1548                 else
1549                         WriteAlert(_("Error! Document is read-only: "),
1550                                    fname);
1551                 return false;
1552         }
1553
1554         FileInfo finfo(fname);
1555         if (finfo.exist() && !finfo.writable()) {
1556                 // Here we should come with a question if we should
1557                 // try to do the save anyway. (i.e. do a chmod first)
1558                 if (flag)
1559                         lyxerr << _("Error! Cannot write file: ")
1560                                << fname << endl;
1561                 else
1562                         WriteFSAlert(_("Error! Cannot write file: "),
1563                                      fname);
1564                 return false;
1565         }
1566
1567         ofstream ofs(fname.c_str());
1568         if (!ofs) {
1569                 if (flag)
1570                         lyxerr << _("Error! Cannot open file: ")
1571                                << fname << endl;
1572                 else
1573                         WriteFSAlert(_("Error! Cannot open file: "),
1574                                      fname);
1575                 return false;
1576         }
1577
1578 #ifdef HAVE_LOCALE
1579         // Use the standard "C" locale for file output.
1580         ofs.imbue(std::locale::classic());
1581 #endif
1582
1583         // The top of the file should not be written by params.
1584
1585         // write out a comment in the top of the file
1586         ofs << '#' << LYX_DOCVERSION 
1587             << " created this file. For more info see http://www.lyx.org/\n"
1588             << "\\lyxformat " << LYX_FORMAT << "\n";
1589
1590         // now write out the buffer paramters.
1591         params.writeFile(ofs);
1592
1593         Paragraph::depth_type depth = 0;
1594
1595         // this will write out all the paragraphs
1596         // using recursive descent.
1597         paragraph->writeFile(this, ofs, params, depth);
1598
1599         // Write marker that shows file is complete
1600         ofs << "\n\\the_end" << endl;
1601
1602         ofs.close();
1603
1604         // how to check if close went ok?
1605         // Following is an attempt... (BE 20001011)
1606         
1607         // good() returns false if any error occured, including some
1608         //        formatting error.
1609         // bad()  returns true if something bad happened in the buffer,
1610         //        which should include file system full errors.
1611
1612         bool status = true;
1613         if (!ofs.good()) {
1614                 status = false;
1615 #if 0
1616                 if (ofs.bad()) {
1617                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1618                 } else {
1619                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1620                                << endl;
1621                 }
1622 #endif
1623         }
1624         
1625         return status;
1626 }
1627
1628
1629 string const Buffer::asciiParagraph(Paragraph const * par,
1630                                     unsigned int linelen) const
1631 {
1632         ostringstream buffer;
1633         Paragraph::depth_type depth = 0;
1634         int ltype = 0;
1635         Paragraph::depth_type ltype_depth = 0;
1636         unsigned int currlinelen = 0;
1637         bool ref_printed = false;
1638
1639         int noparbreak = 0;
1640         int islatex = 0;
1641         if (!par->previous()) {
1642                 // begins or ends a deeper area ?
1643                 if (depth != par->params().depth()) {
1644                         if (par->params().depth() > depth) {
1645                                 while (par->params().depth() > depth) {
1646                                         ++depth;
1647                                 }
1648                         } else {
1649                                 while (par->params().depth() < depth) {
1650                                         --depth;
1651                                 }
1652                         }
1653                 }
1654                 
1655                 // First write the layout
1656                 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1657                 if (tmp == "Itemize") {
1658                         ltype = 1;
1659                         ltype_depth = depth + 1;
1660                 } else if (tmp == "Enumerate") {
1661                         ltype = 2;
1662                         ltype_depth = depth + 1;
1663                 } else if (contains(tmp, "ection")) {
1664                         ltype = 3;
1665                         ltype_depth = depth + 1;
1666                 } else if (contains(tmp, "aragraph")) {
1667                         ltype = 4;
1668                         ltype_depth = depth + 1;
1669                 } else if (tmp == "Description") {
1670                         ltype = 5;
1671                         ltype_depth = depth + 1;
1672                 } else if (tmp == "Abstract") {
1673                         ltype = 6;
1674                         ltype_depth = 0;
1675                 } else if (tmp == "Bibliography") {
1676                         ltype = 7;
1677                         ltype_depth = 0;
1678                 } else {
1679                         ltype = 0;
1680                         ltype_depth = 0;
1681                 }
1682                 
1683                 /* maybe some vertical spaces */ 
1684                 
1685                 /* the labelwidthstring used in lists */ 
1686                 
1687                 /* some lines? */ 
1688                 
1689                 /* some pagebreaks? */ 
1690                 
1691                 /* noindent ? */ 
1692                 
1693                 /* what about the alignment */ 
1694         } else {
1695                 lyxerr << "Should this ever happen?" << endl;
1696         }
1697
1698 #ifndef NO_LATEX
1699         LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1700 #endif
1701         for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1702                 if (!i && !noparbreak) {
1703                         if (linelen > 0)
1704                                 buffer << "\n\n";
1705                         for (Paragraph::depth_type j = 0; j < depth; ++j)
1706                                 buffer << "  ";
1707                         currlinelen = depth * 2;
1708                         switch (ltype) {
1709                         case 0: // Standard
1710                         case 4: // (Sub)Paragraph
1711                         case 5: // Description
1712                                 break;
1713                         case 6: // Abstract
1714                                 if (linelen > 0)
1715                                         buffer << "Abstract\n\n";
1716                                 else
1717                                         buffer << "Abstract: ";
1718                                 break;
1719                         case 7: // Bibliography
1720                                 if (!ref_printed) {
1721                                         if (linelen > 0)
1722                                                 buffer << "References\n\n";
1723                                         else
1724                                                 buffer << "References: ";
1725                                         ref_printed = true;
1726                                 }
1727                                 break;
1728                         default:
1729                                 buffer << par->params().labelString() << " ";
1730                                 break;
1731                         }
1732                         if (ltype_depth > depth) {
1733                                 for (Paragraph::depth_type j = ltype_depth - 1; 
1734                                      j > depth; --j)
1735                                         buffer << "  ";
1736                                 currlinelen += (ltype_depth-depth)*2;
1737                         }
1738                 }
1739 #ifndef NO_LATEX
1740                 LyXFont const font2 = par->getFontSettings(params, i);
1741                 if (font1.latex() != font2.latex()) {
1742                         if (font2.latex() == LyXFont::OFF)
1743                                 islatex = 0;
1744                         else
1745                                 islatex = 1;
1746                 } else {
1747                         islatex = 0;
1748                 }
1749 #endif
1750                 
1751                 char c = par->getUChar(params, i);
1752                 if (islatex)
1753                         continue;
1754                 switch (c) {
1755                 case Paragraph::META_INSET:
1756                 {
1757                         Inset const * inset = par->getInset(i);
1758                         if (inset) {
1759                                 if (!inset->ascii(this, buffer)) {
1760                                         string dummy;
1761                                         string const s =
1762                                                 rsplit(buffer.str().c_str(),
1763                                                        dummy, '\n');
1764                                         currlinelen += s.length();
1765                                 } else {
1766                                         // to be sure it breaks paragraph
1767                                         currlinelen += linelen;
1768                                 }
1769                         }
1770                 }
1771                 break;
1772                 
1773                 case Paragraph::META_NEWLINE:
1774                         if (linelen > 0) {
1775                                 buffer << "\n";
1776                                 for (Paragraph::depth_type j = 0; 
1777                                      j < depth; ++j)
1778                                         buffer << "  ";
1779                         }
1780                         currlinelen = depth * 2;
1781                         if (ltype_depth > depth) {
1782                                 for (Paragraph::depth_type j = ltype_depth;
1783                                      j > depth; --j)
1784                                         buffer << "  ";
1785                                 currlinelen += (ltype_depth - depth) * 2;
1786                         }
1787                         break;
1788                         
1789                 case Paragraph::META_HFILL: 
1790                         buffer << "\t";
1791                         break;
1792                         
1793                 case '\\':
1794                         buffer << "\\";
1795                         break;
1796                         
1797                 default:
1798                         if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1799                             (c == ' ') && ((i + 2) < par->size()))
1800                         {
1801                                 buffer << "\n";
1802                                 for (Paragraph::depth_type j = 0; 
1803                                      j < depth; ++j)
1804                                         buffer << "  ";
1805                                 currlinelen = depth * 2;
1806                                 if (ltype_depth > depth) {
1807                                         for (Paragraph::depth_type j = ltype_depth;
1808                                             j > depth; --j)
1809                                                 buffer << "  ";
1810                                         currlinelen += (ltype_depth-depth)*2;
1811                                 }
1812                         } else if (c != '\0')
1813                                 buffer << c;
1814                         else if (c == '\0')
1815                                 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1816                         ++currlinelen;
1817                         break;
1818                 }
1819         }
1820         return buffer.str().c_str();
1821 }
1822
1823
1824 void Buffer::writeFileAscii(string const & fname, int linelen) 
1825 {
1826         ofstream ofs(fname.c_str());
1827         if (!ofs) {
1828                 WriteFSAlert(_("Error: Cannot write file:"), fname);
1829                 return;
1830         }
1831         writeFileAscii(ofs, linelen);
1832 }
1833
1834
1835 void Buffer::writeFileAscii(ostream & ofs, int linelen) 
1836 {
1837         Paragraph * par = paragraph;
1838         while (par) {
1839                 ofs << asciiParagraph(par, linelen);
1840                 par = par->next();
1841         }
1842         ofs << "\n";
1843 }
1844
1845 bool use_babel;
1846
1847 void Buffer::makeLaTeXFile(string const & fname, 
1848                            string const & original_path,
1849                            bool nice, bool only_body)
1850 {
1851         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1852         
1853         niceFile = nice; // this will be used by Insetincludes.
1854
1855         tex_code_break_column = lyxrc.ascii_linelen;
1856
1857         LyXTextClass const & tclass =
1858                 textclasslist.TextClass(params.textclass);
1859
1860         ofstream ofs(fname.c_str());
1861         if (!ofs) {
1862                 WriteFSAlert(_("Error: Cannot open file: "), fname);
1863                 return;
1864         }
1865         
1866         // validate the buffer.
1867         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1868         LaTeXFeatures features(params, tclass.numLayouts());
1869         validate(features);
1870         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1871         
1872         texrow.reset();
1873         // The starting paragraph of the coming rows is the 
1874         // first paragraph of the document. (Asger)
1875         texrow.start(paragraph, 0);
1876
1877         if (!only_body && nice) {
1878                 ofs << "%% " LYX_DOCVERSION " created this file.  "
1879                         "For more info, see http://www.lyx.org/.\n"
1880                         "%% Do not edit unless you really know what "
1881                         "you are doing.\n";
1882                 texrow.newline();
1883                 texrow.newline();
1884         }
1885         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1886         // There are a few differences between nice LaTeX and usual files:
1887         // usual is \batchmode and has a 
1888         // special input@path to allow the including of figures
1889         // with either \input or \includegraphics (what figinsets do).
1890         // batchmode is not set if there is a tex_code_break_column.
1891         // In this case somebody is interested in the generated LaTeX,
1892         // so this is OK. input@path is set when the actual parameter
1893         // original_path is set. This is done for usual tex-file, but not
1894         // for nice-latex-file. (Matthias 250696)
1895         if (!only_body) {
1896                 if (!nice){
1897                         // code for usual, NOT nice-latex-file
1898                         ofs << "\\batchmode\n"; // changed
1899                         // from \nonstopmode
1900                         texrow.newline();
1901                 }
1902                 if (!original_path.empty()) {
1903                         ofs << "\\makeatletter\n"
1904                             << "\\def\\input@path{{"
1905                             << os::external_path(original_path) << "/}}\n"
1906                             << "\\makeatother\n";
1907                         texrow.newline();
1908                         texrow.newline();
1909                         texrow.newline();
1910                 }
1911                 
1912                 ofs << "\\documentclass";
1913                 
1914                 ostringstream options; // the document class options.
1915                 
1916                 if (tokenPos(tclass.opt_fontsize(),
1917                              '|', params.fontsize) >= 0) {
1918                         // only write if existing in list (and not default)
1919                         options << params.fontsize << "pt,";
1920                 }
1921                 
1922                 
1923                 if (!params.use_geometry &&
1924                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1925                         switch (params.papersize) {
1926                         case BufferParams::PAPER_A4PAPER:
1927                                 options << "a4paper,";
1928                                 break;
1929                         case BufferParams::PAPER_USLETTER:
1930                                 options << "letterpaper,";
1931                                 break;
1932                         case BufferParams::PAPER_A5PAPER:
1933                                 options << "a5paper,";
1934                                 break;
1935                         case BufferParams::PAPER_B5PAPER:
1936                                 options << "b5paper,";
1937                                 break;
1938                         case BufferParams::PAPER_EXECUTIVEPAPER:
1939                                 options << "executivepaper,";
1940                                 break;
1941                         case BufferParams::PAPER_LEGALPAPER:
1942                                 options << "legalpaper,";
1943                                 break;
1944                         }
1945                 }
1946
1947                 // if needed
1948                 if (params.sides != tclass.sides()) {
1949                         switch (params.sides) {
1950                         case LyXTextClass::OneSide:
1951                                 options << "oneside,";
1952                                 break;
1953                         case LyXTextClass::TwoSides:
1954                                 options << "twoside,";
1955                                 break;
1956                         }
1957                 }
1958
1959                 // if needed
1960                 if (params.columns != tclass.columns()) {
1961                         if (params.columns == 2)
1962                                 options << "twocolumn,";
1963                         else
1964                                 options << "onecolumn,";
1965                 }
1966
1967                 if (!params.use_geometry 
1968                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1969                         options << "landscape,";
1970                 
1971                 // language should be a parameter to \documentclass
1972                 use_babel = false;
1973                 ostringstream language_options;
1974                 if (params.language->babel() == "hebrew"
1975                     && default_language->babel() != "hebrew")
1976                          // This seems necessary
1977                         features.UsedLanguages.insert(default_language);
1978
1979                 if (lyxrc.language_use_babel ||
1980                     params.language->lang() != lyxrc.default_language ||
1981                     !features.UsedLanguages.empty()) {
1982                         use_babel = true;
1983                         for (LaTeXFeatures::LanguageList::const_iterator cit =
1984                                      features.UsedLanguages.begin();
1985                              cit != features.UsedLanguages.end(); ++cit)
1986                                 language_options << (*cit)->babel() << ',';
1987                         language_options << params.language->babel();
1988                         if (lyxrc.language_global_options)
1989                                 options << language_options.str() << ',';
1990                 }
1991
1992                 // the user-defined options
1993                 if (!params.options.empty()) {
1994                         options << params.options << ',';
1995                 }
1996
1997                 string strOptions(options.str().c_str());
1998                 if (!strOptions.empty()){
1999                         strOptions = strip(strOptions, ',');
2000                         ofs << '[' << strOptions << ']';
2001                 }
2002                 
2003                 ofs << '{'
2004                     << textclasslist.LatexnameOfClass(params.textclass)
2005                     << "}\n";
2006                 texrow.newline();
2007                 // end of \documentclass defs
2008                 
2009                 // font selection must be done before loading fontenc.sty
2010                 // The ae package is not needed when using OT1 font encoding.
2011                 if (params.fonts != "default" &&
2012                     (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2013                         ofs << "\\usepackage{" << params.fonts << "}\n";
2014                         texrow.newline();
2015                         if (params.fonts == "ae") {
2016                                 ofs << "\\usepackage{aecompl}\n";
2017                                 texrow.newline();
2018                         }
2019                 }
2020                 // this one is not per buffer
2021                 if (lyxrc.fontenc != "default") {
2022                         ofs << "\\usepackage[" << lyxrc.fontenc
2023                             << "]{fontenc}\n";
2024                         texrow.newline();
2025                 }
2026
2027                 if (params.inputenc == "auto") {
2028                         string const doc_encoding =
2029                                 params.language->encoding()->LatexName();
2030
2031                         // Create a list with all the input encodings used 
2032                         // in the document
2033                         set<string> encodings;
2034                         for (LaTeXFeatures::LanguageList::const_iterator it =
2035                                      features.UsedLanguages.begin();
2036                              it != features.UsedLanguages.end(); ++it)
2037                                 if ((*it)->encoding()->LatexName() != doc_encoding)
2038                                         encodings.insert((*it)->encoding()->LatexName());
2039
2040                         ofs << "\\usepackage[";
2041                         std::copy(encodings.begin(), encodings.end(),
2042                                   std::ostream_iterator<string>(ofs, ","));
2043                         ofs << doc_encoding << "]{inputenc}\n";
2044                         texrow.newline();
2045                 } else if (params.inputenc != "default") {
2046                         ofs << "\\usepackage[" << params.inputenc
2047                             << "]{inputenc}\n";
2048                         texrow.newline();
2049                 }
2050
2051                 // At the very beginning the text parameters.
2052                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2053                         switch (params.paperpackage) {
2054                         case BufferParams::PACKAGE_A4:
2055                                 ofs << "\\usepackage{a4}\n";
2056                                 texrow.newline();
2057                                 break;
2058                         case BufferParams::PACKAGE_A4WIDE:
2059                                 ofs << "\\usepackage{a4wide}\n";
2060                                 texrow.newline();
2061                                 break;
2062                         case BufferParams::PACKAGE_WIDEMARGINSA4:
2063                                 ofs << "\\usepackage[widemargins]{a4}\n";
2064                                 texrow.newline();
2065                                 break;
2066                         }
2067                 }
2068                 if (params.use_geometry) {
2069                         ofs << "\\usepackage{geometry}\n";
2070                         texrow.newline();
2071                         ofs << "\\geometry{verbose";
2072                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2073                                 ofs << ",landscape";
2074                         switch (params.papersize2) {
2075                         case BufferParams::VM_PAPER_CUSTOM:
2076                                 if (!params.paperwidth.empty())
2077                                         ofs << ",paperwidth="
2078                                             << params.paperwidth;
2079                                 if (!params.paperheight.empty())
2080                                         ofs << ",paperheight="
2081                                             << params.paperheight;
2082                                 break;
2083                         case BufferParams::VM_PAPER_USLETTER:
2084                                 ofs << ",letterpaper";
2085                                 break;
2086                         case BufferParams::VM_PAPER_USLEGAL:
2087                                 ofs << ",legalpaper";
2088                                 break;
2089                         case BufferParams::VM_PAPER_USEXECUTIVE:
2090                                 ofs << ",executivepaper";
2091                                 break;
2092                         case BufferParams::VM_PAPER_A3:
2093                                 ofs << ",a3paper";
2094                                 break;
2095                         case BufferParams::VM_PAPER_A4:
2096                                 ofs << ",a4paper";
2097                                 break;
2098                         case BufferParams::VM_PAPER_A5:
2099                                 ofs << ",a5paper";
2100                                 break;
2101                         case BufferParams::VM_PAPER_B3:
2102                                 ofs << ",b3paper";
2103                                 break;
2104                         case BufferParams::VM_PAPER_B4:
2105                                 ofs << ",b4paper";
2106                                 break;
2107                         case BufferParams::VM_PAPER_B5:
2108                                 ofs << ",b5paper";
2109                                 break;
2110                         default:
2111                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2112                                 switch (lyxrc.default_papersize) {
2113                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2114                                 case BufferParams::PAPER_USLETTER:
2115                                         ofs << ",letterpaper";
2116                                         break;
2117                                 case BufferParams::PAPER_LEGALPAPER:
2118                                         ofs << ",legalpaper";
2119                                         break;
2120                                 case BufferParams::PAPER_EXECUTIVEPAPER:
2121                                         ofs << ",executivepaper";
2122                                         break;
2123                                 case BufferParams::PAPER_A3PAPER:
2124                                         ofs << ",a3paper";
2125                                         break;
2126                                 case BufferParams::PAPER_A4PAPER:
2127                                         ofs << ",a4paper";
2128                                         break;
2129                                 case BufferParams::PAPER_A5PAPER:
2130                                         ofs << ",a5paper";
2131                                         break;
2132                                 case BufferParams::PAPER_B5PAPER:
2133                                         ofs << ",b5paper";
2134                                         break;
2135                                 }
2136                         }
2137                         if (!params.topmargin.empty())
2138                                 ofs << ",tmargin=" << params.topmargin;
2139                         if (!params.bottommargin.empty())
2140                                 ofs << ",bmargin=" << params.bottommargin;
2141                         if (!params.leftmargin.empty())
2142                                 ofs << ",lmargin=" << params.leftmargin;
2143                         if (!params.rightmargin.empty())
2144                                 ofs << ",rmargin=" << params.rightmargin;
2145                         if (!params.headheight.empty())
2146                                 ofs << ",headheight=" << params.headheight;
2147                         if (!params.headsep.empty())
2148                                 ofs << ",headsep=" << params.headsep;
2149                         if (!params.footskip.empty())
2150                                 ofs << ",footskip=" << params.footskip;
2151                         ofs << "}\n";
2152                         texrow.newline();
2153                 }
2154                 if (features.amsstyle
2155                     && !tclass.provides(LyXTextClass::amsmath)) {
2156                         ofs << "\\usepackage{amsmath}\n";
2157                         texrow.newline();
2158                 }
2159
2160                 if (tokenPos(tclass.opt_pagestyle(),
2161                              '|', params.pagestyle) >= 0) {
2162                         if (params.pagestyle == "fancy") {
2163                                 ofs << "\\usepackage{fancyhdr}\n";
2164                                 texrow.newline();
2165                         }
2166                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2167                         texrow.newline();
2168                 }
2169
2170                 // We try to load babel late, in case it interferes
2171                 // with other packages.
2172                 if (use_babel) {
2173                         string tmp = lyxrc.language_package;
2174                         if (!lyxrc.language_global_options
2175                             && tmp == "\\usepackage{babel}")
2176                                 tmp = string("\\usepackage[") +
2177                                         language_options.str().c_str() +
2178                                         "]{babel}";
2179                         ofs << tmp << "\n";
2180                         texrow.newline();
2181                 }
2182
2183                 if (params.secnumdepth != tclass.secnumdepth()) {
2184                         ofs << "\\setcounter{secnumdepth}{"
2185                             << params.secnumdepth
2186                             << "}\n";
2187                         texrow.newline();
2188                 }
2189                 if (params.tocdepth != tclass.tocdepth()) {
2190                         ofs << "\\setcounter{tocdepth}{"
2191                             << params.tocdepth
2192                             << "}\n";
2193                         texrow.newline();
2194                 }
2195                 
2196                 if (params.paragraph_separation) {
2197                         switch (params.defskip.kind()) {
2198                         case VSpace::SMALLSKIP: 
2199                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2200                                 break;
2201                         case VSpace::MEDSKIP:
2202                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2203                                 break;
2204                         case VSpace::BIGSKIP:
2205                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2206                                 break;
2207                         case VSpace::LENGTH:
2208                                 ofs << "\\setlength\\parskip{"
2209                                     << params.defskip.length().asLatexString()
2210                                     << "}\n";
2211                                 break;
2212                         default: // should never happen // Then delete it.
2213                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2214                                 break;
2215                         }
2216                         texrow.newline();
2217                         
2218                         ofs << "\\setlength\\parindent{0pt}\n";
2219                         texrow.newline();
2220                 }
2221
2222                 // Now insert the LyX specific LaTeX commands...
2223
2224                 // The optional packages;
2225                 string preamble(features.getPackages());
2226
2227                 // this might be useful...
2228                 preamble += "\n\\makeatletter\n";
2229
2230                 // Some macros LyX will need
2231                 string tmppreamble(features.getMacros());
2232
2233                 if (!tmppreamble.empty()) {
2234                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2235                                 "LyX specific LaTeX commands.\n"
2236                                 + tmppreamble + '\n';
2237                 }
2238
2239                 // the text class specific preamble 
2240                 tmppreamble = features.getTClassPreamble();
2241                 if (!tmppreamble.empty()) {
2242                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2243                                 "Textclass specific LaTeX commands.\n"
2244                                 + tmppreamble + '\n';
2245                 }
2246
2247                 /* the user-defined preamble */
2248                 if (!params.preamble.empty()) {
2249                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2250                                 "User specified LaTeX commands.\n"
2251                                 + params.preamble + '\n';
2252                 }
2253
2254                 preamble += "\\makeatother\n";
2255
2256                 // Itemize bullet settings need to be last in case the user
2257                 // defines their own bullets that use a package included
2258                 // in the user-defined preamble -- ARRae
2259                 // Actually it has to be done much later than that
2260                 // since some packages like frenchb make modifications
2261                 // at \begin{document} time -- JMarc 
2262                 string bullets_def;
2263                 for (int i = 0; i < 4; ++i) {
2264                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2265                                 if (bullets_def.empty())
2266                                         bullets_def="\\AtBeginDocument{\n";
2267                                 bullets_def += "  \\renewcommand{\\labelitemi";
2268                                 switch (i) {
2269                                 // `i' is one less than the item to modify
2270                                 case 0:
2271                                         break;
2272                                 case 1:
2273                                         bullets_def += 'i';
2274                                         break;
2275                                 case 2:
2276                                         bullets_def += "ii";
2277                                         break;
2278                                 case 3:
2279                                         bullets_def += 'v';
2280                                         break;
2281                                 }
2282                                 bullets_def += "}{" + 
2283                                   params.user_defined_bullets[i].getText() 
2284                                   + "}\n";
2285                         }
2286                 }
2287
2288                 if (!bullets_def.empty())
2289                   preamble += bullets_def + "}\n\n";
2290
2291                 for (int j = countChar(preamble, '\n'); j-- ;) {
2292                         texrow.newline();
2293                 }
2294
2295                 ofs << preamble;
2296
2297                 // make the body.
2298                 ofs << "\\begin{document}\n";
2299                 texrow.newline();
2300         } // only_body
2301         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2302
2303         if (!lyxrc.language_auto_begin) {
2304                 ofs << subst(lyxrc.language_command_begin, "$$lang",
2305                              params.language->babel())
2306                     << endl;
2307                 texrow.newline();
2308         }
2309         
2310         latexParagraphs(ofs, paragraph, 0, texrow);
2311
2312         // add this just in case after all the paragraphs
2313         ofs << endl;
2314         texrow.newline();
2315
2316         if (!lyxrc.language_auto_end) {
2317                 ofs << subst(lyxrc.language_command_end, "$$lang",
2318                              params.language->babel())
2319                     << endl;
2320                 texrow.newline();
2321         }
2322
2323         if (!only_body) {
2324                 ofs << "\\end{document}\n";
2325                 texrow.newline();
2326         
2327                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2328         } else {
2329                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2330                                      << endl;
2331         }
2332
2333         // Just to be sure. (Asger)
2334         texrow.newline();
2335
2336         // tex_code_break_column's value is used to decide
2337         // if we are in batchmode or not (within mathed_write()
2338         // in math_write.C) so we must set it to a non-zero
2339         // value when we leave otherwise we save incorrect .lyx files.
2340         tex_code_break_column = lyxrc.ascii_linelen;
2341
2342         ofs.close();
2343         if (ofs.fail()) {
2344                 lyxerr << "File was not closed properly." << endl;
2345         }
2346         
2347         lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2348 }
2349
2350
2351 //
2352 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2353 //
2354 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2355                              Paragraph * endpar, TexRow & texrow) const
2356 {
2357         bool was_title = false;
2358         bool already_title = false;
2359
2360         // if only_body
2361         while (par != endpar) {
2362                 LyXLayout const & layout =
2363                         textclasslist.Style(params.textclass,
2364                                             par->layout);
2365             
2366                 if (layout.intitle) {
2367                         if (already_title) {
2368                                 lyxerr <<"Error in latexParagraphs: You"
2369                                         " should not mix title layouts"
2370                                         " with normal ones." << endl;
2371                         } else
2372                                 was_title = true;
2373                 } else if (was_title && !already_title) {
2374                         ofs << "\\maketitle\n";
2375                         texrow.newline();
2376                         already_title = true;
2377                         was_title = false;                  
2378                 }
2379                 
2380                 if (layout.isEnvironment()) {
2381                         par = par->TeXEnvironment(this, params, ofs, texrow);
2382                 } else {
2383                         par = par->TeXOnePar(this, params, ofs, texrow, false);
2384                 }
2385         }
2386         // It might be that we only have a title in this document
2387         if (was_title && !already_title) {
2388                 ofs << "\\maketitle\n";
2389                 texrow.newline();
2390         }
2391 }
2392
2393
2394 bool Buffer::isLatex() const
2395 {
2396         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2397 }
2398
2399
2400 bool Buffer::isLinuxDoc() const
2401 {
2402         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2403 }
2404
2405
2406 bool Buffer::isLiterate() const
2407 {
2408         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2409 }
2410
2411
2412 bool Buffer::isDocBook() const
2413 {
2414         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2415 }
2416
2417
2418 bool Buffer::isSGML() const
2419 {
2420         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2421                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2422 }
2423
2424
2425 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2426                          string const & latexname) const
2427 {
2428         if (!latexname.empty() && latexname != "!-- --")
2429                 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2430         //os << string(depth, ' ') << "<" << latexname << ">\n";
2431 }
2432
2433
2434 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2435                           string const & latexname) const
2436 {
2437         if (!latexname.empty() && latexname != "!-- --")
2438                 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2439         //os << string(depth, ' ') << "</" << latexname << ">\n";
2440 }
2441
2442
2443 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2444 {
2445         ofstream ofs(fname.c_str());
2446
2447         if (!ofs) {
2448                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2449                 return;
2450         }
2451
2452         niceFile = nice; // this will be used by included files.
2453
2454         LyXTextClass const & tclass =
2455                 textclasslist.TextClass(params.textclass);
2456
2457         LaTeXFeatures features(params, tclass.numLayouts());
2458         validate(features);
2459
2460         texrow.reset();
2461
2462         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2463
2464         if (!body_only) {
2465                 string sgml_includedfiles=features.getIncludedFiles(fname);
2466
2467                 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2468                         ofs << "<!doctype linuxdoc system>\n\n";
2469                 } else {
2470                         ofs << "<!doctype linuxdoc system [ "
2471                             << params.preamble << sgml_includedfiles << " \n]>\n\n";
2472                 }
2473
2474                 if (params.options.empty())
2475                         sgmlOpenTag(ofs, 0, top_element);
2476                 else {
2477                         string top = top_element;
2478                         top += " ";
2479                         top += params.options;
2480                         sgmlOpenTag(ofs, 0, top);
2481                 }
2482         }
2483
2484         ofs << "<!-- "  << LYX_DOCVERSION 
2485             << " created this file. For more info see http://www.lyx.org/"
2486             << " -->\n";
2487
2488         Paragraph::depth_type depth = 0; // paragraph depth
2489         Paragraph * par = paragraph;
2490         string item_name;
2491         vector<string> environment_stack(5);
2492
2493         while (par) {
2494                 LyXLayout const & style =
2495                         textclasslist.Style(params.textclass,
2496                                             par->layout);
2497
2498                 // treat <toc> as a special case for compatibility with old code
2499                 if (par->getChar(0) == Paragraph::META_INSET) {
2500                         Inset * inset = par->getInset(0);
2501                         Inset::Code lyx_code = inset->lyxCode();
2502                         if (lyx_code == Inset::TOC_CODE){
2503                                 string const temp = "toc";
2504                                 sgmlOpenTag(ofs, depth, temp);
2505
2506                                 par = par->next();
2507                                 continue;
2508                         }
2509                 }
2510
2511                 // environment tag closing
2512                 for (; depth > par->params().depth(); --depth) {
2513                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2514                         environment_stack[depth].erase();
2515                 }
2516
2517                 // write opening SGML tags
2518                 switch (style.latextype) {
2519                 case LATEX_PARAGRAPH:
2520                         if (depth == par->params().depth() 
2521                            && !environment_stack[depth].empty()) {
2522                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2523                                 environment_stack[depth].erase();
2524                                 if (depth) 
2525                                         --depth;
2526                                 else
2527                                         ofs << "</p>";
2528                         }
2529                         sgmlOpenTag(ofs, depth, style.latexname());
2530                         break;
2531
2532                 case LATEX_COMMAND:
2533                         if (depth!= 0)
2534                                 linuxDocError(par, 0,
2535                                               _("Error : Wrong depth for"
2536                                                 " LatexType Command.\n"));
2537
2538                         if (!environment_stack[depth].empty()){
2539                                 sgmlCloseTag(ofs, depth,
2540                                              environment_stack[depth]);
2541                                 ofs << "</p>";
2542                         }
2543
2544                         environment_stack[depth].erase();
2545                         sgmlOpenTag(ofs, depth, style.latexname());
2546                         break;
2547
2548                 case LATEX_ENVIRONMENT:
2549                 case LATEX_ITEM_ENVIRONMENT:
2550                         if (depth == par->params().depth() 
2551                             && environment_stack[depth] != style.latexname()) {
2552                                 sgmlCloseTag(ofs, depth,
2553                                              environment_stack[depth]);
2554                                 environment_stack[depth].erase();
2555                         }
2556                         if (depth < par->params().depth()) {
2557                                depth = par->params().depth();
2558                                environment_stack[depth].erase();
2559                         }
2560                         if (environment_stack[depth] != style.latexname()) {
2561                                 if (depth == 0) {
2562                                         sgmlOpenTag(ofs, depth, "p");
2563                                 }
2564                                 sgmlOpenTag(ofs, depth, style.latexname());
2565
2566                                 if (environment_stack.size() == depth + 1)
2567                                         environment_stack.push_back("!-- --");
2568                                 environment_stack[depth] = style.latexname();
2569                         }
2570
2571                         if (style.latexparam() == "CDATA")
2572                                 ofs << "<![CDATA[";
2573
2574                         if (style.latextype == LATEX_ENVIRONMENT) break;
2575
2576                         if (style.labeltype == LABEL_MANUAL)
2577                                 item_name = "tag";
2578                         else
2579                                 item_name = "item";
2580
2581                         sgmlOpenTag(ofs, depth + 1, item_name);
2582                         break;
2583                 default:
2584                         sgmlOpenTag(ofs, depth, style.latexname());
2585                         break;
2586                 }
2587
2588                 simpleLinuxDocOnePar(ofs, par, depth);
2589
2590                 par = par->next();
2591
2592                 ofs << "\n";
2593                 // write closing SGML tags
2594                 switch (style.latextype) {
2595                 case LATEX_COMMAND:
2596                         break;
2597                 case LATEX_ENVIRONMENT:
2598                 case LATEX_ITEM_ENVIRONMENT:
2599                         if (style.latexparam() == "CDATA")
2600                                 ofs << "]]>";
2601                         break;
2602                 default:
2603                         sgmlCloseTag(ofs, depth, style.latexname());
2604                         break;
2605                 }
2606         }
2607    
2608         // Close open tags
2609         for (int i=depth; i >= 0; --i)
2610                 sgmlCloseTag(ofs, depth, environment_stack[i]);
2611
2612         if (!body_only) {
2613                 ofs << "\n\n";
2614                 sgmlCloseTag(ofs, 0, top_element);
2615         }
2616
2617         ofs.close();
2618         // How to check for successful close
2619 }
2620
2621
2622 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2623                                   Paragraph::depth_type depth, int desc_on,
2624                                   Paragraph * & par)
2625 {
2626         Paragraph * tpar = par;
2627         while (tpar
2628                && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2629                                                                 "Caption").second))
2630                 tpar = tpar->next();
2631
2632         if (tpar &&
2633             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2634                                                          "Caption").second) {
2635                 sgmlOpenTag(os, depth + 1, inner_tag);
2636                 string extra_par;
2637                 simpleDocBookOnePar(os, extra_par, tpar,
2638                                     desc_on, depth + 2);
2639                 sgmlCloseTag(os, depth+1, inner_tag);
2640                 if (!extra_par.empty())
2641                         os << extra_par;
2642         }
2643 }
2644
2645
2646 // checks, if newcol chars should be put into this line
2647 // writes newline, if necessary.
2648 namespace {
2649
2650 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2651                           string::size_type newcol)
2652 {
2653         colcount += newcol;
2654         if (colcount > lyxrc.ascii_linelen) {
2655                 os << "\n";
2656                 colcount = newcol; // assume write after this call
2657         }
2658 }
2659
2660 enum PAR_TAG {
2661         NONE=0,
2662         TT = 1,
2663         SF = 2,
2664         BF = 4,
2665         IT = 8,
2666         SL = 16,
2667         EM = 32
2668 };
2669
2670
2671 string tag_name(PAR_TAG const & pt) {
2672         switch (pt) {
2673         case NONE: return "!-- --";
2674         case TT: return "tt";
2675         case SF: return "sf";
2676         case BF: return "bf";
2677         case IT: return "it";
2678         case SL: return "sl";
2679         case EM: return "em";
2680         }
2681         return "";
2682 }
2683
2684
2685 inline
2686 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2687 {
2688         p1 = static_cast<PAR_TAG>(p1 | p2);
2689 }
2690
2691
2692 inline
2693 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2694 {
2695         p1 = static_cast<PAR_TAG>( p1 & ~p2);
2696 }
2697
2698 } // namespace anon
2699
2700
2701
2702
2703 // Handle internal paragraph parsing -- layout already processed.
2704 void Buffer::simpleLinuxDocOnePar(ostream & os,
2705                                   Paragraph * par, 
2706                                   Paragraph::depth_type /*depth*/)
2707 {
2708         LyXLayout const & style = textclasslist.Style(params.textclass,
2709                                                       par->getLayout());
2710         string::size_type char_line_count = 5;     // Heuristic choice ;-) 
2711
2712         // gets paragraph main font
2713         LyXFont font_old;
2714         bool desc_on;
2715         if (style.labeltype == LABEL_MANUAL) {
2716                 font_old = style.labelfont;
2717                 desc_on = true;
2718         } else {
2719                 font_old = style.font;
2720                 desc_on = false;
2721         }
2722
2723         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2724         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2725         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
2726         bool is_em = false;
2727
2728         stack < PAR_TAG > tag_state;
2729         // parsing main loop
2730         for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2731
2732                 PAR_TAG tag_close = NONE;
2733                 list < PAR_TAG > tag_open;
2734
2735                 LyXFont const font = par->getFont(params, i);
2736
2737                 if (font_old.family() != font.family()) {
2738                         switch (family_type) {
2739                         case LyXFont::SANS_FAMILY:
2740                                 tag_close |= SF;
2741                                 break;
2742                         case LyXFont::TYPEWRITER_FAMILY:
2743                                 tag_close |= TT;
2744                                 break;
2745                         default:
2746                                 break;
2747                         }
2748
2749                         family_type = font.family();
2750
2751                         switch (family_type) {
2752                         case LyXFont::SANS_FAMILY:
2753                                 tag_open.push_back(SF);
2754                                 break;
2755                         case LyXFont::TYPEWRITER_FAMILY:
2756                                 tag_open.push_back(TT);
2757                                 break;
2758                         default:
2759                                 break;
2760                         }
2761                 }
2762
2763                 if (font_old.series() != font.series()) {
2764                         switch (series_type) {
2765                         case LyXFont::BOLD_SERIES:
2766                                 tag_close |= BF;
2767                                 break;
2768                         default:
2769                                 break;
2770                         }
2771
2772                         series_type = font.series();
2773
2774                         switch (series_type) {
2775                         case LyXFont::BOLD_SERIES:
2776                                 tag_open.push_back(BF);
2777                                 break;
2778                         default:
2779                                 break;
2780                         }
2781
2782                 }
2783
2784                 if (font_old.shape() != font.shape()) {
2785                         switch (shape_type) {
2786                         case LyXFont::ITALIC_SHAPE:
2787                                 tag_close |= IT;
2788                                 break;
2789                         case LyXFont::SLANTED_SHAPE:
2790                                 tag_close |= SL;
2791                                 break;
2792                         default:
2793                                 break;
2794                         }
2795
2796                         shape_type = font.shape();
2797
2798                         switch (shape_type) {
2799                         case LyXFont::ITALIC_SHAPE:
2800                                 tag_open.push_back(IT);
2801                                 break;
2802                         case LyXFont::SLANTED_SHAPE:
2803                                 tag_open.push_back(SL);
2804                                 break;
2805                         default:
2806                                 break;
2807                         }
2808                 }
2809                 // handle <em> tag
2810                 if (font_old.emph() != font.emph()) {
2811                         if (font.emph() == LyXFont::ON) {
2812                                 tag_open.push_back(EM);
2813                                 is_em = true;
2814                         }
2815                         else if (is_em) {
2816                                 tag_close |= EM;
2817                                 is_em = false;
2818                         }
2819                 }
2820
2821                 list < PAR_TAG > temp;
2822                 while(!tag_state.empty() && tag_close ) {
2823                         PAR_TAG k =  tag_state.top();
2824                         tag_state.pop();
2825                         os << "</" << tag_name(k) << ">";
2826                         if (tag_close & k)
2827                                 reset(tag_close,k);
2828                         else
2829                                 temp.push_back(k);
2830                 }
2831
2832                 for(list< PAR_TAG >::const_iterator j = temp.begin();
2833                     j != temp.end(); ++j) {
2834                         tag_state.push(*j);
2835                         os << "<" << tag_name(*j) << ">";
2836                 }
2837
2838                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2839                     j != tag_open.end(); ++j) {
2840                         tag_state.push(*j);
2841                         os << "<" << tag_name(*j) << ">";
2842                 }
2843
2844                 char c = par->getChar(i);
2845
2846                 if (c == Paragraph::META_INSET) {
2847                         Inset * inset = par->getInset(i);
2848                         inset->linuxdoc(this, os);
2849                         font_old = font;
2850                         continue;
2851                 }
2852
2853                 if (
2854 #ifndef NO_LATEX
2855                         font.latex() == LyXFont::ON ||
2856 #endif
2857                     style.latexparam() == "CDATA") {
2858                         // "TeX"-Mode on == > SGML-Mode on.
2859                         if (c != '\0')
2860                                 os << c;
2861                         ++char_line_count;
2862                 } else {
2863                         string sgml_string;
2864                         if (par->linuxDocConvertChar(c, sgml_string)
2865                             && !style.free_spacing) { 
2866                                 // in freespacing mode, spaces are
2867                                 // non-breaking characters
2868                                 if (desc_on) {// if char is ' ' then...
2869
2870                                         ++char_line_count;
2871                                         linux_doc_line_break(os, char_line_count, 6);
2872                                         os << "</tag>";
2873                                         desc_on = false;
2874                                 } else  {
2875                                         linux_doc_line_break(os, char_line_count, 1);
2876                                         os << c;
2877                                 }
2878                         } else {
2879                                 os << sgml_string;
2880                                 char_line_count += sgml_string.length();
2881                         }
2882                 }
2883                 font_old = font;
2884         }
2885
2886         while (!tag_state.empty()) {
2887                 os << "</" << tag_name(tag_state.top()) << ">";
2888                 tag_state.pop();
2889         }
2890
2891         // resets description flag correctly
2892         if (desc_on) {
2893                 // <tag> not closed...
2894                 linux_doc_line_break(os, char_line_count, 6);
2895                 os << "</tag>";
2896         }
2897 }
2898
2899
2900 // Print an error message.
2901 void Buffer::linuxDocError(Paragraph * par, int pos,
2902                            string const & message) 
2903 {
2904         // insert an error marker in text
2905         InsetError * new_inset = new InsetError(message);
2906         par->insertInset(pos, new_inset);
2907 }
2908
2909
2910 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2911 {
2912         ofstream ofs(fname.c_str());
2913         if (!ofs) {
2914                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2915                 return;
2916         }
2917
2918         Paragraph * par = paragraph;
2919
2920         niceFile = nice; // this will be used by Insetincludes.
2921
2922         LyXTextClass const & tclass =
2923                 textclasslist.TextClass(params.textclass);
2924
2925         LaTeXFeatures features(params, tclass.numLayouts());
2926         validate(features);
2927    
2928         texrow.reset();
2929
2930         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2931
2932         if (!only_body) {
2933                 string sgml_includedfiles = features.getIncludedFiles(fname);
2934
2935                 ofs << "<!doctype " << top_element
2936                     << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2937
2938                 if (params.preamble.empty() && sgml_includedfiles.empty())
2939                         ofs << ">\n\n";
2940                 else
2941                         ofs << "\n [ " << params.preamble 
2942                             << sgml_includedfiles << " \n]>\n\n";
2943         }
2944
2945         string top = top_element;       
2946         top += " lang=\"";
2947         top += params.language->code();
2948         top += "\"";
2949
2950         if (!params.options.empty()) {
2951                 top += " ";
2952                 top += params.options;
2953         }
2954         sgmlOpenTag(ofs, 0, top);
2955
2956         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
2957             << "\n  See http://www.lyx.org/ for more information -->\n";
2958
2959         vector<string> environment_stack(10);
2960         vector<string> environment_inner(10);
2961         vector<string> command_stack(10);
2962
2963         bool command_flag = false;
2964         Paragraph::depth_type command_depth = 0;
2965         Paragraph::depth_type command_base = 0;
2966         Paragraph::depth_type cmd_depth = 0;
2967         Paragraph::depth_type depth = 0; // paragraph depth
2968
2969         string item_name;
2970         string command_name;
2971
2972         while (par) {
2973                 string sgmlparam;
2974                 string c_depth;
2975                 string c_params;
2976                 int desc_on = 0; // description mode
2977
2978                 LyXLayout const & style =
2979                         textclasslist.Style(params.textclass,
2980                                             par->layout);
2981
2982                 // environment tag closing
2983                 for (; depth > par->params().depth(); --depth) {
2984                         if (environment_inner[depth] != "!-- --") {
2985                                 item_name = "listitem";
2986                                 sgmlCloseTag(ofs, command_depth + depth,
2987                                              item_name);
2988                                 if (environment_inner[depth] == "varlistentry")
2989                                         sgmlCloseTag(ofs, depth+command_depth,
2990                                                      environment_inner[depth]);
2991                         }
2992                         sgmlCloseTag(ofs, depth + command_depth,
2993                                      environment_stack[depth]);
2994                         environment_stack[depth].erase();
2995                         environment_inner[depth].erase();
2996                 }
2997
2998                 if (depth == par->params().depth()
2999                    && environment_stack[depth] != style.latexname()
3000                    && !environment_stack[depth].empty()) {
3001                         if (environment_inner[depth] != "!-- --") {
3002                                 item_name= "listitem";
3003                                 sgmlCloseTag(ofs, command_depth+depth,
3004                                              item_name);
3005                                 if (environment_inner[depth] == "varlistentry")
3006                                         sgmlCloseTag(ofs,
3007                                                      depth + command_depth,
3008                                                      environment_inner[depth]);
3009                         }
3010                         
3011                         sgmlCloseTag(ofs, depth + command_depth,
3012                                      environment_stack[depth]);
3013                         
3014                         environment_stack[depth].erase();
3015                         environment_inner[depth].erase();
3016                 }
3017
3018                 // Write opening SGML tags.
3019                 switch (style.latextype) {
3020                 case LATEX_PARAGRAPH:
3021                         sgmlOpenTag(ofs, depth + command_depth,
3022                                     style.latexname());
3023                         break;
3024
3025                 case LATEX_COMMAND:
3026                         if (depth != 0)
3027                                 linuxDocError(par, 0,
3028                                               _("Error : Wrong depth for "
3029                                                 "LatexType Command.\n"));
3030                         
3031                         command_name = style.latexname();
3032                         
3033                         sgmlparam = style.latexparam();
3034                         c_params = split(sgmlparam, c_depth,'|');
3035                         
3036                         cmd_depth = lyx::atoi(c_depth);
3037                         
3038                         if (command_flag) {
3039                                 if (cmd_depth < command_base) {
3040                                         for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3041                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3042                                         command_depth = command_base = cmd_depth;
3043                                 } else if (cmd_depth <= command_depth) {
3044                                         for (int j = command_depth; j >= int(cmd_depth); --j)
3045                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3046                                         command_depth = cmd_depth;
3047                                 } else
3048                                         command_depth = cmd_depth;
3049                         } else {
3050                                 command_depth = command_base = cmd_depth;
3051                                 command_flag = true;
3052                         }
3053                         if (command_stack.size() == command_depth + 1)
3054                                 command_stack.push_back(string());
3055                         command_stack[command_depth] = command_name;
3056
3057                         // treat label as a special case for
3058                         // more WYSIWYM handling.
3059                         if (par->getChar(0) == Paragraph::META_INSET) {
3060                                 Inset * inset = par->getInset(0);
3061                                 Inset::Code lyx_code = inset->lyxCode();
3062                                 if (lyx_code == Inset::LABEL_CODE){
3063                                         command_name += " id=\"";
3064                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3065                                         command_name += "\"";
3066                                         desc_on = 3;
3067                                 }
3068                         }
3069
3070                         sgmlOpenTag(ofs, depth + command_depth, command_name);
3071                         if (c_params.empty())
3072                                 item_name = "title";
3073                         else
3074                                 item_name = c_params;
3075                         sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3076                         break;
3077
3078                 case LATEX_ENVIRONMENT:
3079                 case LATEX_ITEM_ENVIRONMENT:
3080                         if (depth < par->params().depth()) {
3081                                 depth = par->params().depth();
3082                                 environment_stack[depth].erase();
3083                         }
3084
3085                         if (environment_stack[depth] != style.latexname()) {
3086                                 if(environment_stack.size() == depth + 1) {
3087                                         environment_stack.push_back("!-- --");
3088                                         environment_inner.push_back("!-- --");
3089                                 }
3090                                 environment_stack[depth] = style.latexname();
3091                                 environment_inner[depth] = "!-- --";
3092                                 sgmlOpenTag(ofs, depth + command_depth,
3093                                             environment_stack[depth]);
3094                         } else {
3095                                 if (environment_inner[depth] != "!-- --") {
3096                                         item_name= "listitem";
3097                                         sgmlCloseTag(ofs,
3098                                                      command_depth + depth,
3099                                                      item_name);
3100                                         if (environment_inner[depth] == "varlistentry")
3101                                                 sgmlCloseTag(ofs,
3102                                                              depth + command_depth,
3103                                                              environment_inner[depth]);
3104                                 }
3105                         }
3106                         
3107                         if (style.latextype == LATEX_ENVIRONMENT) {
3108                                 if (!style.latexparam().empty()) {
3109                                         if(style.latexparam() == "CDATA")
3110                                                 ofs << "<![CDATA[";
3111                                         else
3112                                                 sgmlOpenTag(ofs, depth + command_depth,
3113                                                             style.latexparam());
3114                                 }
3115                                 break;
3116                         }
3117
3118                         desc_on = (style.labeltype == LABEL_MANUAL);
3119
3120                         if (desc_on)
3121                                 environment_inner[depth]= "varlistentry";
3122                         else
3123                                 environment_inner[depth]= "listitem";
3124
3125                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3126                                     environment_inner[depth]);
3127
3128                         if (desc_on) {
3129                                 item_name= "term";
3130                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3131                                             item_name);
3132                         } else {
3133                                 item_name= "para";
3134                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3135                                             item_name);
3136                         }
3137                         break;
3138                 default:
3139                         sgmlOpenTag(ofs, depth + command_depth,
3140                                     style.latexname());
3141                         break;
3142                 }
3143
3144                 string extra_par;
3145                 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3146                                     depth + 1 + command_depth);
3147                 par = par->next();
3148
3149                 string end_tag;
3150                 // write closing SGML tags
3151                 switch (style.latextype) {
3152                 case LATEX_COMMAND:
3153                         if (c_params.empty())
3154                                 end_tag = "title";
3155                         else
3156                                 end_tag = c_params;
3157                         sgmlCloseTag(ofs, depth + command_depth, end_tag);
3158                         break;
3159                 case LATEX_ENVIRONMENT:
3160                         if (!style.latexparam().empty()) {
3161                                 if(style.latexparam() == "CDATA")
3162                                         ofs << "]]>";
3163                                 else
3164                                         sgmlCloseTag(ofs, depth + command_depth,
3165                                                      style.latexparam());
3166                         }
3167                         break;
3168                 case LATEX_ITEM_ENVIRONMENT:
3169                         if (desc_on == 1) break;
3170                         end_tag= "para";
3171                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3172                         break;
3173                 case LATEX_PARAGRAPH:
3174                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3175                         break;
3176                 default:
3177                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3178                         break;
3179                 }
3180         }
3181
3182         // Close open tags
3183         for (int d = depth; d >= 0; --d) {
3184                 if (!environment_stack[depth].empty()) {
3185                         if (environment_inner[depth] != "!-- --") {
3186                                 item_name = "listitem";
3187                                 sgmlCloseTag(ofs, command_depth + depth,
3188                                              item_name);
3189                                if (environment_inner[depth] == "varlistentry")
3190                                        sgmlCloseTag(ofs, depth + command_depth,
3191                                                     environment_inner[depth]);
3192                         }
3193                         
3194                         sgmlCloseTag(ofs, depth + command_depth,
3195                                      environment_stack[depth]);
3196                 }
3197         }
3198         
3199         for (int j = command_depth; j >= 0 ; --j)
3200                 if (!command_stack[j].empty())
3201                         sgmlCloseTag(ofs, j, command_stack[j]);
3202
3203         ofs << "\n\n";
3204         sgmlCloseTag(ofs, 0, top_element);
3205
3206         ofs.close();
3207         // How to check for successful close
3208 }
3209
3210
3211 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3212                                  Paragraph * par, int & desc_on,
3213                                  Paragraph::depth_type depth) const
3214 {
3215         bool emph_flag = false;
3216
3217         LyXLayout const & style = textclasslist.Style(params.textclass,
3218                                                       par->getLayout());
3219
3220         LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3221
3222         int char_line_count = depth;
3223         //if (!style.free_spacing)
3224         //      os << string(depth,' ');
3225
3226         // parsing main loop
3227         for (Paragraph::size_type i = 0;
3228              i < par->size(); ++i) {
3229                 LyXFont font = par->getFont(params, i);
3230
3231                 // handle <emphasis> tag
3232                 if (font_old.emph() != font.emph()) {
3233                         if (font.emph() == LyXFont::ON) {
3234                                 os << "<emphasis>";
3235                                 emph_flag = true;
3236                         }else if(i) {
3237                                 os << "</emphasis>";
3238                                 emph_flag = false;
3239                         }
3240                 }
3241       
3242                 char c = par->getChar(i);
3243
3244                 if (c == Paragraph::META_INSET) {
3245                         Inset * inset = par->getInset(i);
3246                         ostringstream ost;
3247                         inset->docBook(this, ost);
3248                         string tmp_out = ost.str().c_str();
3249
3250                         //
3251                         // This code needs some explanation:
3252                         // Two insets are treated specially
3253                         //   label if it is the first element in a command paragraph
3254                         //         desc_on == 3
3255                         //   graphics inside tables or figure floats can't go on
3256                         //   title (the equivalente in latex for this case is caption
3257                         //   and title should come first
3258                         //         desc_on == 4
3259                         //
3260                         if (desc_on!= 3 || i!= 0) {
3261                                 if (!tmp_out.empty() && tmp_out[0] == '@') {
3262                                         if (desc_on == 4)
3263                                                 extra += frontStrip(tmp_out, '@');
3264                                         else
3265                                                 os << frontStrip(tmp_out, '@');
3266                                 }
3267                                 else
3268                                         os << tmp_out;
3269                         }
3270 #ifndef NO_LATEX
3271                 } else if (font.latex() == LyXFont::ON) {
3272                         // "TeX"-Mode on ==> SGML-Mode on.
3273                         if (c != '\0')
3274                                 os << c;
3275                         ++char_line_count;
3276 #endif
3277                 } else {
3278                         string sgml_string;
3279                         if (par->linuxDocConvertChar(c, sgml_string)
3280                             && !style.free_spacing) { // in freespacing
3281                                                      // mode, spaces are
3282                                                      // non-breaking characters
3283                                 // char is ' '
3284                                 if (desc_on == 1) {
3285                                         ++char_line_count;
3286                                         os << "\n</term><listitem><para>";
3287                                         desc_on = 2;
3288                                 } else {
3289                                         os << c;
3290                                 }
3291                         } else {
3292                                 os << sgml_string;
3293                         }
3294                 }
3295                 font_old = font;
3296         }
3297
3298         if (emph_flag) {
3299                 os << "</emphasis>";
3300         }
3301         
3302         // resets description flag correctly
3303         if (desc_on == 1) {
3304                 // <term> not closed...
3305                 os << "</term>";
3306         }
3307         if(style.free_spacing) os << '\n';
3308 }
3309
3310
3311 // This should be enabled when the Chktex class is implemented. (Asger)
3312 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3313 // Other flags: -wall -v0 -x
3314 int Buffer::runChktex()
3315 {
3316         if (!users->text) return 0;
3317
3318         users->owner()->prohibitInput();
3319
3320         // get LaTeX-Filename
3321         string const name = getLatexName();
3322         string path = OnlyPath(filename);
3323
3324         string const org_path = path;
3325         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3326                 path = tmppath;  
3327         }
3328
3329         Path p(path); // path to LaTeX file
3330         users->owner()->message(_("Running chktex..."));
3331
3332         // Remove all error insets
3333         bool const removedErrorInsets = users->removeAutoInsets();
3334
3335         // Generate the LaTeX file if neccessary
3336         makeLaTeXFile(name, org_path, false);
3337
3338         TeXErrors terr;
3339         Chktex chktex(lyxrc.chktex_command, name, filepath);
3340         int res = chktex.run(terr); // run chktex
3341
3342         if (res == -1) {
3343                 WriteAlert(_("chktex did not work!"),
3344                            _("Could not run with file:"), name);
3345         } else if (res > 0) {
3346                 // Insert all errors as errors boxes
3347                 users->insertErrors(terr);
3348         }
3349
3350         // if we removed error insets before we ran chktex or if we inserted
3351         // error insets after we ran chktex, this must be run:
3352         if (removedErrorInsets || res){
3353                 users->redraw();
3354                 users->fitCursor(users->text);
3355         }
3356         users->owner()->allowInput();
3357
3358         return res;
3359 }
3360
3361
3362 void Buffer::validate(LaTeXFeatures & features) const
3363 {
3364         Paragraph * par = paragraph;
3365         LyXTextClass const & tclass = 
3366                 textclasslist.TextClass(params.textclass);
3367     
3368         // AMS Style is at document level
3369     
3370         features.amsstyle = (params.use_amsmath ||
3371                              tclass.provides(LyXTextClass::amsmath));
3372     
3373         while (par) {
3374                 // We don't use "lyxerr.debug" because of speed. (Asger)
3375                 if (lyxerr.debugging(Debug::LATEX))
3376                         lyxerr << "Paragraph: " <<  par << endl;
3377
3378                 // Now just follow the list of paragraphs and run
3379                 // validate on each of them.
3380                 par->validate(features);
3381
3382                 // and then the next paragraph
3383                 par = par->next();
3384         }
3385
3386         // the bullet shapes are buffer level not paragraph level
3387         // so they are tested here
3388         for (int i = 0; i < 4; ++i) {
3389                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3390                         int const font = params.user_defined_bullets[i].getFont();
3391                         if (font == 0) {
3392                                 int const c = params
3393                                         .user_defined_bullets[i]
3394                                         .getCharacter();
3395                                 if (c == 16
3396                                    || c == 17
3397                                    || c == 25
3398                                    || c == 26
3399                                    || c == 31) {
3400                                         features.latexsym = true;
3401                                 }
3402                         } else if (font == 1) {
3403                                 features.amssymb = true;
3404                         } else if ((font >= 2 && font <= 5)) {
3405                                 features.pifont = true;
3406                         }
3407                 }
3408         }
3409         
3410         if (lyxerr.debugging(Debug::LATEX)) {
3411                 features.showStruct();
3412         }
3413 }
3414
3415
3416 void Buffer::setPaperStuff()
3417 {
3418         params.papersize = BufferParams::PAPER_DEFAULT;
3419         char const c1 = params.paperpackage;
3420         if (c1 == BufferParams::PACKAGE_NONE) {
3421                 char const c2 = params.papersize2;
3422                 if (c2 == BufferParams::VM_PAPER_USLETTER)
3423                         params.papersize = BufferParams::PAPER_USLETTER;
3424                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3425                         params.papersize = BufferParams::PAPER_LEGALPAPER;
3426                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3427                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3428                 else if (c2 == BufferParams::VM_PAPER_A3)
3429                         params.papersize = BufferParams::PAPER_A3PAPER;
3430                 else if (c2 == BufferParams::VM_PAPER_A4)
3431                         params.papersize = BufferParams::PAPER_A4PAPER;
3432                 else if (c2 == BufferParams::VM_PAPER_A5)
3433                         params.papersize = BufferParams::PAPER_A5PAPER;
3434                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3435                          (c2 == BufferParams::VM_PAPER_B5))
3436                         params.papersize = BufferParams::PAPER_B5PAPER;
3437         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3438                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3439                 params.papersize = BufferParams::PAPER_A4PAPER;
3440 }
3441
3442
3443 // This function should be in Buffer because it's a buffer's property (ale)
3444 string const Buffer::getIncludeonlyList(char delim)
3445 {
3446         string lst;
3447         for (inset_iterator it = inset_iterator_begin();
3448             it != inset_iterator_end(); ++it) {
3449                 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3450                         InsetInclude * insetinc = 
3451                                 static_cast<InsetInclude *>(*it);
3452                         if (insetinc->isIncludeOnly()) {
3453                                 if (!lst.empty())
3454                                         lst += delim;
3455                                 lst += insetinc->getRelFileBaseName();
3456                         }
3457                 }
3458         }
3459         lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3460         return lst;
3461 }
3462
3463
3464 vector<string> const Buffer::getLabelList()
3465 {
3466         /// if this is a child document and the parent is already loaded
3467         /// Use the parent's list instead  [ale990407]
3468         if (!params.parentname.empty()
3469             && bufferlist.exists(params.parentname)) {
3470                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3471                 if (tmp)
3472                         return tmp->getLabelList();
3473         }
3474
3475         vector<string> label_list;
3476         for (inset_iterator it = inset_iterator_begin();
3477              it != inset_iterator_end(); ++it) {
3478                 vector<string> const l = (*it)->getLabelList();
3479                 label_list.insert(label_list.end(), l.begin(), l.end());
3480         }
3481         return label_list;
3482 }
3483
3484
3485 Buffer::Lists const Buffer::getLists() const
3486 {
3487         Lists l;
3488         Paragraph * par = paragraph;
3489         bool found;
3490         LyXTextClassList::size_type cap;
3491         boost::tie(found, cap) = textclasslist
3492                 .NumberOfLayout(params.textclass, "Caption");
3493
3494         while (par) {
3495                 char const labeltype =
3496                         textclasslist.Style(params.textclass, 
3497                                             par->getLayout()).labeltype;
3498                 
3499                 if (labeltype >= LABEL_COUNTER_CHAPTER
3500                     && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3501                                 // insert this into the table of contents
3502                         SingleList & item = l["TOC"];
3503                         int depth = max(0,
3504                                         labeltype - 
3505                                         textclasslist.TextClass(params.textclass).maxcounter());
3506                         item.push_back(TocItem(par, depth, par->asString(this, true)));
3507                 }
3508                 // For each paragrph, traverse its insets and look for
3509                 // FLOAT_CODE
3510                 
3511                 if (found) {
3512                         Paragraph::inset_iterator it =
3513                                 par->inset_iterator_begin();
3514                         Paragraph::inset_iterator end =
3515                                 par->inset_iterator_end();
3516                         
3517                         for (; it != end; ++it) {
3518                                 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3519                                         InsetFloat * il =
3520                                                 static_cast<InsetFloat*>(*it);
3521                                         
3522                                         string const type = il->type();
3523                                         
3524                                         // Now find the caption in the float...
3525                                         // We now tranverse the paragraphs of
3526                                         // the inset...
3527                                         Paragraph * tmp = il->inset.paragraph();
3528                                         while (tmp) {
3529                                                 if (tmp->layout == cap) {
3530                                                         SingleList & item = l[type];
3531                                                         string const str =
3532                                                                 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3533                                                         item.push_back(TocItem(tmp, 0 , str));
3534                                                 }
3535                                                 tmp = tmp->next();
3536                                         }
3537                                 }
3538                         }
3539                 } else {
3540                         lyxerr << "caption not found" << endl;
3541                 }
3542                 
3543                 par = par->next();
3544         }
3545         return l;
3546 }
3547
3548
3549 // This is also a buffer property (ale)
3550 vector<pair<string, string> > const Buffer::getBibkeyList()
3551 {
3552         /// if this is a child document and the parent is already loaded
3553         /// Use the parent's list instead  [ale990412]
3554         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3555                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3556                 if (tmp)
3557                         return tmp->getBibkeyList();
3558         }
3559
3560         vector<pair<string, string> > keys;
3561         Paragraph * par = paragraph;
3562         while (par) {
3563                 if (par->bibkey)
3564                         keys.push_back(pair<string, string>(par->bibkey->getContents(),
3565                                                            par->asString(this, false)));
3566                 par = par->next();
3567         }
3568
3569         // Might be either using bibtex or a child has bibliography
3570         if (keys.empty()) {
3571                 for (inset_iterator it = inset_iterator_begin();
3572                         it != inset_iterator_end(); ++it) {
3573                         // Search for Bibtex or Include inset
3574                         if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3575                                 vector<pair<string,string> > tmp =
3576                                         static_cast<InsetBibtex*>(*it)->getKeys(this);
3577                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3578                         } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3579                                 vector<pair<string,string> > const tmp =
3580                                         static_cast<InsetInclude*>(*it)->getKeys();
3581                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3582                         }
3583                 }
3584         }
3585  
3586         return keys;
3587 }
3588
3589
3590 bool Buffer::isDepClean(string const & name) const
3591 {
3592         DEPCLEAN * item = dep_clean;
3593         while (item && item->master != name)
3594                 item = item->next;
3595         if (!item) return true;
3596         return item->clean;
3597 }
3598
3599
3600 void Buffer::markDepClean(string const & name)
3601 {
3602         if (!dep_clean) {
3603                 dep_clean = new DEPCLEAN;
3604                 dep_clean->clean = true;
3605                 dep_clean->master = name;
3606                 dep_clean->next = 0;
3607         } else {
3608                 DEPCLEAN * item = dep_clean;
3609                 while (item && item->master != name)
3610                         item = item->next;
3611                 if (item) {
3612                         item->clean = true;
3613                 } else {
3614                         item = new DEPCLEAN;
3615                         item->clean = true;
3616                         item->master = name;
3617                         item->next = 0;
3618                 }
3619         }
3620 }
3621
3622
3623 bool Buffer::dispatch(string const & command)
3624 {
3625         // Split command string into command and argument
3626         string cmd;
3627         string line = frontStrip(command);
3628         string const arg = strip(frontStrip(split(line, cmd, ' ')));
3629
3630         return dispatch(lyxaction.LookupFunc(cmd), arg);
3631 }
3632
3633
3634 bool Buffer::dispatch(int action, string const & argument)
3635 {
3636         bool dispatched = true;
3637         switch (action) {
3638                 case LFUN_EXPORT: 
3639                         Exporter::Export(this, argument, false);
3640                         break;
3641
3642                 default:
3643                         dispatched = false;
3644         }
3645         return dispatched;
3646 }
3647
3648
3649 void Buffer::resizeInsets(BufferView * bv)
3650 {
3651         /// then remove all LyXText in text-insets
3652         Paragraph * par = paragraph;
3653         for (; par; par = par->next()) {
3654             par->resizeInsetsLyXText(bv);
3655         }
3656 }
3657
3658
3659 void Buffer::redraw()
3660 {
3661         users->redraw(); 
3662         users->fitCursor(users->text); 
3663 }
3664
3665
3666 void Buffer::changeLanguage(Language const * from, Language const * to)
3667 {
3668
3669         Paragraph * par = paragraph;
3670         while (par) {
3671                 par->changeLanguage(params, from, to);
3672                 par = par->next();
3673         }
3674 }
3675
3676
3677 bool Buffer::isMultiLingual()
3678 {
3679         Paragraph * par = paragraph;
3680         while (par) {
3681                 if (par->isMultiLingual(params))
3682                         return true;
3683                 par = par->next();
3684         }
3685         return false;
3686 }
3687
3688
3689 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3690                                        Paragraph::size_type pos)
3691         : par(paragraph)
3692 {
3693         it = par->InsetIterator(pos);
3694         if (it == par->inset_iterator_end()) {
3695                 par = par->next();
3696                 setParagraph();
3697         }
3698 }
3699
3700
3701 void Buffer::inset_iterator::setParagraph()
3702 {
3703         while (par) {
3704                 it = par->inset_iterator_begin();
3705                 if (it != par->inset_iterator_end())
3706                         return;
3707                 par = par->next();
3708         }
3709         //it = 0;
3710         // We maintain an invariant that whenever par = 0 then it = 0
3711 }
3712
3713
3714 Inset * Buffer::getInsetFromID(int id_arg) const
3715 {
3716         for (inset_iterator it = inset_const_iterator_begin();
3717                  it != inset_const_iterator_end(); ++it)
3718         {
3719                 if ((*it)->id() == id_arg)
3720                         return *it;
3721                 Inset * in = (*it)->getInsetFromID(id_arg);
3722                 if (in)
3723                         return in;
3724         }
3725         return 0;
3726 }
3727
3728
3729 Paragraph * Buffer::getParFromID(int id) const
3730 {
3731         if (id < 0) return 0;
3732         Paragraph * par = paragraph;
3733         while (par) {
3734                 if (par->id() == id) {
3735                         return par;
3736                 }
3737                 Paragraph * tmp = par->getParFromID(id);
3738                 if (tmp) {
3739                         return tmp;
3740                 }
3741                 par = par->next();
3742         }
3743         return 0;
3744 }