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