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