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