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