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