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