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