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