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