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