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