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