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