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