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