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