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