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