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