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