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