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