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