]> git.lyx.org Git - features.git/blob - src/buffer.C
3eb78ad986cde7987ae2fa93924c9f0a093aca05
[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 #ifdef USE_OSTREAM_ONLY
1529 void Buffer::makeLaTeXFile(string const & fname, 
1530                            string const & original_path,
1531                            bool nice, bool only_body)
1532 {
1533         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1534         
1535         niceFile = nice; // this will be used by Insetincludes.
1536
1537         tex_code_break_column = lyxrc->ascii_linelen;
1538
1539         LyXTextClass const & tclass =
1540                 textclasslist.TextClass(params.textclass);
1541
1542         ofstream ofs(fname.c_str());
1543         if (!ofs) {
1544                 WriteFSAlert(_("Error: Cannot open file: "), fname);
1545                 return;
1546         }
1547         
1548         // validate the buffer.
1549         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1550         LaTeXFeatures features(tclass.numLayouts());
1551         validate(features);
1552         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1553         
1554         texrow.reset();
1555         // The starting paragraph of the coming rows is the 
1556         // first paragraph of the document. (Asger)
1557         texrow.start(paragraph, 0);
1558
1559         if (!only_body && nice) {
1560                 ofs << "%% " LYX_DOCVERSION " created this file.  "
1561                         "For more info, see http://www.lyx.org/.\n"
1562                         "%% Do not edit unless you really know what "
1563                         "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                         ofs << "\\batchmode\n"; // changed
1581                         // from \nonstopmode
1582                         texrow.newline();
1583                 }
1584                 if (!original_path.empty()) {
1585                         ofs << "\\makeatletter\n"
1586                             << "\\def\\input@path{{"
1587                             << original_path << "/}}\n"
1588                             << "\\makeatother\n";
1589                         texrow.newline();
1590                         texrow.newline();
1591                         texrow.newline();
1592                 }
1593                 
1594                 ofs << "\\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                         ofs << '[' << options << ']';
1672                 }
1673                 
1674                 ofs << '{'
1675                     << textclasslist.LatexnameOfClass(params.textclass)
1676                     << "}\n";
1677                 texrow.newline();
1678                 // end of \documentclass defs
1679                 
1680                 // font selection must be done before loading fontenc.sty
1681                 if (params.fonts != "default") {
1682                         ofs << "\\usepackage{" << params.fonts << "}\n";
1683                         texrow.newline();
1684                 }
1685                 // this one is not per buffer
1686                 if (lyxrc->fontenc != "default") {
1687                         ofs << "\\usepackage[" << lyxrc->fontenc
1688                             << "]{fontenc}\n";
1689                         texrow.newline();
1690                 }
1691                 if (params.inputenc != "default") {
1692                         ofs << "\\usepackage[" << params.inputenc
1693                             << "]{inputenc}\n";
1694                         texrow.newline();
1695                 }
1696                 
1697                 /* at the very beginning the text parameters */
1698                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1699                         switch (params.paperpackage) {
1700                         case BufferParams::PACKAGE_A4:
1701                                 ofs << "\\usepackage{a4}\n";
1702                                 texrow.newline();
1703                                 break;
1704                         case BufferParams::PACKAGE_A4WIDE:
1705                                 ofs << "\\usepackage{a4wide}\n";
1706                                 texrow.newline();
1707                                 break;
1708                         case BufferParams::PACKAGE_WIDEMARGINSA4:
1709                                 ofs << "\\usepackage[widemargins]{a4}\n";
1710                                 texrow.newline();
1711                                 break;
1712                         }
1713                 }
1714                 if (params.use_geometry) {
1715                         ofs << "\\usepackage{geometry}\n";
1716                         texrow.newline();
1717                         ofs << "\\geometry{verbose";
1718                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1719                                 ofs << ",landscape";
1720                         switch (params.papersize2) {
1721                         case BufferParams::VM_PAPER_CUSTOM:
1722                                 if (!params.paperwidth.empty())
1723                                         ofs << ",paperwidth="
1724                                             << params.paperwidth;
1725                                 if (!params.paperheight.empty())
1726                                         ofs << ",paperheight="
1727                                             << params.paperheight;
1728                                 break;
1729                         case BufferParams::VM_PAPER_USLETTER:
1730                                 ofs << ",letterpaper";
1731                                 break;
1732                         case BufferParams::VM_PAPER_USLEGAL:
1733                                 ofs << ",legalpaper";
1734                                 break;
1735                         case BufferParams::VM_PAPER_USEXECUTIVE:
1736                                 ofs << ",executivepaper";
1737                                 break;
1738                         case BufferParams::VM_PAPER_A3:
1739                                 ofs << ",a3paper";
1740                                 break;
1741                         case BufferParams::VM_PAPER_A4:
1742                                 ofs << ",a4paper";
1743                                 break;
1744                         case BufferParams::VM_PAPER_A5:
1745                                 ofs << ",a5paper";
1746                                 break;
1747                         case BufferParams::VM_PAPER_B3:
1748                                 ofs << ",b3paper";
1749                                 break;
1750                         case BufferParams::VM_PAPER_B4:
1751                                 ofs << ",b4paper";
1752                                 break;
1753                         case BufferParams::VM_PAPER_B5:
1754                                 ofs << ",b5paper";
1755                                 break;
1756                         default:
1757                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1758                                 switch (lyxrc->default_papersize) {
1759                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1760                                 case BufferParams::PAPER_USLETTER:
1761                                         ofs << ",letterpaper";
1762                                         break;
1763                                 case BufferParams::PAPER_LEGALPAPER:
1764                                         ofs << ",legalpaper";
1765                                         break;
1766                                 case BufferParams::PAPER_EXECUTIVEPAPER:
1767                                         ofs << ",executivepaper";
1768                                         break;
1769                                 case BufferParams::PAPER_A3PAPER:
1770                                         ofs << ",a3paper";
1771                                         break;
1772                                 case BufferParams::PAPER_A4PAPER:
1773                                         ofs << ",a4paper";
1774                                         break;
1775                                 case BufferParams::PAPER_A5PAPER:
1776                                         ofs << ",a5paper";
1777                                         break;
1778                                 case BufferParams::PAPER_B5PAPER:
1779                                         ofs << ",b5paper";
1780                                         break;
1781                                 }
1782                         }
1783                         if (!params.topmargin.empty())
1784                                 ofs << ",tmargin=" << params.topmargin;
1785                         if (!params.bottommargin.empty())
1786                                 ofs << ",bmargin=" << params.bottommargin;
1787                         if (!params.leftmargin.empty())
1788                                 ofs << ",lmargin=" << params.leftmargin;
1789                         if (!params.rightmargin.empty())
1790                                 ofs << ",rmargin=" << params.rightmargin;
1791                         if (!params.headheight.empty())
1792                                 ofs << ",headheight=" << params.headheight;
1793                         if (!params.headsep.empty())
1794                                 ofs << ",headsep=" << params.headsep;
1795                         if (!params.footskip.empty())
1796                                 ofs << ",footskip=" << params.footskip;
1797                         ofs << "}\n";
1798                         texrow.newline();
1799                 }
1800                 if (params.use_amsmath
1801                     && !prefixIs(textclasslist.LatexnameOfClass(params.textclass), "ams")) {
1802                         ofs << "\\usepackage{amsmath}\n";
1803                         texrow.newline();
1804                 }
1805
1806                 if (tokenPos(tclass.opt_pagestyle(), '|', params.pagestyle) >= 0) {
1807                         if (params.pagestyle == "fancy") {
1808                                 ofs << "\\usepackage{fancyhdr}\n";
1809                                 texrow.newline();
1810                         }
1811                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1812                         texrow.newline();
1813                 }
1814
1815                 // We try to load babel late, in case it interferes
1816                 // with other packages.
1817                 if (params.language != "default" || lyxrc->rtl_support ) {
1818                         ofs << "\\usepackage{babel}\n";
1819                         texrow.newline();
1820                 }
1821
1822                 if (params.secnumdepth != tclass.secnumdepth()) {
1823                         ofs << "\\setcounter{secnumdepth}{"
1824                             << params.secnumdepth
1825                             << "}\n";
1826                         texrow.newline();
1827                 }
1828                 if (params.tocdepth != tclass.tocdepth()) {
1829                         ofs << "\\setcounter{tocdepth}{"
1830                             << params.tocdepth
1831                             << "}\n";
1832                         texrow.newline();
1833                 }
1834                 
1835                 if (params.paragraph_separation) {
1836                         switch (params.defskip.kind()) {
1837                         case VSpace::SMALLSKIP: 
1838                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1839                                 break;
1840                         case VSpace::MEDSKIP:
1841                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1842                                 break;
1843                         case VSpace::BIGSKIP:
1844                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1845                                 break;
1846                         case VSpace::LENGTH:
1847                                 ofs << "\\setlength\\parskip{"
1848                                     << params.defskip.length().asLatexString()
1849                                     << "}\n";
1850                                 break;
1851                         default: // should never happen // Then delete it.
1852                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1853                                 break;
1854                         }
1855                         texrow.newline();
1856                         
1857                         ofs << "\\setlength\\parindent{0pt}\n";
1858                         texrow.newline();
1859                 }
1860
1861                 // Now insert the LyX specific LaTeX commands...
1862                 string preamble, tmppreamble;
1863
1864                 // The optional packages;
1865                 preamble = features.getPackages(params);
1866
1867                 // this might be useful...
1868                 preamble += "\n\\makeatletter\n\n";
1869
1870                 // Some macros LyX will need
1871                 tmppreamble = features.getMacros(params);
1872
1873                 if (!tmppreamble.empty()) {
1874                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1875                                 "LyX specific LaTeX commands.\n"
1876                                 + tmppreamble + '\n';
1877                 }
1878
1879                 // the text class specific preamble 
1880                 tmppreamble = features.getTClassPreamble(params);
1881                 if (!tmppreamble.empty()) {
1882                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1883                                 "Textclass specific LaTeX commands.\n"
1884                                 + tmppreamble + '\n';
1885                 }
1886
1887                 /* the user-defined preamble */
1888                 if (!params.preamble.empty()) {
1889                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1890                                 "User specified LaTeX commands.\n"
1891                                 + params.preamble + '\n';
1892                 }
1893
1894                 preamble += "\\makeatother\n\n";
1895
1896                 // Itemize bullet settings need to be last in case the user
1897                 // defines their own bullets that use a package included
1898                 // in the user-defined preamble -- ARRae
1899                 // Actually it has to be done much later than that
1900                 // since some packages like frenchb make modifications
1901                 // at \begin{document} time -- JMarc 
1902                 string bullets_def;
1903                 for (int i = 0; i < 4; ++i) {
1904                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1905                                 if (bullets_def.empty())
1906                                         bullets_def="\\AtBeginDocument{\n";
1907                                 bullets_def += "  \\renewcommand{\\labelitemi";
1908                                 switch (i) {
1909                                 // `i' is one less than the item to modify
1910                                 case 0:
1911                                         break;
1912                                 case 1:
1913                                         bullets_def += 'i';
1914                                         break;
1915                                 case 2:
1916                                         bullets_def += "ii";
1917                                         break;
1918                                 case 3:
1919                                         bullets_def += 'v';
1920                                         break;
1921                                 }
1922                                 bullets_def += "}{" + 
1923                                   params.user_defined_bullets[i].getText() 
1924                                   + "}\n";
1925                         }
1926                 }
1927
1928                 if (!bullets_def.empty())
1929                   preamble += bullets_def + "}\n\n";
1930
1931                 for (int j = countChar(preamble, '\n'); j-- ;) {
1932                         texrow.newline();
1933                 }
1934
1935                 ofs << preamble;
1936
1937                 // make the body.
1938                 ofs << "\\begin{document}\n\n";
1939                 texrow.newline();
1940                 texrow.newline();
1941         } // only_body
1942         lyxerr.debug() << "preamble finished, now the body." << endl;
1943         
1944         bool was_title = false;
1945         bool already_title = false;
1946 #ifdef HAVE_SSTREAM
1947         ostringstream ftnote;
1948 #else
1949         char * tmpholder = 0;
1950 #endif
1951         TexRow ft_texrow;
1952         int ftcount = 0;
1953
1954         LyXParagraph * par = paragraph;
1955
1956         // if only_body
1957         while (par) {
1958 #ifndef HAVE_SSTREAM
1959                 ostrstream ftnote;
1960                 if (tmpholder) {
1961                         ftnote << tmpholder;
1962                         delete [] tmpholder;
1963                         tmpholder = 0;
1964                 }
1965 #endif
1966                 if (par->IsDummy())
1967                         lyxerr[Debug::LATEX] << "Error in MakeLateXFile."
1968                                              << endl;
1969                 LyXLayout const & layout =
1970                         textclasslist.Style(params.textclass,
1971                                             par->layout);
1972             
1973                 if (layout.intitle) {
1974                         if (already_title) {
1975                                 lyxerr <<"Error in MakeLatexFile: You"
1976                                         " should not mix title layouts"
1977                                         " with normal ones." << endl;
1978                         } else
1979                                 was_title = true;
1980                 } else if (was_title && !already_title) {
1981                         ofs << "\\maketitle\n";
1982                         texrow.newline();
1983                         already_title = true;
1984                         was_title = false;                  
1985                 }
1986                 // We are at depth 0 so we can just use
1987                 // ordinary \footnote{} generation
1988                 // flag this with ftcount
1989                 ftcount = -1;
1990                 if (layout.isEnvironment()
1991                     || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
1992                         par = par->TeXEnvironment(ofs, texrow,
1993                                                   ftnote, ft_texrow, ftcount);
1994                 } else {
1995                         par = par->TeXOnePar(ofs, texrow,
1996                                              ftnote, ft_texrow, ftcount);
1997                 }
1998
1999                 // Write out what we've generated...
2000                 if (ftcount >= 1) {
2001                         if (ftcount > 1) {
2002                                 ofs << "\\addtocounter{footnote}{-"
2003                                     << ftcount - 1
2004                                     << '}';
2005                         }
2006                         ofs << ftnote.str();
2007                         texrow += ft_texrow;
2008 #ifdef HAVE_SSTREAM
2009                         ftnote.str(string());
2010 #else
2011                         delete [] ftnote.str();
2012 #endif
2013                         ft_texrow.reset();
2014                         ftcount = 0;
2015                 }
2016 #ifndef HAVE_SSTREAM
2017                 else {
2018                         // I hate strstreams
2019                         tmpholder = ftnote.str();
2020                 }
2021 #endif
2022         }
2023 #ifndef HAVE_SSTREAM
2024         delete [] tmpholder;
2025 #endif
2026         // It might be that we only have a title in this document
2027         if (was_title && !already_title) {
2028                 ofs << "\\maketitle\n";
2029                 texrow.newline();
2030         }
2031
2032         if (!only_body) {
2033                 ofs << "\\end{document}\n";
2034                 texrow.newline();
2035         
2036                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2037         } else {
2038                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2039                                      << endl;
2040         }
2041
2042         // Just to be sure. (Asger)
2043         texrow.newline();
2044
2045         // tex_code_break_column's value is used to decide
2046         // if we are in batchmode or not (within mathed_write()
2047         // in math_write.C) so we must set it to a non-zero
2048         // value when we leave otherwise we save incorrect .lyx files.
2049         tex_code_break_column = lyxrc->ascii_linelen;
2050
2051         ofs.close();
2052         if (ofs.fail()) {
2053                 lyxerr << "File was not closed properly." << endl;
2054         }
2055         
2056         lyxerr.debug() << "Finished making latex file." << endl;
2057 }
2058 #else
2059 void Buffer::makeLaTeXFile(string const & fname, 
2060                            string const & original_path,
2061                            bool nice, bool only_body)
2062 {
2063         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2064         
2065         niceFile = nice; // this will be used by Insetincludes.
2066
2067         tex_code_break_column = lyxrc->ascii_linelen;
2068
2069         LyXTextClass const & tclass =
2070                 textclasslist.TextClass(params.textclass);
2071
2072         ofstream ofs(fname.c_str());
2073         if (!ofs) {
2074                 WriteFSAlert(_("Error: Cannot open file: "), fname);
2075                 return;
2076         }
2077         
2078         // validate the buffer.
2079         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
2080         LaTeXFeatures features(tclass.numLayouts());
2081         validate(features);
2082         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
2083         
2084         texrow.reset();
2085         // The starting paragraph of the coming rows is the 
2086         // first paragraph of the document. (Asger)
2087         texrow.start(paragraph, 0);
2088
2089         string LFile;
2090         
2091         if (!only_body && nice) {
2092                 LFile += "%% " LYX_DOCVERSION " created this file.  "
2093                          "For more info, see http://www.lyx.org/.\n";
2094                 LFile += "%% Do not edit unless you really know what you are doing.\n";
2095                 texrow.newline();
2096                 texrow.newline();
2097         }
2098         lyxerr.debug() << "lyx header finished" << endl;
2099         // There are a few differences between nice LaTeX and usual files:
2100         // usual is \batchmode and has a 
2101         // special input@path to allow the including of figures
2102         // with either \input or \includegraphics (what figinsets do).
2103         // batchmode is not set if there is a tex_code_break_column.
2104         // In this case somebody is interested in the generated LaTeX,
2105         // so this is OK. input@path is set when the actual parameter
2106         // original_path is set. This is done for usual tex-file, but not
2107         // for nice-latex-file. (Matthias 250696)
2108         if (!only_body) {
2109                 if (!nice){
2110                         // code for usual, NOT nice-latex-file
2111                         LFile += "\\batchmode\n"; // changed
2112                         // from \nonstopmode
2113                         texrow.newline();
2114                 }
2115                 if (!original_path.empty()) {
2116                         LFile += "\\makeatletter\n";
2117                         texrow.newline();
2118                         LFile += "\\def\\input@path{{" + original_path
2119                                  + "/}}\n";
2120                         texrow.newline();
2121                         LFile += "\\makeatother\n";
2122                         texrow.newline();
2123                 }
2124                 
2125                 LFile += "\\documentclass";
2126                 
2127                 string options; // the document class options.
2128                 
2129                 if (tokenPos(tclass.opt_fontsize(), '|', params.fontsize) >= 0) {
2130                         // only write if existing in list (and not default)
2131                         options += params.fontsize;
2132                         options += "pt,";
2133                 }
2134                 
2135                 
2136                 if (!params.use_geometry &&
2137                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2138                         switch (params.papersize) {
2139                         case BufferParams::PAPER_A4PAPER:
2140                                 options += "a4paper,";
2141                                 break;
2142                         case BufferParams::PAPER_USLETTER:
2143                                 options += "letterpaper,";
2144                                 break;
2145                         case BufferParams::PAPER_A5PAPER:
2146                                 options += "a5paper,";
2147                                 break;
2148                         case BufferParams::PAPER_B5PAPER:
2149                                 options += "b5paper,";
2150                                 break;
2151                         case BufferParams::PAPER_EXECUTIVEPAPER:
2152                                 options += "executivepaper,";
2153                                 break;
2154                         case BufferParams::PAPER_LEGALPAPER:
2155                                 options += "legalpaper,";
2156                                 break;
2157                         }
2158                 }
2159
2160                 // if needed
2161                 if (params.sides != tclass.sides()) {
2162                         switch (params.sides) {
2163                         case LyXTextClass::OneSide:
2164                                 options += "oneside,";
2165                                 break;
2166                         case LyXTextClass::TwoSides:
2167                                 options += "twoside,";
2168                                 break;
2169                         }
2170
2171                 }
2172
2173                 // if needed
2174                 if (params.columns != tclass.columns()) {
2175                         if (params.columns == 2)
2176                                 options += "twocolumn,";
2177                         else
2178                                 options += "onecolumn,";
2179                 }
2180
2181                 if (!params.use_geometry 
2182                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2183                         options += "landscape,";
2184                 
2185                 // language should be a parameter to \documentclass             
2186                 if (params.language != "default") {
2187                         if (params.language == "hebrew")
2188                                 options += "english,";
2189                         else if (lyxrc->rtl_support)
2190                                 options += "hebrew,";
2191                         options += params.language + ',';
2192                 } else if (lyxrc->rtl_support)
2193                         options += "hebrew,english,";
2194
2195                 // the user-defined options
2196                 if (!params.options.empty()) {
2197                         options += params.options + ',';
2198                 }
2199                 
2200                 if (!options.empty()){
2201                         options = strip(options, ',');
2202                         LFile += '[';
2203                         LFile += options;
2204                         LFile += ']';
2205                 }
2206                 
2207                 LFile += '{';
2208                 LFile += textclasslist.LatexnameOfClass(params.textclass);
2209                 LFile += "}\n";
2210                 texrow.newline();
2211                 // end of \documentclass defs
2212                 
2213                 // font selection must be done before loading fontenc.sty
2214                 if (params.fonts != "default") {
2215                         LFile += "\\usepackage{" + params.fonts + "}\n";
2216                         texrow.newline();
2217                 }
2218                 // this one is not per buffer
2219                 if (lyxrc->fontenc != "default") {
2220                         LFile += "\\usepackage[" + lyxrc->fontenc
2221                                  + "]{fontenc}\n";
2222                         texrow.newline();
2223                 }
2224                 if (params.inputenc != "default") {
2225                         LFile += "\\usepackage[" + params.inputenc
2226                                  + "]{inputenc}\n";
2227                         texrow.newline();
2228                 }
2229                 
2230                 /* at the very beginning the text parameters */
2231                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2232                         switch (params.paperpackage) {
2233                         case BufferParams::PACKAGE_A4:
2234                                 LFile += "\\usepackage{a4}\n";
2235                                 texrow.newline();
2236                                 break;
2237                         case BufferParams::PACKAGE_A4WIDE:
2238                                 LFile += "\\usepackage{a4wide}\n";
2239                                 texrow.newline();
2240                                 break;
2241                         case BufferParams::PACKAGE_WIDEMARGINSA4:
2242                                 LFile += "\\usepackage[widemargins]{a4}\n";
2243                                 texrow.newline();
2244                                 break;
2245                         }
2246                 }
2247                 if (params.use_geometry) {
2248                         LFile += "\\usepackage{geometry}\n";
2249                         texrow.newline();
2250                         LFile += "\\geometry{verbose";
2251                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2252                                 LFile += ",landscape";
2253                         switch (params.papersize2) {
2254                         case BufferParams::VM_PAPER_CUSTOM:
2255                                 if (!params.paperwidth.empty())
2256                                         LFile += ",paperwidth="
2257                                                  + params.paperwidth;
2258                                 if (!params.paperheight.empty())
2259                                         LFile += ",paperheight="
2260                                                  + params.paperheight;
2261                                 break;
2262                         case BufferParams::VM_PAPER_USLETTER:
2263                                 LFile += ",letterpaper";
2264                                 break;
2265                         case BufferParams::VM_PAPER_USLEGAL:
2266                                 LFile += ",legalpaper";
2267                                 break;
2268                         case BufferParams::VM_PAPER_USEXECUTIVE:
2269                                 LFile += ",executivepaper";
2270                                 break;
2271                         case BufferParams::VM_PAPER_A3:
2272                                 LFile += ",a3paper";
2273                                 break;
2274                         case BufferParams::VM_PAPER_A4:
2275                                 LFile += ",a4paper";
2276                                 break;
2277                         case BufferParams::VM_PAPER_A5:
2278                                 LFile += ",a5paper";
2279                                 break;
2280                         case BufferParams::VM_PAPER_B3:
2281                                 LFile += ",b3paper";
2282                                 break;
2283                         case BufferParams::VM_PAPER_B4:
2284                                 LFile += ",b4paper";
2285                                 break;
2286                         case BufferParams::VM_PAPER_B5:
2287                                 LFile += ",b5paper";
2288                                 break;
2289                         default:
2290                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2291                                 switch (lyxrc->default_papersize) {
2292                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2293                                 case BufferParams::PAPER_USLETTER:
2294                                         LFile += ",letterpaper";
2295                                         break;
2296                                 case BufferParams::PAPER_LEGALPAPER:
2297                                         LFile += ",legalpaper";
2298                                         break;
2299                                 case BufferParams::PAPER_EXECUTIVEPAPER:
2300                                         LFile += ",executivepaper";
2301                                         break;
2302                                 case BufferParams::PAPER_A3PAPER:
2303                                         LFile += ",a3paper";
2304                                         break;
2305                                 case BufferParams::PAPER_A4PAPER:
2306                                         LFile += ",a4paper";
2307                                         break;
2308                                 case BufferParams::PAPER_A5PAPER:
2309                                         LFile += ",a5paper";
2310                                         break;
2311                                 case BufferParams::PAPER_B5PAPER:
2312                                         LFile += ",b5paper";
2313                                         break;
2314                                 }
2315                         }
2316                         if (!params.topmargin.empty())
2317                                 LFile += ",tmargin=" + params.topmargin;
2318                         if (!params.bottommargin.empty())
2319                                 LFile += ",bmargin=" + params.bottommargin;
2320                         if (!params.leftmargin.empty())
2321                                 LFile += ",lmargin=" + params.leftmargin;
2322                         if (!params.rightmargin.empty())
2323                                 LFile += ",rmargin=" + params.rightmargin;
2324                         if (!params.headheight.empty())
2325                                 LFile += ",headheight=" + params.headheight;
2326                         if (!params.headsep.empty())
2327                                 LFile += ",headsep=" + params.headsep;
2328                         if (!params.footskip.empty())
2329                                 LFile += ",footskip=" + params.footskip;
2330                         LFile += "}\n";
2331                         texrow.newline();
2332                 }
2333                 if (params.use_amsmath
2334                     && !prefixIs(textclasslist.LatexnameOfClass(params.textclass), "ams")) {
2335                         LFile += "\\usepackage{amsmath}\n";
2336                 }
2337
2338                 if (tokenPos(tclass.opt_pagestyle(), '|', params.pagestyle) >= 0) {
2339                         if (params.pagestyle == "fancy") {
2340                                 LFile += "\\usepackage{fancyhdr}\n";
2341                                 texrow.newline();
2342                         }
2343                         LFile += "\\pagestyle{" + params.pagestyle + "}\n";
2344                         texrow.newline();
2345                 }
2346
2347                 // We try to load babel late, in case it interferes
2348                 // with other packages.
2349                 if (params.language != "default" || lyxrc->rtl_support ) {
2350                         LFile += "\\usepackage{babel}\n";
2351                         texrow.newline();
2352                 }
2353
2354                 if (params.secnumdepth != tclass.secnumdepth()) {
2355                         LFile += "\\setcounter{secnumdepth}{";
2356                         LFile += tostr(params.secnumdepth);
2357                         LFile += "}\n";
2358                         texrow.newline();
2359                 }
2360                 if (params.tocdepth != tclass.tocdepth()) {
2361                         LFile += "\\setcounter{tocdepth}{";
2362                         LFile += tostr(params.tocdepth);
2363                         LFile += "}\n";
2364                         texrow.newline();
2365                 }
2366                 
2367                 if (params.paragraph_separation) {
2368                         switch (params.defskip.kind()) {
2369                         case VSpace::SMALLSKIP: 
2370                                 LFile += "\\setlength\\parskip{\\smallskipamount}\n";
2371                                 break;
2372                         case VSpace::MEDSKIP:
2373                                 LFile += "\\setlength\\parskip{\\medskipamount}\n";
2374                                 break;
2375                         case VSpace::BIGSKIP:
2376                                 LFile += "\\setlength\\parskip{\\bigskipamount}\n";
2377                                 break;
2378                         case VSpace::LENGTH:
2379                                 LFile += "\\setlength\\parskip{"
2380                                          + params.defskip.length().asLatexString()
2381                                          + "}\n";
2382                                 break;
2383                         default: // should never happen // Then delete it.
2384                                 LFile += "\\setlength\\parskip{\\medskipamount}\n";
2385                                 break;
2386                         }
2387                         texrow.newline();
2388                         
2389                         LFile += "\\setlength\\parindent{0pt}\n";
2390                         texrow.newline();
2391                 }
2392
2393                 // Write out what we've generated so far...and reset LFile
2394                 ofs << LFile;
2395                 LFile.clear(); 
2396
2397                 // Now insert the LyX specific LaTeX commands...
2398                 string preamble, tmppreamble;
2399
2400                 // The optional packages;
2401                 preamble = features.getPackages(params);
2402
2403                 // this might be useful...
2404                 preamble += "\n\\makeatletter\n\n";
2405
2406                 // Some macros LyX will need
2407                 tmppreamble = features.getMacros(params);
2408
2409                 if (!tmppreamble.empty()) {
2410                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2411                                 "LyX specific LaTeX commands.\n"
2412                                 + tmppreamble + '\n';
2413                 }
2414
2415                 // the text class specific preamble 
2416                 tmppreamble = features.getTClassPreamble(params);
2417                 if (!tmppreamble.empty()) {
2418                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2419                                 "Textclass specific LaTeX commands.\n"
2420                                 + tmppreamble + '\n';
2421                 }
2422
2423                 /* the user-defined preamble */
2424                 if (!params.preamble.empty()) {
2425                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2426                                 "User specified LaTeX commands.\n"
2427                                 + params.preamble + '\n';
2428                 }
2429
2430                 preamble += "\\makeatother\n\n";
2431
2432                 // Itemize bullet settings need to be last in case the user
2433                 // defines their own bullets that use a package included
2434                 // in the user-defined preamble -- ARRae
2435                 // Actually it has to be done much later than that
2436                 // since some packages like frenchb make modifications
2437                 // at \begin{document} time -- JMarc 
2438                 string bullets_def;
2439                 for (int i = 0; i < 4; ++i) {
2440                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2441                                 if (bullets_def.empty())
2442                                         bullets_def="\\AtBeginDocument{\n";
2443                                 bullets_def += "  \\renewcommand{\\labelitemi";
2444                                 switch (i) {
2445                                 // `i' is one less than the item to modify
2446                                 case 0:
2447                                         break;
2448                                 case 1:
2449                                         bullets_def += 'i';
2450                                         break;
2451                                 case 2:
2452                                         bullets_def += "ii";
2453                                         break;
2454                                 case 3:
2455                                         bullets_def += 'v';
2456                                         break;
2457                                 }
2458                                 bullets_def += "}{" + 
2459                                   params.user_defined_bullets[i].getText() 
2460                                   + "}\n";
2461                         }
2462                 }
2463
2464                 if (!bullets_def.empty())
2465                   preamble += bullets_def + "}\n\n";
2466
2467                 for (int j = countChar(preamble, '\n'); j-- ;) {
2468                         texrow.newline();
2469                 }
2470
2471                 ofs << preamble;
2472
2473                 // make the body.
2474                 LFile += "\\begin{document}\n\n";
2475                 texrow.newline();
2476                 texrow.newline();
2477         } // only_body
2478         lyxerr.debug() << "preamble finished, now the body." << endl;
2479         
2480         bool was_title = false;
2481         bool already_title = false;
2482         string ftnote;
2483         TexRow ft_texrow;
2484         int ftcount = 0;
2485         int loop_count = 0;
2486
2487         LyXParagraph * par = paragraph;
2488
2489         // if only_body
2490         while (par) {
2491                 ++loop_count;
2492                 if (par->IsDummy())
2493                         lyxerr[Debug::LATEX] << "Error in MakeLateXFile."
2494                                              << endl;
2495                 LyXLayout const & layout =
2496                         textclasslist.Style(params.textclass,
2497                                             par->layout);
2498             
2499                 if (layout.intitle) {
2500                         if (already_title) {
2501                                 lyxerr <<"Error in MakeLatexFile: You"
2502                                         " should not mix title layouts"
2503                                         " with normal ones." << endl;
2504                         } else
2505                                 was_title = true;
2506                 } else if (was_title && !already_title) {
2507                         LFile += "\\maketitle\n";
2508                         texrow.newline();
2509                         already_title = true;
2510                         was_title = false;                  
2511                 }
2512                 // We are at depth 0 so we can just use
2513                 // ordinary \footnote{} generation
2514                 // flag this with ftcount
2515                 ftcount = -1;
2516                 if (layout.isEnvironment()
2517                     || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2518                         par = par->TeXEnvironment(LFile, texrow,
2519                                                   ftnote, ft_texrow, ftcount);
2520                 } else {
2521                         par = par->TeXOnePar(LFile, texrow,
2522                                              ftnote, ft_texrow, ftcount);
2523                 }
2524
2525                 // Write out what we've generated...and reset LFile
2526                 if (ftcount >= 1) {
2527                         if (ftcount > 1) {
2528                                 LFile += "\\addtocounter{footnote}{-";
2529                                 LFile += tostr(ftcount - 1);
2530                                 LFile += '}';
2531                         }
2532                         LFile += ftnote;
2533                         texrow += ft_texrow;
2534                         ftnote.clear();
2535                         ft_texrow.reset();
2536                         ftcount = 0;
2537                 }
2538                 if (loop_count == 2) {
2539                         // fwrite()ing every second time through the loop
2540                         // gains a few extra % of speed; going higher than
2541                         // 2 will slow things down again.  I'll look at
2542                         // LFile.length() in a future revision.  ARRae
2543                         ofs << LFile;
2544                         LFile.clear();
2545                         loop_count = 0;
2546                 }
2547         }
2548
2549         // It might be that we only have a title in this document
2550         if (was_title && !already_title) {
2551                 LFile += "\\maketitle\n";
2552                 texrow.newline();
2553         }
2554
2555         if (!only_body) {
2556                 LFile += "\\end{document}\n";
2557                 texrow.newline();
2558         
2559                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2560         } else {
2561                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2562                                      << endl;
2563         }
2564
2565         // Just to be sure. (Asger)
2566         texrow.newline();
2567
2568         // Write out what we've generated...and reset LFile
2569         ofs << LFile;
2570         LFile.clear();
2571
2572         // tex_code_break_column's value is used to decide
2573         // if we are in batchmode or not (within mathed_write()
2574         // in math_write.C) so we must set it to a non-zero
2575         // value when we leave otherwise we save incorrect .lyx files.
2576         tex_code_break_column = lyxrc->ascii_linelen;
2577
2578         // How to check if the close went ok when using fstreams
2579         ofs.close();
2580         lyxerr.debug() << "Finished making latex file." << endl;
2581 }
2582 #endif
2583
2584
2585 bool Buffer::isLatex() const
2586 {
2587         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2588 }
2589
2590
2591 bool Buffer::isLinuxDoc() const
2592 {
2593         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2594 }
2595
2596
2597 bool Buffer::isLiterate() const
2598 {
2599         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2600 }
2601
2602
2603 bool Buffer::isDocBook() const
2604 {
2605         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2606 }
2607
2608
2609 bool Buffer::isSGML() const
2610 {
2611         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2612                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2613 }
2614
2615
2616 void Buffer::sgmlOpenTag(ostream & os, int depth,
2617                          string const & latexname) const
2618 {
2619         os << string(depth, ' ') << "<" << latexname << ">\n";
2620 }
2621
2622
2623 void Buffer::sgmlCloseTag(ostream & os, int depth,
2624                           string const & latexname) const
2625 {
2626         os << string(depth, ' ') << "</" << latexname << ">\n";
2627 }
2628
2629
2630 void Buffer::makeLinuxDocFile(string const & fname, int column)
2631 {
2632         LyXParagraph * par = paragraph;
2633
2634         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2635         string environment_stack[10];
2636         string item_name;
2637
2638         int depth = 0;              /* paragraph depth */
2639
2640         ofstream ofs(fname.c_str());
2641
2642         if (!ofs) {
2643                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2644                 return;
2645         }
2646    
2647         tex_code_break_column = column; 
2648         texrow.reset();
2649    
2650         if (params.preamble.empty()) {
2651                 ofs << "<!doctype linuxdoc system>\n\n";
2652         }
2653         else {
2654                 ofs << "<!doctype linuxdoc system \n [ "
2655                     << params.preamble << " \n]>\n\n";
2656         }
2657
2658         ofs << "<!-- "  << LYX_DOCVERSION 
2659             << " created this file. For more info see http://www.lyx.org/"
2660             << " -->\n";
2661
2662         if(params.options.empty())
2663                 sgmlOpenTag(ofs, 0, top_element);
2664         else {
2665                 string top = top_element;
2666                 top += " ";
2667                 top += params.options;
2668                 sgmlOpenTag(ofs, 0, top);
2669         }
2670
2671         while (par) {
2672                 int desc_on = 0;            /* description mode*/
2673                 LyXLayout const & style =
2674                         textclasslist.Style(users->buffer()->params.textclass,
2675                                             par->layout);
2676                 par->AutoDeleteInsets();
2677
2678                 /* treat <toc> as a special case for compatibility with old code */
2679                 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2680                         Inset * inset = par->GetInset(0);
2681                         char  lyx_code = inset->LyxCode();
2682                         if (lyx_code == Inset::TOC_CODE){
2683                                 string temp = "toc";
2684                                 sgmlOpenTag(ofs, depth, temp);
2685
2686                                 par = par->next;
2687                                 linuxDocHandleFootnote(ofs, par, depth);
2688                                 continue;
2689                         }
2690                 }
2691
2692                 // environment tag closing
2693                 for( ; depth > par->depth; --depth) {
2694                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2695                         environment_stack[depth].clear();
2696                 }
2697
2698                 // write opening SGML tags
2699                 switch(style.latextype) {
2700                 case LATEX_PARAGRAPH:
2701                         if(depth == par->depth 
2702                            && !environment_stack[depth].empty()) {
2703                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2704                                 environment_stack[depth].clear();
2705                                 if(depth) 
2706                                         --depth;
2707                                 else
2708                                         ofs << "</p>";
2709                         }
2710                         sgmlOpenTag(ofs, depth, style.latexname());
2711                         break;
2712
2713                 case LATEX_COMMAND:
2714                         if (depth!= 0)
2715                                 LinuxDocError(par, 0, _("Error : Wrong depth for LatexType Command.\n"));
2716
2717                         if (!environment_stack[depth].empty()){
2718                                 sgmlCloseTag(ofs, depth,
2719                                              environment_stack[depth]);
2720                                 ofs << "</p>";
2721                         }
2722
2723                         environment_stack[depth].clear();
2724                         sgmlOpenTag(ofs, depth, style.latexname());
2725                         break;
2726
2727                 case LATEX_ENVIRONMENT:
2728                 case LATEX_ITEM_ENVIRONMENT:
2729                         if(depth == par->depth 
2730                            && environment_stack[depth] != style.latexname()
2731                            && !environment_stack[depth].empty()) {
2732
2733                                 sgmlCloseTag(ofs, depth,
2734                                              environment_stack[depth]);
2735                                 environment_stack[depth].clear();
2736                         }
2737                         if (depth < par->depth) {
2738                                depth = par->depth;
2739                                environment_stack[depth].clear();
2740                         }
2741                         if (environment_stack[depth] != style.latexname()) {
2742                                 if(depth == 0) {
2743                                         string temp = "p";
2744                                         sgmlOpenTag(ofs, depth, temp);
2745                                 }
2746                                 environment_stack[depth] = style.latexname();
2747                                 sgmlOpenTag(ofs, depth, environment_stack[depth]);
2748                         }
2749                         if(style.latextype == LATEX_ENVIRONMENT) break;
2750
2751                         desc_on = (style.labeltype == LABEL_MANUAL);
2752
2753                         if(desc_on)
2754                                 item_name = "tag";
2755                         else
2756                                 item_name = "item";
2757
2758                         sgmlOpenTag(ofs, depth + 1, item_name);
2759                         break;
2760                 default:
2761                         sgmlOpenTag(ofs, depth, style.latexname());
2762                         break;
2763                 }
2764
2765                 do {
2766                         SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2767
2768                         par = par->next;
2769                         linuxDocHandleFootnote(ofs, par, depth);
2770                 }
2771                 while(par && par->IsDummy());
2772
2773                 ofs << "\n";
2774                 /* write closing SGML tags */
2775                 switch(style.latextype) {
2776                 case LATEX_COMMAND:
2777                 case LATEX_ENVIRONMENT:
2778                 case LATEX_ITEM_ENVIRONMENT:
2779                         break;
2780                 default:
2781                         sgmlCloseTag(ofs, depth, style.latexname());
2782                         break;
2783                 }
2784         }
2785    
2786         /* Close open tags */
2787         for(; depth > 0; --depth)
2788                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2789
2790         if(!environment_stack[depth].empty())
2791                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2792
2793         ofs << "\n\n";
2794         sgmlCloseTag(ofs, 0, top_element);
2795
2796         ofs.close();
2797         // How to check for successful close
2798 }
2799
2800
2801 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2802                                     int const depth)
2803 {
2804         string tag = "footnote";
2805
2806         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2807                 sgmlOpenTag(os, depth + 1, tag);
2808                 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2809                 sgmlCloseTag(os, depth + 1, tag);
2810                 par = par->next;
2811         }
2812 }
2813
2814
2815 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2816                                   int const depth, int desc_on,
2817                                   LyXParagraph * & par)
2818 {
2819         LyXParagraph * tpar = par;
2820         while (tpar && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE) &&
2821                (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2822                                                              "Caption").second))
2823                 tpar = tpar->next;
2824         if (tpar &&
2825             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2826                                                          "Caption").second) {
2827                 sgmlOpenTag(os, depth + 1, inner_tag);
2828 #ifdef USE_OSTREAM_ONLY
2829                 string extra_par;
2830                 SimpleDocBookOnePar(os, extra_par, tpar,
2831                                     desc_on, depth + 2);
2832 #else
2833                 string tmp_par, extra_par;
2834                 SimpleDocBookOnePar(tmp_par, extra_par, tpar,
2835                                     desc_on, depth + 2);
2836                 tmp_par = strip(tmp_par);
2837                 tmp_par = frontStrip(tmp_par);
2838                 os << tmp_par;
2839 #endif
2840                 sgmlCloseTag(os, depth+1, inner_tag);
2841                 if(!extra_par.empty())
2842                         os << extra_par;
2843         }
2844 }
2845
2846
2847 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2848                                    int const depth)
2849 {
2850         string tag, inner_tag;
2851         string tmp_par, extra_par;
2852         bool inner_span = false;
2853         int desc_on = 4;
2854
2855         // This is not how I like to see enums. They should not be anonymous
2856         // and variables of its type should not be declared right after the
2857         // last brace. (Lgb)
2858         enum SOME_ENUM {
2859                 NO_ONE,
2860                 FOOTNOTE_LIKE,
2861                 MARGIN_LIKE,
2862                 FIG_LIKE,
2863                 TAB_LIKE
2864         };
2865         SOME_ENUM last = NO_ONE;
2866         SOME_ENUM present = FOOTNOTE_LIKE;
2867
2868         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2869                 if(last == present) {
2870                         if(inner_span) {
2871                                 if(!tmp_par.empty()) {
2872                                         os << tmp_par;
2873                                         tmp_par.clear();
2874                                         sgmlCloseTag(os, depth+1, inner_tag);
2875                                         sgmlOpenTag(os, depth+1, inner_tag);
2876                                 }
2877                         }
2878                         else
2879                                 os << "\n";
2880                 } else {
2881                         os << tmp_par;
2882                         if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2883                                                             inner_tag);
2884                         if(!extra_par.empty()) os << extra_par;
2885                         if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2886                         extra_par.clear();
2887
2888                         switch (par->footnotekind) {
2889                         case LyXParagraph::FOOTNOTE:
2890                         case LyXParagraph::ALGORITHM:
2891                                 tag = "footnote";
2892                                 inner_tag = "para";
2893                                 present = FOOTNOTE_LIKE;
2894                                 inner_span = true;
2895                                 break;
2896                         case LyXParagraph::MARGIN:
2897                                 tag = "sidebar";
2898                                 inner_tag = "para";
2899                                 present = MARGIN_LIKE;
2900                                 inner_span = true;
2901                                 break;
2902                         case LyXParagraph::FIG:
2903                         case LyXParagraph::WIDE_FIG:
2904                                 tag = "figure";
2905                                 inner_tag = "title";
2906                                 present = FIG_LIKE;
2907                                 inner_span = false;
2908                                 break;
2909                         case LyXParagraph::TAB:
2910                         case LyXParagraph::WIDE_TAB:
2911                                 tag = "table";
2912                                 inner_tag = "title";
2913                                 present = TAB_LIKE;
2914                                 inner_span = false;
2915                                 break;
2916                         }
2917                         sgmlOpenTag(os, depth, tag);
2918                         if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2919                                 DocBookHandleCaption(os, inner_tag, depth,
2920                                                      desc_on, par);
2921                                 inner_tag.clear();
2922                         } else {
2923                                 sgmlOpenTag(os, depth + 1, inner_tag);
2924                         }
2925                 }
2926                 // ignore all caption here, we processed them above!!!
2927                 if (par->layout != textclasslist.NumberOfLayout(params.textclass,
2928                                                            "Caption").second) {
2929 #ifdef USE_OSTREAM_ONLY
2930 #ifdef HAVE_SSTREAM
2931                         ostringstream ost;
2932 #else
2933                         ostrstream ost;
2934 #endif
2935                         SimpleDocBookOnePar(ost, extra_par, par,
2936                                             desc_on, depth + 2);
2937 #ifdef HAVE_SSTREAM
2938                         tmp_par += ost.str().c_str();
2939 #else
2940                         ost << '\0';
2941                         char * ctmp = ost.str();
2942                         tmp_par += ctmp;
2943                         delete [] ctmp;
2944 #endif
2945 #else
2946 #endif
2947                 }
2948                 tmp_par = frontStrip(strip(tmp_par));
2949
2950                 last = present;
2951                 par = par->next;
2952         }
2953         os << tmp_par;
2954         if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2955         if(!extra_par.empty()) os << extra_par;
2956         if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2957 }
2958
2959
2960 /* push a tag in a style stack */
2961 void Buffer::push_tag(ostream & os, char const * tag,
2962                       int & pos, char stack[5][3])
2963 {
2964         /* pop all previous tags */
2965         for (int j = pos; j >= 0; --j)
2966                 os << "</" << stack[j] << ">";
2967
2968         /* add new tag */
2969         sprintf(stack[++pos], "%s", tag);
2970
2971         /* push all tags */
2972         for (int i = 0; i <= pos; ++i)
2973                 os << "<" << stack[i] << ">";
2974 }
2975
2976 void Buffer::pop_tag(ostream & os, char const * tag,
2977                      int & pos, char stack[5][3])
2978 {
2979         int j;
2980
2981         // pop all tags till specified one
2982         for (j = pos; (j >= 0) && (strcmp(stack[j], tag)); --j)
2983                 os << "</" << stack[j] << ">";
2984
2985         // closes the tag
2986         os << "</" << tag << ">";
2987
2988         // push all tags, but the specified one
2989         for (j = j + 1; j <= pos; ++j) {
2990                 os << "<" << stack[j] << ">";
2991                 strcpy(stack[j-1], stack[j]);
2992         }
2993         --pos;
2994 }
2995
2996
2997 /* handle internal paragraph parsing -- layout already processed */
2998
2999 // checks, if newcol chars should be put into this line
3000 // writes newline, if necessary.
3001 static
3002 void linux_doc_line_break(ostream & os, unsigned int & colcount,
3003                           const unsigned int newcol)
3004 {
3005         colcount += newcol;
3006         if (colcount > lyxrc->ascii_linelen) {
3007                 os << "\n";
3008                 colcount = newcol; // assume write after this call
3009         }
3010 }
3011
3012
3013 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
3014                                   int desc_on, int const /*depth*/)
3015 {
3016         LyXFont font1, font2;
3017         char c;
3018         Inset * inset;
3019         LyXParagraph::size_type main_body;
3020         int j;
3021         LyXLayout const & style = textclasslist.Style(params.textclass,
3022                                                       par->GetLayout());
3023
3024         char family_type = 0;               // family font flag 
3025         bool is_bold     = false;           // series font flag 
3026         char shape_type  = 0;               // shape font flag 
3027         bool is_em = false;                 // emphasis (italic) font flag 
3028
3029         int stack_num = -1;          // style stack position 
3030         char stack[5][3];            // style stack 
3031         unsigned int char_line_count = 5;     // Heuristic choice ;-) 
3032
3033         if (style.labeltype != LABEL_MANUAL)
3034                 main_body = 0;
3035         else
3036                 main_body = par->BeginningOfMainBody();
3037
3038         /* gets paragraph main font */
3039         if (main_body > 0)
3040                 font1 = style.labelfont;
3041         else
3042                 font1 = style.font;
3043
3044   
3045         /* parsing main loop */
3046         for (LyXParagraph::size_type i = 0;
3047              i < par->size(); ++i) {
3048
3049                 /* handle quote tag */
3050                 if (i == main_body && !par->IsDummy()) {
3051                         if (main_body > 0)
3052                                 font1 = style.font;
3053                 }
3054
3055                 font2 = par->getFont(i);
3056
3057                 if (font1.family() != font2.family()) {
3058                         switch(family_type) {
3059                         case 0:
3060                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
3061                                         push_tag(os, "tt", stack_num, stack);
3062                                         family_type= 1;
3063                                 }
3064                                 else if (font2.family() == LyXFont::SANS_FAMILY) {
3065                                         push_tag(os, "sf", stack_num, stack);
3066                                         family_type= 2;
3067                                 }
3068                                 break;
3069                         case 1:
3070                                 pop_tag(os, "tt", stack_num, stack);
3071                                 if (font2.family() == LyXFont::SANS_FAMILY) {
3072                                         push_tag(os, "sf", stack_num, stack);
3073                                         family_type= 2;
3074                                 }
3075                                 else {
3076                                         family_type= 0;
3077                                 }
3078                                 break;
3079                         case 2:
3080                                 pop_tag(os, "sf", stack_num, stack);
3081                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
3082                                         push_tag(os, "tt", stack_num, stack);
3083                                         family_type= 1;
3084                                 }
3085                                 else {
3086                                         family_type= 0;
3087                                 }
3088                         }
3089                 }
3090
3091                 /* handle bold face */
3092                 if (font1.series() != font2.series()) {
3093                         if (font2.series() == LyXFont::BOLD_SERIES) {
3094                                 push_tag(os, "bf", stack_num, stack);
3095                                 is_bold = true;
3096                         }
3097                         else if (is_bold) {
3098                                 pop_tag(os, "bf", stack_num, stack);
3099                                 is_bold = false;
3100                         }
3101                 }
3102
3103                 /* handle italic and slanted fonts */
3104                 if (font1.shape() != font2.shape()) {
3105                         switch(shape_type) {
3106                         case 0:
3107                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
3108                                         push_tag(os, "it", stack_num, stack);
3109                                         shape_type= 1;
3110                                 }
3111                                 else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
3112                                         push_tag(os, "sl", stack_num, stack);
3113                                         shape_type= 2;
3114                                 }
3115                                 break;
3116                         case 1:
3117                                 pop_tag(os, "it", stack_num, stack);
3118                                 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
3119                                         push_tag(os, "sl", stack_num, stack);
3120                                         shape_type= 2;
3121                                 }
3122                                 else {
3123                                         shape_type= 0;
3124                                 }
3125                                 break;
3126                         case 2:
3127                                 pop_tag(os, "sl", stack_num, stack);
3128                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
3129                                         push_tag(os, "it", stack_num, stack);
3130                                         shape_type= 1;
3131                                 }
3132                                 else {
3133                                         shape_type= 0;
3134                                 }
3135                         }
3136                 }
3137                 /* handle <em> tag */
3138                 if (font1.emph() != font2.emph()) {
3139                         if (font2.emph() == LyXFont::ON) {
3140                                 push_tag(os, "em", stack_num, stack);
3141                                 is_em = true;
3142                         } else if (is_em) {
3143                                 pop_tag(os, "em", stack_num, stack);
3144                                 is_em = false;
3145                         }
3146                 }
3147
3148                 c = par->GetChar(i);
3149       
3150                 if (font2.latex() == LyXFont::ON) {
3151                         // "TeX"-Mode on == > SGML-Mode on.
3152                         if (c!= '\0')
3153                                 os << c; // see LaTeX-Generation...
3154                         ++char_line_count;
3155                 } else if (c == LyXParagraph::META_INSET) {
3156                         inset = par->GetInset(i);
3157 #ifdef USE_OSTREAM_ONLY
3158                         inset->Linuxdoc(os);
3159 #else
3160                         string tmp_out;
3161                         inset->Linuxdoc(tmp_out);
3162                         os << tmp_out;
3163 #endif
3164                 }
3165                 else {
3166                         string sgml_string;
3167                         if (par->linuxDocConvertChar(c, sgml_string)
3168                             && !style.free_spacing) { // in freespacing
3169                                                      // mode, spaces are
3170                                                      // non-breaking characters
3171                                 // char is ' '
3172                                 if (desc_on == 1) {
3173                                         ++char_line_count;
3174                                         linux_doc_line_break(os, char_line_count, 6);
3175                                         os << "</tag>";
3176                                         desc_on = 2;
3177                                 }
3178                                 else  {
3179                                         linux_doc_line_break(os, char_line_count, 1);
3180                                         os << c;
3181                                 }
3182                         }
3183                         else {
3184                                 os << sgml_string;
3185                                 char_line_count += sgml_string.length();
3186                         }
3187                 }
3188                 font1 = font2;
3189         }
3190
3191         /* needed if there is an optional argument but no contents */
3192         if (main_body > 0 && main_body == par->size()) {
3193                 font1 = style.font;
3194         }
3195
3196         /* pop all defined Styles */
3197         for (j = stack_num; j >= 0; --j) {
3198                 linux_doc_line_break(os, 
3199                                      char_line_count, 
3200                                      3 + strlen(stack[j]));
3201                 os << "</" << stack[j] << ">";
3202         }
3203
3204         /* resets description flag correctly */
3205         switch(desc_on){
3206         case 1:
3207                 /* <tag> not closed... */
3208                 linux_doc_line_break(os, char_line_count, 6);
3209                 os << "</tag>";
3210                 break;
3211         case 2:
3212                 /* fprintf(file, "</p>");*/
3213                 break;
3214         }
3215 }
3216
3217
3218 /* print an error message */
3219 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
3220                            char const * message) 
3221 {
3222         InsetError * new_inset;
3223
3224         /* insert an error marker in text */
3225         new_inset = new InsetError(message);
3226         par->InsertChar(pos, LyXParagraph::META_INSET);
3227         par->InsertInset(pos, new_inset);
3228 }
3229
3230 // This constant defines the maximum number of 
3231 // environment layouts that can be nesteded.
3232 // The same applies for command layouts.
3233 // These values should be more than enough.
3234 //           José Matos (1999/07/22)
3235
3236 enum { MAX_NEST_LEVEL = 25};
3237
3238 void Buffer::makeDocBookFile(string const & fname, int column)
3239 {
3240         LyXParagraph * par = paragraph;
3241
3242         string top_element= textclasslist.LatexnameOfClass(params.textclass);
3243         string environment_stack[MAX_NEST_LEVEL];
3244         string environment_inner[MAX_NEST_LEVEL];
3245         string command_stack[MAX_NEST_LEVEL];
3246         bool command_flag= false;
3247         int command_depth= 0, command_base= 0, cmd_depth= 0;
3248
3249         string item_name, command_name;
3250         string c_depth, c_params, tmps;
3251
3252         int depth= 0;              /* paragraph depth */
3253
3254         tex_code_break_column = column; 
3255
3256         ofstream ofs(fname.c_str());
3257         if (!ofs) {
3258                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3259                 return;
3260         }
3261    
3262         texrow.reset();
3263
3264         ofs << "<!doctype " << top_element
3265             << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3266
3267         if (params.preamble.empty())
3268                 ofs << ">\n\n";
3269         else
3270                 ofs << "\n [ " << params.preamble << " \n]>\n\n";
3271
3272         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
3273             << "\n  See http://www.lyx.org/ for more information -->\n";
3274
3275         if(params.options.empty())
3276                 sgmlOpenTag(ofs, 0, top_element);
3277         else {
3278                 string top = top_element;
3279                 top += " ";
3280                 top += params.options;
3281                 sgmlOpenTag(ofs, 0, top);
3282         }
3283
3284         while (par) {
3285                 int desc_on = 0;            /* description mode*/
3286                 LyXLayout const & style =
3287                         textclasslist.Style(users->buffer()->params.textclass,
3288                                             par->layout);
3289                 par->AutoDeleteInsets();
3290
3291                 /* environment tag closing */
3292                 for( ; depth > par->depth; --depth) {
3293                         if(environment_inner[depth] != "!-- --") {
3294                                 item_name= "listitem";
3295                                 sgmlCloseTag(ofs, command_depth + depth,
3296                                              item_name);
3297                                 if( environment_inner[depth] == "varlistentry")
3298                                         sgmlCloseTag(ofs, depth+command_depth,
3299                                                      environment_inner[depth]);
3300                         }
3301                         sgmlCloseTag(ofs, depth + command_depth,
3302                                      environment_stack[depth]);
3303                         environment_stack[depth].clear();
3304                         environment_inner[depth].clear();
3305                 }
3306
3307                 if(depth == par->depth
3308                    && environment_stack[depth] != style.latexname()
3309                    && !environment_stack[depth].empty()) {
3310                         if(environment_inner[depth] != "!-- --") {
3311                                 item_name= "listitem";
3312                                 sgmlCloseTag(ofs, command_depth+depth,
3313                                              item_name);
3314                                 if( environment_inner[depth] == "varlistentry")
3315                                         sgmlCloseTag(ofs,
3316                                                      depth + command_depth,
3317                                                      environment_inner[depth]);
3318                         }
3319                         
3320                         sgmlCloseTag(ofs, depth + command_depth,
3321                                      environment_stack[depth]);
3322                         
3323                         environment_stack[depth].clear();
3324                         environment_inner[depth].clear();
3325                 }
3326
3327                 // Write opening SGML tags.
3328                 switch(style.latextype) {
3329                 case LATEX_PARAGRAPH:
3330                         if(style.latexname() != "dummy")
3331                                sgmlOpenTag(ofs, depth+command_depth,
3332                                            style.latexname());
3333                         break;
3334
3335                 case LATEX_COMMAND:
3336                         if (depth!= 0)
3337                                 LinuxDocError(par, 0,
3338                                               _("Error : Wrong depth for "
3339                                                 "LatexType Command.\n"));
3340                         
3341                         command_name = style.latexname();
3342                         
3343                         tmps = style.latexparam();
3344                         c_params = split(tmps, c_depth,'|');
3345                         
3346                         cmd_depth= atoi(c_depth.c_str());
3347                         
3348                         if(command_flag) {
3349                                 if(cmd_depth<command_base) {
3350                                         for(int j = command_depth;
3351                                             j >= command_base; --j)
3352                                                 if(!command_stack[j].empty())
3353                                                         sgmlCloseTag(ofs, j, command_stack[j]);
3354                                         command_depth= command_base= cmd_depth;
3355                                 }
3356                                 else if(cmd_depth <= command_depth) {
3357                                         for(int j = command_depth;
3358                                             j >= cmd_depth; --j)
3359
3360                                                 if(!command_stack[j].empty())
3361                                                         sgmlCloseTag(ofs, j, command_stack[j]);
3362                                         command_depth= cmd_depth;
3363                                 }
3364                                 else
3365                                         command_depth= cmd_depth;
3366                         }
3367                         else {
3368                                 command_depth = command_base = cmd_depth;
3369                                 command_flag = true;
3370                         }
3371                         command_stack[command_depth]= command_name;
3372
3373                         // treat label as a special case for
3374                         // more WYSIWYM handling.
3375                         if (par->GetChar(0) == LyXParagraph::META_INSET) {
3376                                 Inset * inset = par->GetInset(0);
3377                                 char  lyx_code = inset->LyxCode();
3378                                 if (lyx_code == Inset::LABEL_CODE){
3379                                         command_name += " id=\"";
3380                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3381                                         command_name += "\"";
3382                                         desc_on = 3;
3383                                 }
3384                         }
3385
3386                         sgmlOpenTag(ofs, depth+command_depth, command_name);
3387                         item_name = "title";
3388                         sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3389                         break;
3390
3391                 case LATEX_ENVIRONMENT:
3392                 case LATEX_ITEM_ENVIRONMENT:
3393                         if (depth < par->depth) {
3394                                 depth = par->depth;
3395                                 environment_stack[depth].clear();
3396                         }
3397
3398                         if (environment_stack[depth] != style.latexname()) {
3399                                 environment_stack[depth] = style.latexname();
3400                                 environment_inner[depth] = "!-- --";
3401                                 sgmlOpenTag(ofs, depth + command_depth,
3402                                             environment_stack[depth]);
3403                         } else {
3404                                 if(environment_inner[depth] != "!-- --") {
3405                                         item_name= "listitem";
3406                                         sgmlCloseTag(ofs,
3407                                                      command_depth + depth,
3408                                                      item_name);
3409                                         if (environment_inner[depth] == "varlistentry")
3410                                                 sgmlCloseTag(ofs,
3411                                                              depth + command_depth,
3412                                                              environment_inner[depth]);
3413                                 }
3414                         }
3415                         
3416                         if(style.latextype == LATEX_ENVIRONMENT) {
3417                                 if(!style.latexparam().empty())
3418                                         sgmlOpenTag(ofs, depth + command_depth,
3419                                                     style.latexparam());
3420                                 break;
3421                         }
3422
3423                         desc_on = (style.labeltype == LABEL_MANUAL);
3424
3425                         if(desc_on)
3426                                 environment_inner[depth]= "varlistentry";
3427                         else
3428                                 environment_inner[depth]= "listitem";
3429
3430                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3431                                     environment_inner[depth]);
3432
3433                         if(desc_on) {
3434                                 item_name= "term";
3435                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3436                                             item_name);
3437                         }
3438                         else {
3439                                 item_name= "para";
3440                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3441                                             item_name);
3442                         }
3443                         break;
3444                 default:
3445                         sgmlOpenTag(ofs, depth + command_depth,
3446                                     style.latexname());
3447                         break;
3448                 }
3449
3450                 do {
3451 #ifdef USE_OSTREAM_ONLY
3452                         string extra_par;
3453                         SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3454                                             depth + 1 + command_depth);
3455                         par = par->next;
3456                         DocBookHandleFootnote(ofs, par,
3457                                               depth + 1 + command_depth);
3458 #else
3459                         string tmp_par, extra_par;
3460
3461                         SimpleDocBookOnePar(tmp_par, extra_par, par, desc_on,
3462                                             depth + 1 + command_depth);
3463                         ofs << tmp_par;
3464
3465                         par = par->next;
3466                         DocBookHandleFootnote(ofs, par,
3467                                               depth + 1 + command_depth);
3468 #endif
3469                 }
3470                 while(par && par->IsDummy());
3471
3472                 string end_tag;
3473                 /* write closing SGML tags */
3474                 switch(style.latextype) {
3475                 case LATEX_COMMAND:
3476                         end_tag = "title";
3477                         sgmlCloseTag(ofs, depth + command_depth, end_tag);
3478                         break;
3479                 case LATEX_ENVIRONMENT:
3480                         if(!style.latexparam().empty())
3481                                 sgmlCloseTag(ofs, depth + command_depth,
3482                                              style.latexparam());
3483                         break;
3484                 case LATEX_ITEM_ENVIRONMENT:
3485                         if(desc_on == 1) break;
3486                         end_tag= "para";
3487                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3488                         break;
3489                 case LATEX_PARAGRAPH:
3490                         if(style.latexname() != "dummy")
3491                                 sgmlCloseTag(ofs, depth + command_depth,
3492                                              style.latexname());
3493                         break;
3494                 default:
3495                         sgmlCloseTag(ofs, depth + command_depth,
3496                                      style.latexname());
3497                         break;
3498                 }
3499         }
3500
3501         // Close open tags
3502         for(; depth >= 0; --depth) {
3503                 if(!environment_stack[depth].empty()) {
3504                         if(environment_inner[depth] != "!-- --") {
3505                                 item_name= "listitem";
3506                                 sgmlCloseTag(ofs, command_depth + depth,
3507                                              item_name);
3508                                if( environment_inner[depth] == "varlistentry")
3509                                        sgmlCloseTag(ofs, depth + command_depth,
3510                                                     environment_inner[depth]);
3511                         }
3512                         
3513                         sgmlCloseTag(ofs, depth + command_depth,
3514                                      environment_stack[depth]);
3515                 }
3516         }
3517         
3518         for(int j = command_depth; j >= command_base; --j)
3519                 if(!command_stack[j].empty())
3520                         sgmlCloseTag(ofs, j, command_stack[j]);
3521
3522         ofs << "\n\n";
3523         sgmlCloseTag(ofs, 0, top_element);
3524
3525         ofs.close();
3526         // How to check for successful close
3527 }
3528
3529
3530 #ifdef USE_OSTREAM_ONLY
3531 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3532                                  LyXParagraph * par, int & desc_on,
3533                                  int const depth) 
3534 {
3535         if (par->table) {
3536                 par->SimpleDocBookOneTablePar(os, extra, desc_on, depth);
3537                 return;
3538         }
3539         LyXFont font1, font2;
3540         char c;
3541         Inset * inset;
3542         LyXParagraph::size_type main_body;
3543         int j;
3544         //string emph = "emphasis";
3545         bool emph_flag = false;
3546         int char_line_count = 0;
3547
3548         LyXLayout const & style = textclasslist.Style(params.textclass,
3549                                                       par->GetLayout());
3550
3551         if (style.labeltype != LABEL_MANUAL)
3552                 main_body = 0;
3553         else
3554                 main_body = par->BeginningOfMainBody();
3555
3556         // gets paragraph main font
3557         if (main_body > 0)
3558                 font1 = style.labelfont;
3559         else
3560                 font1 = style.font;
3561
3562         char_line_count = depth;
3563         if(!style.free_spacing)
3564                 for (j = 0; j < depth; ++j)
3565                         os << ' ';
3566
3567         // parsing main loop
3568         for (LyXParagraph::size_type i = 0;
3569              i < par->size(); ++i) {
3570                 font2 = par->getFont(i);
3571
3572                 // handle <emphasis> tag
3573                 if (font1.emph() != font2.emph() && i) {
3574                         if (font2.emph() == LyXFont::ON) {
3575                                 os << "<emphasis>";
3576                                 emph_flag= true;
3577                         }else {
3578                                 os << "</emphasis>";
3579                                 emph_flag= false;
3580                         }
3581                 }
3582       
3583                 c = par->GetChar(i);
3584
3585                 if (c == LyXParagraph::META_INSET) {
3586                         inset = par->GetInset(i);
3587 #ifdef HAVE_SSTREAM
3588                         ostringstream ost;
3589                         inset->DocBook(ost);
3590                         string tmp_out = ost.str().c_str();
3591 #else
3592                         ostrstream ost;
3593                         inset->DocBook(ost);
3594                         ost << '\0';
3595                         char * ctmp = ost.str();
3596                         string tmp_out(ctmp);
3597                         delete [] ctmp;
3598 #endif
3599                         //
3600                         // This code needs some explanation:
3601                         // Two insets are treated specially
3602                         //   label if it is the first element in a command paragraph
3603                         //         desc_on == 3
3604                         //   graphics inside tables or figure floats can't go on
3605                         //   title (the equivalente in latex for this case is caption
3606                         //   and title should come first
3607                         //         desc_on == 4
3608                         //
3609                         if(desc_on!= 3 || i!= 0) {
3610                                 if(!tmp_out.empty() && tmp_out[0] == '@') {
3611                                         if(desc_on == 4)
3612                                                 extra += frontStrip(tmp_out, '@');
3613                                         else
3614                                                 os << frontStrip(tmp_out, '@');
3615                                 }
3616                                 else
3617                                         os << tmp_out;
3618                         }
3619                 } else if (font2.latex() == LyXFont::ON) {
3620                         // "TeX"-Mode on ==> SGML-Mode on.
3621                         if (c!= '\0')
3622                                 os << c;
3623                         ++char_line_count;
3624                 }
3625                 else {
3626                         string sgml_string;
3627                         if (par->linuxDocConvertChar(c, sgml_string)
3628                             && !style.free_spacing) { // in freespacing
3629                                                      // mode, spaces are
3630                                                      // non-breaking characters
3631                                 // char is ' '
3632                                 if (desc_on == 1) {
3633                                         ++char_line_count;
3634                                         os << "\n</term><listitem><para>";
3635                                         desc_on = 2;
3636                                 }
3637                                 else  {
3638                                         os << c;
3639                                 }
3640                         }
3641                         else {
3642                                 os << sgml_string;
3643                         }
3644                 }
3645                 font1 = font2;
3646         }
3647
3648         /* needed if there is an optional argument but no contents */
3649         if (main_body > 0 && main_body == par->size()) {
3650                 font1 = style.font;
3651         }
3652         if (emph_flag) {
3653                 os << "</emphasis>";
3654         }
3655         
3656         /* resets description flag correctly */
3657         switch(desc_on){
3658         case 1:
3659                 /* <term> not closed... */
3660                 os << "</term>";
3661                 break;
3662         }
3663         os << '\n';
3664 }
3665 #else
3666 void Buffer::SimpleDocBookOnePar(string & file, string & extra,
3667                                  LyXParagraph * par, int & desc_on,
3668                                  int const depth) 
3669 {
3670         if (par->table) {
3671                 par->SimpleDocBookOneTablePar(file, extra, desc_on, depth);
3672                 return;
3673         }
3674         LyXFont font1, font2;
3675         char c;
3676         Inset * inset;
3677         LyXParagraph::size_type main_body;
3678         int j;
3679         string emph= "emphasis";
3680         bool emph_flag= false;
3681         int char_line_count= 0;
3682
3683         LyXLayout const & style = textclasslist.Style(params.textclass,
3684                                                       par->GetLayout());
3685
3686         if (style.labeltype != LABEL_MANUAL)
3687                 main_body = 0;
3688         else
3689                 main_body = par->BeginningOfMainBody();
3690
3691         /* gets paragraph main font */
3692         if (main_body > 0)
3693                 font1 = style.labelfont;
3694         else
3695                 font1 = style.font;
3696
3697         char_line_count = depth;
3698         if(!style.free_spacing)
3699                 for (j = 0; j < depth; ++j)
3700                         file += ' ';
3701
3702         /* parsing main loop */
3703         for (LyXParagraph::size_type i = 0;
3704              i < par->size(); ++i) {
3705                 font2 = par->getFont(i);
3706
3707                 /* handle <emphasis> tag */
3708                 if (font1.emph() != font2.emph() && i) {
3709                         if (font2.emph() == LyXFont::ON) {
3710                                 file += "<emphasis>";
3711                                 emph_flag= true;
3712                         }else {
3713                                 file += "</emphasis>";
3714                                 emph_flag= false;
3715                         }
3716                 }
3717       
3718                 c = par->GetChar(i);
3719
3720                 if (c == LyXParagraph::META_INSET) {
3721                         inset = par->GetInset(i);
3722 #ifdef USE_OSTREAM_ONLY
3723 #ifdef HAVE_SSTREAM
3724                         ostringstream ost;
3725                         inset->DocBook(ost);
3726                         string tmp_out = ost.str().c_str();
3727 #else
3728                         ostrstream ost;
3729                         inset->DocBook(ost);
3730                         ost << '\0';
3731                         char * ctmp = ost.str();
3732                         string tmp_out(ctmp);
3733                         delete [] ctmp;
3734 #endif
3735 #else
3736                         string tmp_out;
3737                         inset->DocBook(tmp_out);
3738 #endif
3739                         //
3740                         // This code needs some explanation:
3741                         // Two insets are treated specially
3742                         //   label if it is the first element in a command paragraph
3743                         //         desc_on == 3
3744                         //   graphics inside tables or figure floats can't go on
3745                         //   title (the equivalente in latex for this case is caption
3746                         //   and title should come first
3747                         //         desc_on == 4
3748                         //
3749                         if(desc_on!= 3 || i!= 0) {
3750                                 if(!tmp_out.empty() && tmp_out[0] == '@') {
3751                                         if(desc_on == 4)
3752                                                 extra += frontStrip(tmp_out, '@');
3753                                         else
3754                                                 file += frontStrip(tmp_out, '@');
3755                                 }
3756                                 else
3757                                         file += tmp_out;
3758                         }
3759                 } else if (font2.latex() == LyXFont::ON) {
3760                         // "TeX"-Mode on ==> SGML-Mode on.
3761                         if (c!= '\0')
3762                                 file += c;
3763                         ++char_line_count;
3764                 }
3765                 else {
3766                         string sgml_string;
3767                         if (par->linuxDocConvertChar(c, sgml_string)
3768                             && !style.free_spacing) { // in freespacing
3769                                                      // mode, spaces are
3770                                                      // non-breaking characters
3771                                 // char is ' '
3772                                 if (desc_on == 1) {
3773                                         ++char_line_count;
3774                                         file += '\n';
3775                                         file += "</term><listitem><para>";
3776                                         desc_on = 2;
3777                                 }
3778                                 else  {
3779                                         file += c;
3780                                 }
3781                         }
3782                         else {
3783                                 file += sgml_string;
3784                         }
3785                 }
3786                 font1 = font2;
3787         }
3788
3789         /* needed if there is an optional argument but no contents */
3790         if (main_body > 0 && main_body == par->size()) {
3791                 font1 = style.font;
3792         }
3793         if (emph_flag) {
3794                 file += "</emphasis>";
3795         }
3796         
3797         /* resets description flag correctly */
3798         switch(desc_on){
3799         case 1:
3800                 /* <term> not closed... */
3801                 file += "</term>";
3802                 break;
3803         }
3804         file += '\n';
3805 }
3806 #endif
3807
3808
3809 int Buffer::runLaTeX()
3810 {
3811         if (!users->text) return 0;
3812
3813         ProhibitInput();
3814
3815         // get LaTeX-Filename
3816         string name = getLatexName();
3817
3818         string path = OnlyPath(filename);
3819
3820         string org_path = path;
3821         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3822                 path = tmppath;  
3823         }
3824
3825         Path p(path); // path to LaTeX file
3826         users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));   
3827
3828         // Remove all error insets
3829         bool a = users->removeAutoInsets();
3830
3831         // Always generate the LaTeX file
3832         makeLaTeXFile(name, org_path, false);
3833         markDviDirty();
3834
3835         // do the LaTex run(s)
3836         TeXErrors terr;
3837         string latex_command = lyxrc->pdf_mode ?
3838                 lyxrc->pdflatex_command : lyxrc->latex_command;
3839         LaTeX latex(latex_command, name, filepath);
3840         int res = latex.run(terr,
3841                             users->owner()->getMiniBuffer()); // running latex
3842
3843         // check return value from latex.run().
3844         if ((res & LaTeX::NO_LOGFILE)) {
3845                 WriteAlert(_("LaTeX did not work!"),
3846                            _("Missing log file:"), name);
3847         } else if ((res & LaTeX::ERRORS)) {
3848                 users->owner()->getMiniBuffer()->Set(_("Done"));
3849                 // Insert all errors as errors boxes
3850                 users->insertErrors(terr);
3851                 
3852                 // Dvi should also be kept dirty if the latex run
3853                 // ends up with errors. However it should be possible
3854                 // to view a dirty dvi too.
3855         } else {
3856                 //no errors or any other things to think about so:
3857                 users->owner()->getMiniBuffer()->Set(_("Done"));
3858                 markDviClean();
3859         }
3860
3861         // if we removed error insets before we ran LaTeX or if we inserted
3862         // error insets after we ran LaTeX this must be run:
3863         if (a || (res & LaTeX::ERRORS)){
3864                 users->redraw();
3865                 users->fitCursor();
3866                 users->updateScrollbar();
3867         }
3868         AllowInput();
3869  
3870         return latex.getNumErrors();
3871 }
3872
3873
3874 int Buffer::runLiterate()
3875 {
3876         if (!users->text) return 0;
3877
3878         ProhibitInput();
3879
3880         // get LaTeX-Filename
3881         string name = getLatexName();
3882         // get Literate-Filename
3883         string lit_name = ChangeExtension (getLatexName(), 
3884                                            lyxrc->literate_extension, true);
3885
3886         string path = OnlyPath(filename);
3887
3888         string org_path = path;
3889         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3890                 path = tmppath;  
3891         }
3892
3893         Path p(path); // path to Literate file
3894         users->owner()->getMiniBuffer()->Set(_("Running Literate..."));   
3895
3896         // Remove all error insets
3897         bool a = users->removeAutoInsets();
3898
3899         // generate the Literate file if necessary
3900         if (!isDviClean() || a) {
3901                 makeLaTeXFile(lit_name, org_path, false);
3902                 markDviDirty();
3903         }
3904
3905         string latex_command = lyxrc->pdf_mode ?
3906                 lyxrc->pdflatex_command : lyxrc->latex_command;
3907         Literate literate(latex_command, name, filepath, 
3908                           lit_name,
3909                           lyxrc->literate_command, lyxrc->literate_error_filter,
3910                           lyxrc->build_command, lyxrc->build_error_filter);
3911         TeXErrors terr;
3912         int res = literate.weave(terr, users->owner()->getMiniBuffer());
3913
3914         // check return value from literate.weave().
3915         if ((res & Literate::NO_LOGFILE)) {
3916                 WriteAlert(_("Literate command did not work!"),
3917                            _("Missing log file:"), name);
3918         } else if ((res & Literate::ERRORS)) {
3919                 users->owner()->getMiniBuffer()->Set(_("Done"));
3920                 // Insert all errors as errors boxes
3921                 users->insertErrors(terr);
3922                 
3923                 // Dvi should also be kept dirty if the latex run
3924                 // ends up with errors. However it should be possible
3925                 // to view a dirty dvi too.
3926         } else {
3927                 //no errors or any other things to think about so:
3928                 users->owner()->getMiniBuffer()->Set(_("Done"));
3929                 markDviClean();
3930         }
3931
3932         // if we removed error insets before we ran LaTeX or if we inserted
3933         // error insets after we ran LaTeX this must be run:
3934         if (a || (res & Literate::ERRORS)){
3935                 users->redraw();
3936                 users->fitCursor();
3937                 users->updateScrollbar();
3938         }
3939         AllowInput();
3940  
3941         return literate.getNumErrors();
3942 }
3943
3944
3945 int Buffer::buildProgram()
3946 {
3947         if (!users->text) return 0;
3948  
3949         ProhibitInput();
3950  
3951         // get LaTeX-Filename
3952         string name = getLatexName();
3953         // get Literate-Filename
3954         string lit_name = ChangeExtension(getLatexName(), 
3955                                           lyxrc->literate_extension, true);
3956  
3957         string path = OnlyPath(filename);
3958  
3959         string org_path = path;
3960         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3961                 path = tmppath;  
3962         }
3963  
3964         Path p(path); // path to Literate file
3965         users->owner()->getMiniBuffer()->Set(_("Building Program..."));   
3966  
3967         // Remove all error insets
3968         bool a = users->removeAutoInsets();
3969  
3970         // generate the LaTeX file if necessary
3971         if (!isNwClean() || a) {
3972                 makeLaTeXFile(lit_name, org_path, false);
3973                 markNwDirty();
3974         }
3975
3976         string latex_command = lyxrc->pdf_mode ?
3977                 lyxrc->pdflatex_command : lyxrc->latex_command;
3978         Literate literate(latex_command, name, filepath, 
3979                           lit_name,
3980                           lyxrc->literate_command, lyxrc->literate_error_filter,
3981                           lyxrc->build_command, lyxrc->build_error_filter);
3982         TeXErrors terr;
3983         int res = literate.build(terr, users->owner()->getMiniBuffer());
3984  
3985         // check return value from literate.build().
3986         if ((res & Literate::NO_LOGFILE)) {
3987                 WriteAlert(_("Build did not work!"),
3988                            _("Missing log file:"), name);
3989         } else if ((res & Literate::ERRORS)) {
3990                 users->owner()->getMiniBuffer()->Set(_("Done"));
3991                 // Insert all errors as errors boxes
3992                 users->insertErrors(terr);
3993                 
3994                 // Literate files should also be kept dirty if the literate 
3995                 // command run ends up with errors.
3996         } else {
3997                 //no errors or any other things to think about so:
3998                 users->owner()->getMiniBuffer()->Set(_("Done"));
3999                 markNwClean();
4000         }
4001  
4002         // if we removed error insets before we ran Literate/Build or if we inserted
4003         // error insets after we ran Literate/Build this must be run:
4004         if (a || (res & Literate::ERRORS)){
4005                 users->redraw();
4006                 users->fitCursor();
4007                 users->updateScrollbar();
4008         }
4009         AllowInput();
4010
4011         return literate.getNumErrors();
4012 }
4013
4014
4015 // This should be enabled when the Chktex class is implemented. (Asger)
4016 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
4017 // Other flags: -wall -v0 -x
4018 int Buffer::runChktex()
4019 {
4020         if (!users->text) return 0;
4021
4022         ProhibitInput();
4023
4024         // get LaTeX-Filename
4025         string name = getLatexName();
4026         string path = OnlyPath(filename);
4027
4028         string org_path = path;
4029         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
4030                 path = tmppath;  
4031         }
4032
4033         Path p(path); // path to LaTeX file
4034         users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
4035
4036         // Remove all error insets
4037         bool a = users->removeAutoInsets();
4038
4039         // Generate the LaTeX file if neccessary
4040         if (!isDviClean() || a) {
4041                 makeLaTeXFile(name, org_path, false);
4042                 markDviDirty();
4043         }
4044
4045         TeXErrors terr;
4046         Chktex chktex(lyxrc->chktex_command, name, filepath);
4047         int res = chktex.run(terr); // run chktex
4048
4049         if (res == -1) {
4050                 WriteAlert(_("chktex did not work!"),
4051                            _("Could not run with file:"), name);
4052         } else if (res > 0) {
4053                 // Insert all errors as errors boxes
4054                 users->insertErrors(terr);
4055         }
4056
4057         // if we removed error insets before we ran chktex or if we inserted
4058         // error insets after we ran chktex, this must be run:
4059         if (a || res){
4060                 users->redraw();
4061                 users->fitCursor();
4062                 users->updateScrollbar();
4063         }
4064         AllowInput();
4065
4066         return res;
4067 }
4068
4069
4070 #if 0
4071 void Buffer::RoffAsciiTable(ostream & os, LyXParagraph * par)
4072 {
4073         LyXFont font1(LyXFont::ALL_INHERIT);
4074         LyXFont font2;
4075         Inset * inset;
4076         LyXParagraph::size_type i;
4077         int j, cell = 0;
4078         char c;
4079         
4080         string fname1 = TmpFileName(string(), "RAT1");
4081         string fname2 = TmpFileName(string(), "RAT2");
4082
4083         ofstream ofs(fname1.c_str());
4084         if (!ofs) {
4085                 WriteAlert(_("LYX_ERROR:"),
4086                            _("Cannot open temporary file:"), fname1);
4087                 return;
4088         }
4089         par->table->RoffEndOfCell(ofs, -1);
4090         for (i = 0; i < par->size(); ++i) {
4091                 c = par->GetChar(i);
4092                 if (par->table->IsContRow(cell)) {
4093                         if (c == LyXParagraph::META_NEWLINE)
4094                                 ++cell;
4095                         continue;
4096                 }
4097                 font2 = par->GetFontSettings(i);
4098                 if (font1.latex() != font2.latex()) {
4099                         if (font2.latex() != LyXFont::OFF)
4100                                 continue;
4101                 }
4102                 switch (c) {
4103                 case LyXParagraph::META_INSET:
4104                         if ((inset = par->GetInset(i))) {
4105 #if 1
4106 #ifdef HAVE_SSTREAM
4107                                 stringstresm ss(ios::in | ios::out);
4108                                 inset->Latex(ss, -1);
4109                                 ss.seekp(0);
4110                                 ss.get(c);
4111                                 while (!ss) {
4112                                         if (c == '\\')
4113                                                 ofs << "\\\\";
4114                                         else
4115                                                 ofs << c;
4116                                         ss.get(c);
4117                                 }
4118 #else
4119                                 strstream ss;
4120                                 inset->Latex(ss, -1);
4121                                 ss.seekp(0);
4122                                 ss.get(c);
4123                                 while (!ss) {
4124                                         if (c == '\\')
4125                                                 ofs << "\\\\";
4126                                         else
4127                                                 ofs << c;
4128                                         ss.get(c);
4129                                 }
4130                                 delete [] ss.str();
4131 #endif
4132 #else
4133                                 fstream fs(fname2.c_str(), ios::in|ios::out);
4134                                 if (!fs) {
4135                                         WriteAlert(_("LYX_ERROR:"),
4136                                                    _("Cannot open temporary file:"), fname2);
4137                                         ofs.close();
4138                                         remove(fname1.c_str());
4139                                         return;
4140                                 }
4141                                 inset->Latex(fs, -1);
4142                                 fs.seekp(0);
4143                                 fs.get(c);
4144                                 while(!fs) {
4145                                         if (c == '\\')
4146                                                 ofs << "\\\\";
4147                                         else
4148                                                 ofs << c;
4149                                         fs >> c;
4150                                 }
4151                                 fs.close();
4152 #endif
4153                         }
4154                         break;
4155                 case LyXParagraph::META_NEWLINE:
4156                         if (par->table->CellHasContRow(cell)>= 0)
4157                                 par->RoffContTableRows(ofs, i+1, cell);
4158                         par->table->RoffEndOfCell(ofs, cell);
4159                         ++cell;
4160                         break;
4161                 case LyXParagraph::META_HFILL: 
4162                         break;
4163 #if 0
4164                 case LyXParagraph::META_PROTECTED_SEPARATOR:
4165                         break;
4166 #endif
4167                 case '\\': 
4168                         ofs << "\\\\";
4169                         break;
4170                 default:
4171                         if (c != '\0')
4172                                 ofs << c;
4173                         else if (c == '\0')
4174                                 lyxerr.debug()
4175                                         << "RoffAsciiTable:"
4176                                         " NULL char in structure." << endl;
4177                         break;
4178                 }
4179         }
4180         par->table->RoffEndOfCell(ofs, cell);
4181         ofs.close();
4182         string cmd = lyxrc->ascii_roff_command + " >" + fname2;
4183         cmd = subst(cmd, "$$FName", fname1);
4184         Systemcalls one(Systemcalls::System, cmd);
4185         if (!(lyxerr.debugging(Debug::ROFF))) {
4186                 remove(fname1.c_str());
4187         }
4188         ifstream ifs(fname2.c_str());
4189         if (!ifs) {
4190                 WriteFSAlert(_("Error! Can't open temporary file:"), fname2);
4191                 return;
4192         }
4193         // now output the produced file
4194         os << "\n\n";
4195         ifs.get(c);
4196         if (!ifs)
4197                 WriteAlert(_("Error!"),
4198                            _("Error executing *roff command on table"));
4199         // overread leading blank lines
4200         while(!ifs && (c == '\n'))
4201                 ifs.get(c);
4202         while(!ifs) {
4203                 for(j = 0; j < par->depth; ++j)
4204                         os << "  ";
4205                 while(!ifs && (c != '\n')) {
4206                         os << c;
4207                         ifs.get(c);
4208                 }
4209                 os << '\n';
4210                 // overread trailing blank lines
4211                 while(!ifs && (c == '\n'))
4212                         ifs.get(c);
4213         }
4214         ifs.close();
4215         remove(fname2.c_str());
4216 }
4217 #endif
4218
4219         
4220 /// changed Heinrich Bauer, 23/03/98
4221 bool Buffer::isDviClean() const
4222 {
4223   if (lyxrc->use_tempdir)
4224     return dvi_clean_tmpd;
4225   else
4226     return dvi_clean_orgd;
4227 }
4228
4229  
4230 /// changed Heinrich Bauer, 23/03/98
4231 void Buffer::markDviClean()
4232 {
4233   if (lyxrc->use_tempdir)
4234     dvi_clean_tmpd = true;
4235   else
4236     dvi_clean_orgd = true;
4237 }
4238
4239
4240 /// changed Heinrich Bauer, 23/03/98
4241 void Buffer::markDviDirty()
4242 {
4243   if (lyxrc->use_tempdir)
4244     dvi_clean_tmpd = false;
4245   else
4246     dvi_clean_orgd = false;
4247 }
4248
4249
4250 void Buffer::validate(LaTeXFeatures & features) const
4251 {
4252         LyXParagraph * par = paragraph;
4253         LyXTextClass const & tclass = 
4254                 textclasslist.TextClass(params.textclass);
4255     
4256         // AMS Style is at document level
4257     
4258         features.amsstyle = (params.use_amsmath ||
4259                              tclass.provides(LyXTextClass::amsmath));
4260     
4261         while (par) {
4262                 // We don't use "lyxerr.debug" because of speed. (Asger)
4263                 if (lyxerr.debugging(Debug::LATEX))
4264                         lyxerr << "Paragraph: " <<  par << endl;
4265
4266                 // Now just follow the list of paragraphs and run
4267                 // validate on each of them.
4268                 par->validate(features);
4269
4270                 // and then the next paragraph
4271                 par = par->next;
4272         }
4273
4274         // the bullet shapes are buffer level not paragraph level
4275         // so they are tested here
4276         for (int i = 0; i < 4; ++i) {
4277                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
4278                         int font = params.user_defined_bullets[i].getFont();
4279                         if (font == 0) {
4280                                 int c = params
4281                                         .user_defined_bullets[i]
4282                                         .getCharacter();
4283                                 if (c == 16
4284                                    || c == 17
4285                                    || c == 25
4286                                    || c == 26
4287                                    || c == 31) {
4288                                         features.latexsym = true;
4289                                 }
4290                         }
4291                         if (font == 1) {
4292                                 features.amssymb = true;
4293                         }
4294                         else if ((font >= 2 && font <= 5)) {
4295                                 features.pifont = true;
4296                         }
4297                 }
4298         }
4299         
4300         if (lyxerr.debugging(Debug::LATEX)) {
4301                 features.showStruct(params);
4302         }
4303 }
4304
4305
4306 void Buffer::setPaperStuff()
4307 {
4308         params.papersize = BufferParams::PAPER_DEFAULT;
4309         char c1 = params.paperpackage;
4310         if (c1 == BufferParams::PACKAGE_NONE) {
4311                 char c2 = params.papersize2;
4312                 if (c2 == BufferParams::VM_PAPER_USLETTER)
4313                         params.papersize = BufferParams::PAPER_USLETTER;
4314                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
4315                         params.papersize = BufferParams::PAPER_LEGALPAPER;
4316                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
4317                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
4318                 else if (c2 == BufferParams::VM_PAPER_A3)
4319                         params.papersize = BufferParams::PAPER_A3PAPER;
4320                 else if (c2 == BufferParams::VM_PAPER_A4)
4321                         params.papersize = BufferParams::PAPER_A4PAPER;
4322                 else if (c2 == BufferParams::VM_PAPER_A5)
4323                         params.papersize = BufferParams::PAPER_A5PAPER;
4324                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
4325                          (c2 == BufferParams::VM_PAPER_B5))
4326                         params.papersize = BufferParams::PAPER_B5PAPER;
4327         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
4328                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
4329                 params.papersize = BufferParams::PAPER_A4PAPER;
4330 }
4331
4332
4333 // This function should be in Buffer because it's a buffer's property (ale)
4334 string Buffer::getIncludeonlyList(char delim)
4335 {
4336         string lst;
4337         LyXParagraph * par = paragraph;
4338         LyXParagraph::size_type pos;
4339         Inset * inset;
4340         while (par){
4341                 pos = -1;
4342                 while ((inset = par->ReturnNextInsetPointer(pos))){
4343                         if (inset->LyxCode() == Inset::INCLUDE_CODE) {
4344                                 InsetInclude * insetinc = 
4345                                         static_cast<InsetInclude*>(inset);
4346                                 if (insetinc->isInclude() 
4347                                     && insetinc->isNoLoad()) {
4348                                         if (!lst.empty())
4349                                                 lst += delim;
4350                                         lst += ChangeExtension(insetinc->getContents(), string(), true);
4351                                 }
4352                         }
4353                         ++pos;
4354                 } 
4355                 par = par->next;
4356         }
4357         lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
4358         return lst;
4359 }
4360
4361
4362 // This is also a buffer property (ale)
4363 string Buffer::getReferenceList(char delim)
4364 {
4365         /// if this is a child document and the parent is already loaded
4366         /// Use the parent's list instead  [ale990407]
4367         if (!params.parentname.empty()
4368             && bufferlist.exists(params.parentname)) {
4369                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
4370                 if (tmp)
4371                         return tmp->getReferenceList(delim);
4372         }
4373
4374         LyXParagraph * par = paragraph;
4375         LyXParagraph::size_type pos;
4376         Inset * inset;
4377         string lst;
4378         while (par) {
4379                 pos = -1;
4380                 while ((inset = par->ReturnNextInsetPointer(pos))){     
4381                         for (int i = 0; i < inset->GetNumberOfLabels(); ++i) {
4382                                 if (!lst.empty())
4383                                         lst += delim;
4384                                 lst += inset->getLabel(i);
4385                         }
4386                         ++pos;
4387                 }
4388                 par = par->next;
4389         }
4390         lyxerr.debug() << "References(" <<  lst << ")" << endl;
4391         return lst;
4392 }
4393
4394
4395 // This is also a buffer property (ale)
4396 string Buffer::getBibkeyList(char delim)
4397 {
4398         /// if this is a child document and the parent is already loaded
4399         /// Use the parent's list instead  [ale990412]
4400         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
4401                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
4402                 if (tmp)
4403                         return tmp->getBibkeyList(delim);
4404         }
4405
4406         string bibkeys;
4407         LyXParagraph * par = paragraph;
4408         while (par) {
4409                 if (par->bibkey) {
4410                         if (!bibkeys.empty())
4411                                 bibkeys += delim;
4412                         bibkeys += par->bibkey->getContents();
4413                 }
4414                 par = par->next;
4415         }
4416
4417         // Might be either using bibtex or a child has bibliography
4418         if (bibkeys.empty()) {
4419                 par = paragraph;
4420                 while (par) {
4421                         Inset * inset;
4422                         LyXParagraph::size_type pos = -1;
4423
4424                         // Search for Bibtex or Include inset
4425                         while ((inset = par->ReturnNextInsetPointer(pos))) {
4426                                 if (inset-> LyxCode() == Inset::BIBTEX_CODE) {
4427                                         if (!bibkeys.empty())
4428                                                 bibkeys += delim;
4429                                         bibkeys += static_cast<InsetBibtex*>(inset)->getKeys(delim);
4430                                 } else if (inset-> LyxCode() == Inset::INCLUDE_CODE) {
4431                                         string bk = static_cast<InsetInclude*>(inset)->getKeys(delim);
4432                                         if (!bk.empty()) {
4433                                                 if (!bibkeys.empty())
4434                                                         bibkeys += delim;
4435                                                 bibkeys += bk;
4436                                         }
4437                                 }
4438                                 ++pos;
4439                         }
4440                         par = par->next;
4441                 }
4442         }
4443  
4444         lyxerr.debug() << "Bibkeys(" << bibkeys << ")" << endl;
4445         return bibkeys;
4446 }
4447
4448
4449 bool Buffer::isDepClean(string const & name) const
4450 {
4451         DEPCLEAN * item = dep_clean;
4452         while (item && item->master != name)
4453                 item = item->next;
4454         if (!item) return true;
4455         return item->clean;
4456 }
4457
4458
4459 void Buffer::markDepClean(string const & name)
4460 {
4461         if (!dep_clean) {
4462                 dep_clean = new DEPCLEAN;
4463                 dep_clean->clean = true;
4464                 dep_clean->master = name;
4465                 dep_clean->next = 0;
4466         } else {
4467                 DEPCLEAN* item = dep_clean;
4468                 while (item && item->master != name)
4469                         item = item->next;
4470                 if (item) {
4471                         item->clean = true;
4472                 } else {
4473                         item = new DEPCLEAN;
4474                         item->clean = true;
4475                         item->master = name;
4476                         item->next = 0;;
4477                 }
4478         }
4479 }
4480
4481
4482 void Buffer::Dispatch(string const & command)
4483 {
4484         // Split command string into command and argument
4485         string cmd, line = frontStrip(command);
4486         string arg = strip(frontStrip(split(line, cmd, ' ')));
4487
4488         Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
4489 }
4490
4491
4492 void Buffer::Dispatch(int action, string const & argument)
4493 {
4494         switch (action) {
4495                 case LFUN_EXPORT: 
4496                         MenuExport(this, argument);
4497                         break;
4498
4499                 default:
4500                         lyxerr << "A truly unknown func!" << endl;
4501                 break;
4502
4503         } // end of switch
4504 }