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