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