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