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