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