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