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