]> git.lyx.org Git - lyx.git/blob - src/buffer.C
white-space changes, removed definitions.h several enum changes because of this,...
[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.exist() || !fi.readable()) {
223                 WriteAlert(_("Error!"),
224                            _("Cannot open specified file:"),
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                 "#This file was created by <%s> %s",
1206                 userName.c_str(),(char*)date());
1207         fprintf(file,
1208                 "#LyX 1.0 (C) 1995-1999 Matthias Ettrich"
1209                 " and the LyX Team\n");
1210         
1211         // at the very beginning the used lyx format
1212         fprintf(file, "\\lyxformat %.2f\n", LYX_FORMAT);
1213
1214         // now write out the buffer parameters.
1215         params.writeFile(file);
1216
1217         char footnoteflag = 0;
1218         char depth = 0;
1219
1220         // this will write out all the paragraphs
1221         // using recursive descent.
1222         paragraph->writeFile(file, params, footnoteflag, depth);
1223
1224         // Write marker that shows file is complete
1225         fprintf(file, "\n\\the_end\n");
1226         if (file.close()) {
1227                 if (flag)
1228                         lyxerr << _("Error! Could not close file properly: ")
1229                                << filename << endl;
1230                 else
1231                         WriteFSAlert(_("Error! Could not close file properly: "),
1232                                      filename);
1233                 return false;
1234         }
1235         return true;
1236 }
1237
1238
1239 void Buffer::writeFileAscii(string const & filename, int linelen) 
1240 {
1241         FilePtr file(filename, FilePtr::write);
1242         LyXFont
1243                 font1, font2;
1244         Inset * inset;
1245         LyXParagraph * par = paragraph;
1246         char
1247                 c,
1248                 footnoteflag = 0,
1249                 depth = 0;
1250
1251         string
1252                 fname1,
1253                 tmp;
1254
1255         LyXParagraph::size_type i;
1256         int
1257                 j, h,
1258                 ltype = 0,
1259                 ltype_depth = 0,
1260                 noparbreak = 0,
1261                 islatex = 0,
1262                 * clen = 0,
1263                 actcell = 0,
1264                 actpos = 0,
1265                 cell = 0,
1266                 cells = 0,
1267                 currlinelen = 0;
1268         long
1269                 fpos = 0;
1270         bool
1271                 ref_printed = false;
1272    
1273    
1274         if (!file()) {
1275                 WriteFSAlert(_("Error: Cannot write file:"), filename);
1276                 return;
1277         }
1278         fname1 = TmpFileName();
1279         while (par) {
1280                 noparbreak = 0;
1281                 islatex = 0;
1282                 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1283                     !par->previous ||
1284                     par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE){
1285          
1286                         /* begins a footnote environment ? */ 
1287                         if (footnoteflag != par->footnoteflag) {
1288                                 footnoteflag = par->footnoteflag;
1289                                 if (footnoteflag) {
1290                                         j = strlen(string_footnotekinds[par->footnotekind])+4;
1291                                         if (currlinelen+j > linelen)
1292                                                 fprintf(file, "\n");
1293                                         fprintf(file, "([%s] ", 
1294                                                 string_footnotekinds[par->footnotekind]);
1295                                         currlinelen += j;
1296                                 }
1297                         }
1298          
1299                         /* begins or ends a deeper area ?*/ 
1300                         if (depth != par->depth) {
1301                                 if (par->depth > depth) {
1302                                         while (par->depth > depth) {
1303                                                 depth++;
1304                                         }
1305                                 }
1306                                 else {
1307                                         while (par->depth < depth) {
1308                                                 depth--;
1309                                         }
1310                                 }
1311                         }
1312          
1313                         /* First write the layout */
1314                         tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1315                         if (tmp == "Itemize") {
1316                                 ltype = 1;
1317                                 ltype_depth = depth+1;
1318                         } else if (tmp == "Enumerate") {
1319                                 ltype = 2;
1320                                 ltype_depth = depth+1;
1321                         } else if (strstr(tmp.c_str(), "ection")) {
1322                                 ltype = 3;
1323                                 ltype_depth = depth+1;
1324                         } else if (strstr(tmp.c_str(), "aragraph")) {
1325                                 ltype = 4;
1326                                 ltype_depth = depth+1;
1327                         } else if (tmp == "Description") {
1328                                 ltype = 5;
1329                                 ltype_depth = depth+1;
1330                         } else if (tmp == "Abstract") {
1331                                 ltype = 6;
1332                                 ltype_depth = 0;
1333                         } else if (tmp == "Bibliography") {
1334                                 ltype = 7;
1335                                 ltype_depth = 0;
1336                         } else {
1337                                 ltype = 0;
1338                                 ltype_depth = 0;
1339                         }
1340          
1341                         /* maybe some vertical spaces */ 
1342
1343                         /* the labelwidthstring used in lists */ 
1344          
1345                         /* some lines? */ 
1346          
1347                         /* some pagebreaks? */ 
1348          
1349                         /* noindent ? */ 
1350          
1351                         /* what about the alignment */ 
1352                 }
1353                 else {
1354                         /* dummy layout, that means a footnote ended */ 
1355                         footnoteflag = LyXParagraph::NO_FOOTNOTE;
1356                         fprintf(file, ") ");
1357                         noparbreak = 1;
1358                 }
1359       
1360                 /* It might be a table */ 
1361                 if (par->table){
1362                         if (!lyxrc->ascii_roff_command.empty() &&
1363                             lyxrc->ascii_roff_command != "none") {
1364                                 RoffAsciiTable(file, par);
1365                                 par = par->next;
1366                                 continue;
1367                         }
1368                         cell = 1;
1369                         actcell = 0;
1370                         cells = par->table->columns;
1371                         clen = new int [cells];
1372                         memset(clen, 0, sizeof(int)*cells);
1373                         for (i = 0, j = 0, h = 1; i < par->size(); ++i, ++h) {
1374                                 c = par->GetChar(i);
1375                                 if (c == LyXParagraph::META_INSET) {
1376                                         if ((inset = par->GetInset(i))) {
1377                                                 FilePtr fp(fname1,
1378                                                            FilePtr::write);
1379                                                 if (!fp()) {
1380                                                         WriteFSAlert(_("Error: Cannot open temporary file:"), fname1);
1381                                                         return;
1382                                                 }
1383                                                 inset->Latex(fp,-1);
1384                                                 h += ftell(fp) - 1;
1385                                                 remove(fname1.c_str());
1386                                         }
1387                                 } else if (c == LyXParagraph::META_NEWLINE) {
1388                                         if (clen[j] < h)
1389                                                 clen[j] = h;
1390                                         h = 0;
1391                                         j = (++j) % par->table->NumberOfCellsInRow(actcell);
1392                                         actcell++;
1393                                 }
1394                         }
1395                         if (clen[j] < h)
1396                                 clen[j] = h;
1397                 }
1398       
1399                 font1 = LyXFont(LyXFont::ALL_INHERIT);
1400                 actcell = 0;
1401                 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1402                         if (!i && !footnoteflag && !noparbreak){
1403                                 fprintf(file, "\n\n");
1404                                 for(j = 0; j<depth; j++)
1405                                         fprintf(file, "  ");
1406                                 currlinelen = depth*2;
1407                                 switch(ltype) {
1408                                 case 0: /* Standart */
1409                                 case 4: /* (Sub)Paragraph */
1410                                 case 5: /* Description */
1411                                         break;
1412                                 case 6: /* Abstract */
1413                                         fprintf(file, "Abstract\n\n");
1414                                         break;
1415                                 case 7: /* Bibliography */
1416                                         if (!ref_printed) {
1417                                                 fprintf(file, "References\n\n");
1418                                                 ref_printed = true;
1419                                         }
1420                                         break;
1421                                 default:
1422                                         fprintf(file, "%s ", par->labelstring.c_str());
1423                                         break;
1424                                 }
1425                                 if (ltype_depth > depth) {
1426                                         for(j = ltype_depth-1; j>depth; j--)
1427                                                 fprintf(file, "  ");
1428                                         currlinelen += (ltype_depth-depth)*2;
1429                                 }
1430                                 if (par->table) {
1431                                         for(j = 0;j<cells;j++) {
1432                                                 fputc('+', file);
1433                                                 for(h = 0; h<(clen[j]+1); h++)
1434                                                         fputc('-', file);
1435                                         }
1436                                         fprintf(file, "+\n");
1437                                         for(j = 0; j<depth; j++)
1438                                                 fprintf(file, "  ");
1439                                         currlinelen = depth*2;
1440                                         if (ltype_depth > depth) {
1441                                                 for(j = ltype_depth; j>depth; j--)
1442                                                         fprintf(file, "  ");
1443                                                 currlinelen += (ltype_depth-depth)*2;
1444                                         }
1445                                         fprintf(file, "| ");
1446                                 }
1447                         }
1448                         font2 = par->GetFontSettings(i);
1449                         if (font1.latex() != font2.latex()) {
1450                                 if (font2.latex() == LyXFont::OFF)
1451                                         islatex = 0;
1452                                 else
1453                                         islatex = 1;
1454                         }
1455                         else {
1456                                 islatex = 0;
1457                         }
1458                         c = par->GetChar(i);
1459                         if (islatex)
1460                                 continue;
1461                         switch (c) {
1462                         case LyXParagraph::META_INSET:
1463                                 if ((inset = par->GetInset(i))) {
1464                                         fpos = ftell(file);
1465                                         inset->Latex(file,-1);
1466                                         currlinelen += (ftell(file) - fpos);
1467                                         actpos += (ftell(file) - fpos) - 1;
1468                                 }
1469                                 break;
1470                         case LyXParagraph::META_NEWLINE:
1471                                 if (par->table) {
1472                                         if (par->table->NumberOfCellsInRow(actcell) <= cell) {
1473                                                 for(j = actpos;j<clen[cell-1];j++)
1474                                                         fputc(' ', file);
1475                                                 fprintf(file, " |\n");
1476                                                 for(j = 0; j<depth; j++)
1477                                                         fprintf(file, "  ");
1478                                                 currlinelen = depth*2;
1479                                                 if (ltype_depth > depth) {
1480                                                         for(j = ltype_depth; j>depth; j--)
1481                                                                 fprintf(file, "  ");
1482                                                         currlinelen += (ltype_depth-depth)*2;
1483                                                 }
1484                                                 for(j = 0;j<cells;j++) {
1485                                                         fputc('+', file);
1486                                                         for(h = 0; h<(clen[j]+1); h++)
1487                                                                 fputc('-', file);
1488                                                 }
1489                                                 fprintf(file, "+\n");
1490                                                 for(j = 0; j<depth; j++)
1491                                                         fprintf(file, "  ");
1492                                                 currlinelen = depth*2;
1493                                                 if (ltype_depth > depth) {
1494                                                         for(j = ltype_depth; j>depth; j--)
1495                                                                 fprintf(file, "  ");
1496                                                         currlinelen += (ltype_depth-depth)*2;
1497                                                 }
1498                                                 fprintf(file, "| ");
1499                                                 cell = 1;
1500                                         } else {
1501                                                 for(j = actpos; j<clen[cell-1]; j++)
1502                                                         fputc(' ', file);
1503                                                 fprintf(file, " | ");
1504                                                 cell++;
1505                                         }
1506                                         actcell++;
1507                                         currlinelen = actpos = 0;
1508                                 } else {
1509                                         fprintf(file, "\n");
1510                                         for(j = 0; j<depth; j++)
1511                                                 fprintf(file, "  ");
1512                                         currlinelen = depth*2;
1513                                         if (ltype_depth > depth) {
1514                                                 for(j = ltype_depth; j>depth; j--)
1515                                                         fprintf(file, "  ");
1516                                                 currlinelen += (ltype_depth-depth)*2;
1517                                         }
1518                                 }
1519                                 break;
1520                         case LyXParagraph::META_HFILL: 
1521                                 fprintf(file, "\t");
1522                                 break;
1523                         case LyXParagraph::META_PROTECTED_SEPARATOR:
1524                                 fprintf(file, " ");
1525                                 break;
1526                         case '\\': 
1527                                 fprintf(file, "\\");
1528                                 break;
1529                         default:
1530                                 if (currlinelen > linelen - 10
1531                                     && c == ' ' && i + 2 < par->size()) {
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;
1538                                                     j > depth; --j)
1539                                                         fprintf(file, "  ");
1540                                                 currlinelen += (ltype_depth-depth)*2;
1541                                         }
1542                                 } else if (c != '\0')
1543                                         fprintf(file, "%c", c);
1544                                 else if (c == '\0')
1545                                         lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1546                                 currlinelen++;
1547                                 break;
1548                         }
1549                 }
1550                 if (par->table) {
1551                         for(j = actpos;j<clen[cell-1];j++)
1552                                 fputc(' ', file);
1553                         fprintf(file, " |\n");
1554                         for(j = 0; j<depth; j++)
1555                                 fprintf(file, "  ");
1556                         currlinelen = depth*2;
1557                         if (ltype_depth > depth) {
1558                                 for(j = ltype_depth; j>depth; j--)
1559                                         fprintf(file, "  ");
1560                                 currlinelen += (ltype_depth-depth)*2;
1561                         }
1562                         for(j = 0;j<cells;j++) {
1563                                 fputc('+', file);
1564                                 for(h = 0; h<(clen[j]+1); h++)
1565                                         fputc('-', file);
1566                         }
1567                         fprintf(file, "+\n");
1568                         delete [] clen;    
1569                 }      
1570                 par = par->next;
1571         }
1572    
1573         fprintf(file, "\n");
1574 }
1575
1576
1577 void Buffer::makeLaTeXFile(string const & filename, 
1578                            string const & original_path,
1579                            bool nice, bool only_body)
1580 {
1581         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1582         params.textclass = GetCurrentTextClass();
1583         niceFile = nice; // this will be used by Insetincludes.
1584
1585         tex_code_break_column = lyxrc->ascii_linelen;
1586
1587         LyXTextClass const & tclass =
1588                 textclasslist.TextClass(params.textclass);
1589   
1590         FilePtr file(filename, FilePtr::write);
1591         if (!file()) {
1592                 WriteFSAlert(_("Error: Cannot write file:"), filename);
1593                 return;
1594         }
1595
1596         // validate the buffer.
1597         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1598         LaTeXFeatures features(tclass.numLayouts());
1599         validate(features);
1600         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1601         
1602         texrow.reset();
1603         // The starting paragraph of the coming rows is the 
1604         // first paragraph of the document. (Asger)
1605         texrow.start(paragraph, 0);
1606
1607         string userName(getUserName());
1608         string LFile;
1609         
1610         if (!only_body && nice) {
1611                 LFile += "%% This LaTeX-file was created by <";
1612                 LFile += userName + "> " + (char*)date();
1613                 LFile += "%% LyX 1.0 (C) 1995-1999 by Matthias Ettrich and the LyX Team\n";
1614                 LFile += "\n%% Do not edit this file unless you know what you are doing.\n";
1615                 texrow.newline();
1616                 texrow.newline();
1617                 texrow.newline();
1618                 texrow.newline();
1619         }
1620         lyxerr.debug() << "lyx header finished" << endl;
1621         // There are a few differences between nice LaTeX and usual files:
1622         // usual is \batchmode, uses \listfiles and has a 
1623         // special input@path to allow the including of figures
1624         // with either \input or \includegraphics (what figinsets do).
1625         // batchmode is not set if there is a tex_code_break_column.
1626         // In this case somebody is interested in the generated LaTeX,
1627         // so this is OK. input@path is set when the actual parameter
1628         // original_path is set. This is done for usual tex-file, but not
1629         // for nice-latex-file. (Matthias 250696)
1630         if (!only_body) {
1631                 if (!nice){
1632                         // code for usual, NOT nice-latex-file
1633                         LFile += "\\batchmode\n"; // changed
1634                         // from \nonstopmode
1635                         texrow.newline();
1636                         // We don't need listfiles anymore
1637                         //LFile += "\\listfiles\n";
1638                         //texrow.newline();
1639                 }
1640                 if (!original_path.empty()) {
1641                         LFile += "\\makeatletter\n";
1642                         texrow.newline();
1643                         LFile += "\\def\\input@path{{" + original_path
1644                                  + "/}}\n";
1645                         texrow.newline();
1646                         LFile += "\\makeatother\n";
1647                         texrow.newline();
1648                 }
1649                 
1650                 LFile += "\\documentclass";
1651                 
1652                 string options; // the document class options.
1653                 
1654                 if (tokenPos(tclass.opt_fontsize(), '|', params.fontsize) >= 0) {
1655                         // only write if existing in list (and not default)
1656                         options += params.fontsize;
1657                         options += "pt,";
1658                 }
1659                 
1660                 
1661                 if (!params.use_geometry &&
1662                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1663                         switch (params.papersize) {
1664                         case BufferParams::PAPER_A4PAPER:
1665                                 options += "a4paper,";
1666                                 break;
1667                         case BufferParams::PAPER_USLETTER:
1668                                 options += "letterpaper,";
1669                                 break;
1670                         case BufferParams::PAPER_A5PAPER:
1671                                 options += "a5paper,";
1672                                 break;
1673                         case BufferParams::PAPER_B5PAPER:
1674                                 options += "b5paper,";
1675                                 break;
1676                         case BufferParams::PAPER_EXECUTIVEPAPER:
1677                                 options += "executivepaper,";
1678                                 break;
1679                         case BufferParams::PAPER_LEGALPAPER:
1680                                 options += "legalpaper,";
1681                                 break;
1682                         }
1683                 }
1684
1685                 // if needed
1686                 if (params.sides != tclass.sides()) {
1687                         if (params.sides == 2)
1688                                 options += "twoside,";
1689                         else
1690                                 options += "oneside,";
1691                 }
1692
1693                 // if needed
1694                 if (params.columns != tclass.columns()) {
1695                         if (params.columns == 2)
1696                                 options += "twocolumn,";
1697                         else
1698                                 options += "onecolumn,";
1699                 }
1700
1701                 if (!params.use_geometry && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1702                         options += "landscape,";
1703                 
1704                 // language should be a parameter to \documentclass
1705                 if (params.language != "default") {
1706                         options += params.language + ',';
1707                 }
1708                 
1709                 // the user-defined options
1710                 if (!params.options.empty()) {
1711                         options += params.options + ',';
1712                 }
1713                 
1714                 if (!options.empty()){
1715                         options = strip(options, ',');
1716                         LFile += '[';
1717                         LFile += options;
1718                         LFile += ']';
1719                 }
1720                 
1721                 LFile += '{';
1722                 LFile += textclasslist.LatexnameOfClass(params.textclass);
1723                 LFile += "}\n";
1724                 texrow.newline();
1725                 // end of \documentclass defs
1726                 
1727                 // font selection must be done before loading fontenc.sty
1728                 if (params.fonts != "default") {
1729                         LFile += "\\usepackage{" + params.fonts + "}\n";
1730                         texrow.newline();
1731                 }
1732                 // this one is not per buffer
1733                 if (lyxrc->fontenc != "default") {
1734                         LFile += "\\usepackage[" + lyxrc->fontenc
1735                                  + "]{fontenc}\n";
1736                         texrow.newline();
1737                 }
1738                 if (params.inputenc != "default") {
1739                         LFile += "\\usepackage[" + params.inputenc
1740                                  + "]{inputenc}\n";
1741                         texrow.newline();
1742                 }
1743                 
1744                 /* at the very beginning the text parameters */
1745                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1746                         switch (params.paperpackage) {
1747                         case BufferParams::PACKAGE_A4:
1748                                 LFile += "\\usepackage{a4}\n";
1749                                 texrow.newline();
1750                                 break;
1751                         case BufferParams::PACKAGE_A4WIDE:
1752                                 LFile += "\\usepackage{a4wide}\n";
1753                                 texrow.newline();
1754                                 break;
1755                         case BufferParams::PACKAGE_WIDEMARGINSA4:
1756                                 LFile += "\\usepackage[widemargins]{a4}\n";
1757                                 texrow.newline();
1758                                 break;
1759                         }
1760                 }
1761                 if (params.use_geometry) {
1762                         LFile += "\\usepackage{geometry}\n";
1763                         texrow.newline();
1764                         LFile += "\\geometry{verbose";
1765                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1766                                 LFile += ",landscape";
1767                         switch (params.papersize2) {
1768                         case BufferParams::VM_PAPER_CUSTOM:
1769                                 if (!params.paperwidth.empty())
1770                                         LFile += ",paperwidth= "
1771                                                  + params.paperwidth;
1772                                 if (!params.paperheight.empty())
1773                                         LFile += ",paperheight= "
1774                                                  + params.paperheight;
1775                                 break;
1776                         case BufferParams::VM_PAPER_USLETTER:
1777                                 LFile += ",letterpaper";
1778                                 break;
1779                         case BufferParams::VM_PAPER_USLEGAL:
1780                                 LFile += ",legalpaper";
1781                                 break;
1782                         case BufferParams::VM_PAPER_USEXECUTIVE:
1783                                 LFile += ",executivepaper";
1784                                 break;
1785                         case BufferParams::VM_PAPER_A3:
1786                                 LFile += ",a3paper";
1787                                 break;
1788                         case BufferParams::VM_PAPER_A4:
1789                                 LFile += ",a4paper";
1790                                 break;
1791                         case BufferParams::VM_PAPER_A5:
1792                                 LFile += ",a5paper";
1793                                 break;
1794                         case BufferParams::VM_PAPER_B3:
1795                                 LFile += ",b3paper";
1796                                 break;
1797                         case BufferParams::VM_PAPER_B4:
1798                                 LFile += ",b4paper";
1799                                 break;
1800                         case BufferParams::VM_PAPER_B5:
1801                                 LFile += ",b5paper";
1802                                 break;
1803                         default:
1804                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1805                                 switch (lyxrc->default_papersize) {
1806                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1807                                 case BufferParams::PAPER_USLETTER:
1808                                         LFile += ",letterpaper";
1809                                         break;
1810                                 case BufferParams::PAPER_LEGALPAPER:
1811                                         LFile += ",legalpaper";
1812                                         break;
1813                                 case BufferParams::PAPER_EXECUTIVEPAPER:
1814                                         LFile += ",executivepaper";
1815                                         break;
1816                                 case BufferParams::PAPER_A3PAPER:
1817                                         LFile += ",a3paper";
1818                                         break;
1819                                 case BufferParams::PAPER_A4PAPER:
1820                                         LFile += ",a4paper";
1821                                         break;
1822                                 case BufferParams::PAPER_A5PAPER:
1823                                         LFile += ",a5paper";
1824                                         break;
1825                                 case BufferParams::PAPER_B5PAPER:
1826                                         LFile += ",b5paper";
1827                                         break;
1828                                 }
1829                         }
1830                         if (!params.topmargin.empty())
1831                                 LFile += ",tmargin= " + params.topmargin;
1832                         if (!params.bottommargin.empty())
1833                                 LFile += ",bmargin= " + params.bottommargin;
1834                         if (!params.leftmargin.empty())
1835                                 LFile += ",lmargin= " + params.leftmargin;
1836                         if (!params.rightmargin.empty())
1837                                 LFile += ",rmargin= " + params.rightmargin;
1838                         if (!params.headheight.empty())
1839                                 LFile += ",headheight= " + params.headheight;
1840                         if (!params.headsep.empty())
1841                                 LFile += ",headsep= " + params.headsep;
1842                         if (!params.footskip.empty())
1843                                 LFile += ",footskip= " + params.footskip;
1844                         LFile += "}\n";
1845                         texrow.newline();
1846                 }
1847                 if (params.use_amsmath
1848                     && !prefixIs(textclasslist.LatexnameOfClass(params.textclass), "ams")) {
1849                         LFile += "\\usepackage{amsmath}\n";
1850                 }
1851
1852                 if (tokenPos(tclass.opt_pagestyle(), '|', params.pagestyle) >= 0) {
1853                         if (params.pagestyle == "fancy") {
1854                                 LFile += "\\usepackage{fancyhdr}\n";
1855                                 texrow.newline();
1856                         }
1857                         LFile += "\\pagestyle{" + params.pagestyle + "}\n";
1858                         texrow.newline();
1859                 }
1860
1861                 // We try to load babel late, in case it interferes
1862                 // with other packages.
1863                 if (params.language != "default") {
1864                         LFile += "\\usepackage{babel}\n";
1865                         texrow.newline();
1866                 }
1867
1868                 if (params.secnumdepth != tclass.secnumdepth()) {
1869                         LFile += "\\setcounter{secnumdepth}{";
1870                         LFile += tostr(params.secnumdepth);
1871                         LFile += "}\n";
1872                         texrow.newline();
1873                 }
1874                 if (params.tocdepth != tclass.tocdepth()) {
1875                         LFile += "\\setcounter{tocdepth}{";
1876                         LFile += tostr(params.tocdepth);
1877                         LFile += "}\n";
1878                         texrow.newline();
1879                 }
1880                 
1881                 if (params.paragraph_separation) {
1882                         switch (params.defskip.kind()) {
1883                         case VSpace::SMALLSKIP: 
1884                                 LFile += "\\setlength\\parskip{\\smallskipamount}\n";
1885                                 break;
1886                         case VSpace::MEDSKIP:
1887                                 LFile += "\\setlength\\parskip{\\medskipamount}\n";
1888                                 break;
1889                         case VSpace::BIGSKIP:
1890                                 LFile += "\\setlength\\parskip{\\bigskipamount}\n";
1891                                 break;
1892                         case VSpace::LENGTH:
1893                                 LFile += "\\setlength\\parskip{"
1894                                          + params.defskip.length().asLatexString()
1895                                          + "}\n";
1896                                 break;
1897                         default: // should never happen // Then delete it.
1898                                 LFile += "\\setlength\\parskip{\\medskipamount}\n";
1899                                 break;
1900                         }
1901                         texrow.newline();
1902                         
1903                         LFile += "\\setlength\\parindent{0pt}\n";
1904                         texrow.newline();
1905                 }
1906
1907                 // Write out what we've generated so far...and reset LFile
1908                 fwrite(LFile.c_str(), sizeof(char), LFile.length(), file);
1909                 LFile.clear(); 
1910
1911                 // Now insert the LyX specific LaTeX commands...
1912                 string preamble, tmppreamble;
1913
1914                 // The optional packages;
1915                 preamble = features.getPackages(params);
1916
1917                 // this might be useful...
1918                 preamble += "\n\\makeatletter\n\n";
1919
1920                 // Some macros LyX will need
1921                 tmppreamble = features.getMacros(params);
1922
1923                 if (!tmppreamble.empty()) {
1924                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1925                                 "LyX specific LaTeX commands.\n"
1926                                 + tmppreamble + '\n';
1927                 }
1928
1929                 // the text class specific preamble 
1930                 tmppreamble = features.getTClassPreamble(params);
1931                 if (!tmppreamble.empty()) {
1932                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1933                                 "Textclass specific LaTeX commands.\n"
1934                                 + tmppreamble + '\n';
1935                 }
1936
1937                 /* the user-defined preamble */
1938                 if (!params.preamble.empty()) {
1939                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1940                                 "User specified LaTeX commands.\n"
1941                                 + params.preamble + '\n';
1942                 }
1943
1944                 preamble += "\\makeatother\n\n";
1945
1946                 // Itemize bullet settings need to be last in case the user
1947                 // defines their own bullets that use a package included
1948                 // in the user-defined preamble -- ARRae
1949                 for (int i = 0; i < 4; ++i) {
1950                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1951                                 preamble += "\\renewcommand\\labelitemi";
1952                                 switch (i) {
1953                                         // `i' is one less than the item to modify
1954                                 case 0:
1955                                         break;
1956                                 case 1:
1957                                         preamble += 'i';
1958                                         break;
1959                                 case 2:
1960                                         preamble += "ii";
1961                                         break;
1962                                 case 3:
1963                                         preamble += 'v';
1964                                         break;
1965                                 }
1966                                 preamble += "[0]{" + params.user_defined_bullets[i].getText() + "}\n";
1967                         }
1968                 }
1969
1970                 for (int j = countChar(preamble, '\n'); j-- ;) {
1971                         texrow.newline();
1972                 }
1973
1974                 // A bit faster than printing a char at a time I think.
1975                 fwrite(preamble.c_str(), sizeof(char),
1976                        preamble.length(), file);
1977
1978                 // make the body.
1979                 LFile += "\\begin{document}\n\n";
1980                 texrow.newline();
1981                 texrow.newline();
1982         } // only_body
1983         lyxerr.debug() << "preamble finished, now the body." << endl;
1984         
1985         bool was_title = false;
1986         bool already_title = false;
1987         string ftnote;
1988         TexRow ft_texrow;
1989         int ftcount = 0;
1990         int loop_count = 0;
1991
1992         LyXParagraph * par = paragraph;
1993
1994         // if only_body
1995         while (par) {
1996                 ++loop_count;
1997                 if (par->IsDummy())
1998                         lyxerr[Debug::LATEX] << "Error in MakeLateXFile."
1999                                              << endl;
2000                 LyXLayout const & layout = textclasslist.Style(params.textclass,
2001                                                     par->layout);
2002             
2003                 if (layout.intitle) {
2004                         if (already_title) {
2005                                 lyxerr <<"Error in MakeLatexFile: You"
2006                                         " should not mix title layouts"
2007                                         " with normal ones." << endl;
2008                         } else
2009                                 was_title = true;
2010                 } else if (was_title && !already_title) {
2011                         LFile += "\\maketitle\n";
2012                         texrow.newline();
2013                         already_title = true;
2014                         was_title = false;                  
2015                 }
2016                 // We are at depth 0 so we can just use
2017                 // ordinary \footnote{} generation
2018                 // flag this with ftcount
2019                 ftcount = -1;
2020                 if (layout.isEnvironment()
2021                     || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2022                         par = par->TeXEnvironment(LFile, texrow,
2023                                                   ftnote, ft_texrow, ftcount);
2024                 } else {
2025                         par = par->TeXOnePar(LFile, texrow,
2026                                              ftnote, ft_texrow, ftcount);
2027                 }
2028
2029                 // Write out what we've generated...and reset LFile
2030                 if (ftcount >= 1) {
2031                         if (ftcount > 1) {
2032                                 LFile += "\\addtocounter{footnote}{-";
2033                                 LFile += tostr(ftcount - 1);
2034                                 LFile += '}';
2035                         }
2036                         LFile += ftnote;
2037                         texrow += ft_texrow;
2038                         ftnote.clear();
2039                         ft_texrow.reset();
2040                         ftcount = 0;
2041                 }
2042                 if (loop_count == 2) {
2043                         // fwrite()ing every second time through the loop
2044                         // gains a few extra % of speed; going higher than
2045                         // 2 will slow things down again.  I'll look at
2046                         // LFile.length() in a future revision.  ARRae
2047                         fwrite(LFile.c_str(), sizeof(char),
2048                                LFile.length(), file);
2049                         LFile.clear();
2050                         loop_count = 0;
2051                 }
2052         }
2053
2054         // It might be that we only have a title in this document
2055         if (was_title && !already_title) {
2056                 LFile += "\\maketitle\n";
2057                 texrow.newline();
2058         }
2059
2060         if (!only_body) {
2061                 LFile += "\\end{document}\n";
2062                 texrow.newline();
2063         
2064                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2065         } else {
2066                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2067                                      << endl;
2068         }
2069
2070         // Just to be sure. (Asger)
2071         texrow.newline();
2072
2073         // Write out what we've generated...and reset LFile
2074         fwrite(LFile.c_str(), sizeof(char), LFile.length(), file);
2075         LFile.clear();
2076
2077         // tex_code_break_column's value is used to decide
2078         // if we are in batchmode or not (within mathed_write()
2079         // in math_write.C) so we must set it to a non-zero
2080         // value when we leave otherwise we save incorrect .lyx files.
2081         tex_code_break_column = lyxrc->ascii_linelen;
2082
2083         if (file.close()) {
2084                 WriteFSAlert(_("Error! Could not close file properly:"), filename);
2085         }
2086         lyxerr.debug() << "Finished making latex file." << endl;
2087 }
2088
2089
2090 bool Buffer::isLatex() const
2091 {
2092         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2093 }
2094
2095
2096 bool Buffer::isLinuxDoc() const
2097 {
2098         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2099 }
2100
2101
2102 bool Buffer::isLiterate() const
2103 {
2104         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2105 }
2106
2107
2108 bool Buffer::isDocBook() const
2109 {
2110         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2111 }
2112
2113
2114 bool Buffer::isSGML() const
2115 {
2116         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2117                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2118 }
2119
2120
2121 void Buffer::sgmlOpenTag(FILE * file, int depth, 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::sgmlCloseTag(FILE * file, int depth,
2131                           string const & latexname) const
2132 {
2133         static char * space[] = {" ", "  ", "   ", "    ", "     ", "      ", "       ",
2134                          "        ", "         ", "          ", "          "};
2135
2136         fprintf(file, "%s</%s>\n", space[depth], latexname.c_str());
2137 }
2138
2139
2140 void Buffer::makeLinuxDocFile(string const & filename, int column)
2141 {
2142         LyXParagraph * par = paragraph;
2143
2144         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2145         string environment_stack[10];
2146         string item_name;
2147
2148         int depth = 0;              /* paragraph depth */
2149
2150         FilePtr file(filename, FilePtr::write);
2151         tex_code_break_column = column; 
2152
2153         if (!file()) {
2154                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), filename);
2155                 return;
2156         }
2157    
2158         texrow.reset();
2159    
2160         if (params.preamble.empty()) {
2161                 fprintf(file, "<!doctype linuxdoc system>\n\n");
2162         }
2163         else {
2164                 fprintf(file, "<!doctype linuxdoc system \n [ %s \n]>\n\n", 
2165                         params.preamble.c_str() );
2166         }
2167
2168         string userName(getUserName());
2169         fprintf(file,
2170                 "<!-- LinuxDoc file was created by LyX 1.0 (C) 1995-1999 ");
2171         fprintf(file, "by <%s> %s -->\n", userName.c_str(), (char *)date());
2172
2173         if(params.options.empty())
2174                 sgmlOpenTag(file, 0, top_element);
2175         else {
2176                 string top = top_element;
2177                 top += " ";
2178                 top += params.options;
2179                 sgmlOpenTag(file, 0, top);
2180         }
2181
2182         while (par) {
2183                 int desc_on = 0;            /* description mode*/
2184                 LyXLayout const & style =
2185                         textclasslist.Style(GetCurrentTextClass(),
2186                                             par->layout);
2187                 par->AutoDeleteInsets();
2188
2189                 /* treat <toc> as a special case for compatibility with old code */
2190                 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2191                         Inset *inset = par->GetInset(0);
2192                         char  lyx_code = inset->LyxCode();
2193                         if (lyx_code == Inset::TOC_CODE){
2194                                 string temp = "toc";
2195                                 sgmlOpenTag(file, depth, temp);
2196
2197                                 par = par->next;
2198                                 linuxDocHandleFootnote(file, par, depth);
2199                                 continue;
2200                         }
2201                 }
2202
2203                 /* environment tag closing */
2204                 for( ;depth > par->depth; depth--) {
2205                         sgmlCloseTag(file, depth, environment_stack[depth]);
2206                         environment_stack[depth].clear();
2207                 }
2208
2209                 /* write opening SGML tags */
2210                 switch(style.latextype) {
2211                 case LATEX_PARAGRAPH:
2212                         if(depth == par->depth 
2213                            && !environment_stack[depth].empty()) {
2214                                 sgmlCloseTag(file, depth, environment_stack[depth]);
2215                                 environment_stack[depth].clear();
2216                                 if(depth) 
2217                                         depth--;
2218                                 else
2219                                         fprintf(file, "</p>");
2220                         }
2221                         sgmlOpenTag(file, depth, style.latexname());
2222                         break;
2223
2224                 case LATEX_COMMAND:
2225                         if (depth!= 0)
2226                                 LinuxDocError(par, 0, _("Error : Wrong depth for LatexType Command.\n"));
2227
2228                         if (!environment_stack[depth].empty()){
2229                                 sgmlCloseTag(file, depth, environment_stack[depth]);
2230                                 fprintf(file, "</p>");
2231                         }
2232
2233                         environment_stack[depth].clear();
2234                         sgmlOpenTag(file, depth, style.latexname());
2235                         break;
2236
2237                 case LATEX_ENVIRONMENT:
2238                 case LATEX_ITEM_ENVIRONMENT:
2239                         if(depth == par->depth 
2240                            && environment_stack[depth] != style.latexname()
2241                            && !environment_stack[depth].empty()) {
2242
2243                                 sgmlCloseTag(file, depth,
2244                                              environment_stack[depth]);
2245                                 environment_stack[depth].clear();
2246                         }
2247                         if (depth < par->depth) {
2248                                depth = par->depth;
2249                                environment_stack[depth].clear();
2250                         }
2251                         if (environment_stack[depth] != style.latexname()) {
2252                                 if(depth == 0) {
2253                                         string temp = "p";
2254                                         sgmlOpenTag(file, depth, temp);
2255                                 }
2256                                 environment_stack[depth] = style.latexname();
2257                                 sgmlOpenTag(file, depth, environment_stack[depth]);
2258                         }
2259                         if(style.latextype == LATEX_ENVIRONMENT) break;
2260
2261                         desc_on = (style.labeltype == LABEL_MANUAL);
2262
2263                         if(desc_on)
2264                                 item_name = "tag";
2265                         else
2266                                 item_name = "item";
2267
2268                         sgmlOpenTag(file, depth+1, item_name);
2269                         break;
2270                 default:
2271                         sgmlOpenTag(file, depth, style.latexname());
2272                         break;
2273                 }
2274
2275                 do {
2276                         SimpleLinuxDocOnePar(file, par, desc_on, depth);
2277
2278                         par = par->next;
2279                         linuxDocHandleFootnote(file, par, depth);
2280                 }
2281                 while(par && par->IsDummy());
2282
2283                 fprintf(file, "\n");
2284                 /* write closing SGML tags */
2285                 switch(style.latextype) {
2286                 case LATEX_COMMAND:
2287                 case LATEX_ENVIRONMENT:
2288                 case LATEX_ITEM_ENVIRONMENT:
2289                         break;
2290                 default:
2291                         sgmlCloseTag(file, depth, style.latexname());
2292                         break;
2293                 }
2294         }
2295    
2296         /* Close open tags */
2297         for(;depth>0;depth--)
2298                 sgmlCloseTag(file, depth, environment_stack[depth]);
2299
2300         if(!environment_stack[depth].empty())
2301                 sgmlCloseTag(file, depth, environment_stack[depth]);
2302
2303         fprintf(file, "\n\n");
2304         sgmlCloseTag(file, 0, top_element);
2305
2306         if (file.close()) {
2307                 WriteFSAlert(_("Error! Could not close file properly:"),
2308                              filename);
2309         } 
2310 }
2311
2312
2313 void Buffer::linuxDocHandleFootnote(FILE * file, LyXParagraph * & par,
2314                                     int const depth)
2315 {
2316         string tag = "footnote";
2317
2318         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2319                 sgmlOpenTag(file, depth+1, tag);
2320                 SimpleLinuxDocOnePar(file, par, 0, depth+1);
2321                 sgmlCloseTag(file, depth+1, tag);
2322                 par = par->next;
2323         }
2324 }
2325
2326 void Buffer::DocBookHandleCaption(FILE * file, string & inner_tag,
2327                                   int const depth, int desc_on,
2328                                   LyXParagraph * & par)
2329 {
2330         LyXParagraph * tpar = par;
2331         string tmp_par, extra_par;
2332         while (tpar && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE) &&
2333                (tpar->layout != textclasslist.NumberOfLayout(params.textclass, "Caption").second))
2334                 tpar = tpar->next;
2335         if (tpar &&
2336             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2337                                                          "Caption").second) {
2338                 sgmlOpenTag(file, depth+1, inner_tag);
2339             SimpleDocBookOnePar(tmp_par, extra_par, tpar, desc_on, depth+2);
2340                tmp_par = strip(tmp_par);
2341                tmp_par = frontStrip(tmp_par);
2342                fprintf(file, "%s", tmp_par.c_str());
2343                sgmlCloseTag(file, depth+1, inner_tag);
2344                if(!extra_par.empty())
2345                        fprintf(file, "%s", extra_par.c_str());
2346        }
2347 }
2348
2349 void Buffer::DocBookHandleFootnote(FILE * file, LyXParagraph * & par,
2350                                    int const depth)
2351 {
2352         string tag, inner_tag;
2353         string tmp_par, extra_par;
2354         bool inner_span = false;
2355         int desc_on = 4;
2356
2357         // This is not how I like to see enums. They should not be anonymous
2358         // and variables of its type should not be declared right after the
2359         // last brace. (Lgb)
2360         enum {
2361                 NO_ONE,
2362                 FOOTNOTE_LIKE,
2363                 MARGIN_LIKE,
2364                 FIG_LIKE,
2365                 TAB_LIKE
2366         } last = NO_ONE, present = FOOTNOTE_LIKE;
2367
2368         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2369                 if(last == present) {
2370                         if(inner_span) {
2371                                 if(!tmp_par.empty()) {
2372                                         fprintf(file, "%s", tmp_par.c_str());
2373                                         tmp_par.clear();
2374                                         sgmlCloseTag(file, depth+1, inner_tag);
2375                                         sgmlOpenTag(file, depth+1, inner_tag);
2376                                 }
2377                         }
2378                         else
2379                                 fprintf(file, "\n");
2380                 } else {
2381                         fprintf(file, "%s", tmp_par.c_str());
2382                         if(!inner_tag.empty()) sgmlCloseTag(file, depth+1, inner_tag);
2383                         if(!extra_par.empty()) fprintf(file, "%s", extra_par.c_str());
2384                         if(!tag.empty()) sgmlCloseTag(file, depth, tag);
2385                         extra_par.clear();
2386
2387                         switch (par->footnotekind) {
2388                         case LyXParagraph::FOOTNOTE:
2389                         case LyXParagraph::ALGORITHM:
2390                                 tag = "footnote";
2391                                 inner_tag = "para";
2392                                 present = FOOTNOTE_LIKE;
2393                                 inner_span = true;
2394                                 break;
2395                         case LyXParagraph::MARGIN:
2396                                 tag = "sidebar";
2397                                 inner_tag = "para";
2398                                 present = MARGIN_LIKE;
2399                                 inner_span = true;
2400                                 break;
2401                         case LyXParagraph::FIG:
2402                         case LyXParagraph::WIDE_FIG:
2403                                 tag = "figure";
2404                                 inner_tag = "title";
2405                                 present = FIG_LIKE;
2406                                 inner_span = false;
2407                                 break;
2408                         case LyXParagraph::TAB:
2409                         case LyXParagraph::WIDE_TAB:
2410                                 tag = "table";
2411                                 inner_tag = "title";
2412                                 present = TAB_LIKE;
2413                                 inner_span = false;
2414                                 break;
2415                         }
2416                         sgmlOpenTag(file, depth, tag);
2417                         if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2418                                 DocBookHandleCaption(file, inner_tag, depth,
2419                                                      desc_on, par);
2420                                 inner_tag.clear();
2421                         } else {
2422                                 sgmlOpenTag(file, depth+1, inner_tag);
2423                         }
2424                 }
2425                 // ignore all caption here, we processed them above!!!
2426                 if (par->layout != textclasslist.NumberOfLayout(params.textclass,
2427                                                            "Caption").second) {
2428                         SimpleDocBookOnePar(tmp_par, extra_par, par,
2429                                             desc_on, depth+2);
2430                 }
2431                 tmp_par = frontStrip(strip(tmp_par));
2432
2433                 last = present;
2434                 par = par->next;
2435         }
2436         fprintf(file, "%s", tmp_par.c_str());
2437         if(!inner_tag.empty()) sgmlCloseTag(file, depth+1, inner_tag);
2438         if(!extra_par.empty()) fprintf(file, "%s", extra_par.c_str());
2439         if(!tag.empty()) sgmlCloseTag(file, depth, tag);
2440
2441 }
2442
2443
2444 /* push a tag in a style stack */
2445 void Buffer::push_tag(FILE * file, char const * tag,
2446                       int & pos, char stack[5][3])
2447 {
2448         int j;
2449
2450         /* pop all previous tags */
2451         for (j = pos; j >= 0; j--)
2452                 fprintf(file, "</%s>", stack[j]); 
2453
2454         /* add new tag */
2455         sprintf(stack[++pos], "%s", tag);
2456
2457         /* push all tags */
2458         for (j= 0; j<= pos; j++)
2459                 fprintf(file, "<%s>", stack[j]);
2460 }
2461
2462
2463 // pop a tag from a style stack
2464 void Buffer::pop_tag(FILE * file, char const * tag,
2465                      int & pos, char stack[5][3])
2466 {
2467         int j;
2468
2469         // pop all tags till specified one
2470         for (j= pos; (j>= 0) && (strcmp(stack[j], tag)); j--)
2471                 fprintf(file, "</%s>", stack[j]);
2472
2473         // closes the tag
2474         fprintf(file, "</%s>", tag);
2475
2476         // push all tags, but the specified one
2477         for (j= j+1; j<= pos; j++) {
2478                 fprintf(file, "<%s>", stack[j]);
2479                 strcpy(stack[j-1], stack[j]);
2480         }
2481         pos --;
2482 }
2483
2484
2485 /* handle internal paragraph parsing -- layout already processed */
2486
2487 // checks, if newcol chars should be put into this line
2488 // writes newline, if necessary.
2489 static
2490 void linux_doc_line_break(FILE * file, unsigned int & colcount,
2491                           const unsigned int newcol)
2492 {
2493         colcount += newcol;
2494         if (colcount > lyxrc->ascii_linelen) {
2495                 fprintf(file, "\n");
2496                 colcount = newcol; // assume write after this call
2497         }
2498 }
2499
2500
2501 void Buffer::SimpleLinuxDocOnePar(FILE * file, LyXParagraph * par,
2502                                   int desc_on, int const depth)
2503 {
2504         LyXFont font1, font2;
2505         char c;
2506         Inset * inset;
2507         LyXParagraph::size_type main_body;
2508         int j;
2509         LyXLayout const & style = textclasslist.Style(params.textclass,
2510                                                       par->GetLayout());
2511
2512         char family_type = 0;               // family font flag 
2513         bool is_bold     = false;           // series font flag 
2514         char shape_type  = 0;               // shape font flag 
2515         bool is_em = false;                 // emphasis (italic) font flag 
2516
2517         int stack_num = -1;          // style stack position 
2518         char stack[5][3];            // style stack 
2519         unsigned int char_line_count = 5;     // Heuristic choice ;-) 
2520
2521         if (style.labeltype != LABEL_MANUAL)
2522                 main_body = 0;
2523         else
2524                 main_body = par->BeginningOfMainBody();
2525
2526         /* gets paragraph main font */
2527         if (main_body > 0)
2528                 font1 = style.labelfont;
2529         else
2530                 font1 = style.font;
2531
2532   
2533         /* parsing main loop */
2534         for (LyXParagraph::size_type i = 0;
2535              i < par->size(); ++i) {
2536
2537                 /* handle quote tag */
2538                 if (i == main_body && !par->IsDummy()) {
2539                         if (main_body > 0)
2540                                 font1 = style.font;
2541                 }
2542
2543                 font2 = par->getFont(i);
2544
2545                 if (font1.family() != font2.family()) {
2546                         switch(family_type) {
2547                         case 0:
2548                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2549                                         push_tag(file, "tt", stack_num, stack);
2550                                         family_type= 1;
2551                                 }
2552                                 else if (font2.family() == LyXFont::SANS_FAMILY) {
2553                                         push_tag(file, "sf", stack_num, stack);
2554                                         family_type= 2;
2555                                 }
2556                                 break;
2557                         case 1:
2558                                 pop_tag(file, "tt", stack_num, stack);
2559                                 if (font2.family() == LyXFont::SANS_FAMILY) {
2560                                         push_tag(file, "sf", stack_num, stack);
2561                                         family_type= 2;
2562                                 }
2563                                 else {
2564                                         family_type= 0;
2565                                 }
2566                                 break;
2567                         case 2:
2568                                 pop_tag(file, "sf", stack_num, stack);
2569                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2570                                         push_tag(file, "tt", stack_num, stack);
2571                                         family_type= 1;
2572                                 }
2573                                 else {
2574                                         family_type= 0;
2575                                 }
2576                         }
2577                 }
2578
2579                 /* handle bold face */
2580                 if (font1.series() != font2.series()) {
2581                         if (font2.series() == LyXFont::BOLD_SERIES) {
2582                                 push_tag(file, "bf", stack_num, stack);
2583                                 is_bold = true;
2584                         }
2585                         else if (is_bold) {
2586                                 pop_tag(file, "bf", stack_num, stack);
2587                                 is_bold = false;
2588                         }
2589                 }
2590
2591                 /* handle italic and slanted fonts */
2592                 if (font1.shape() != font2.shape()) {
2593                         switch(shape_type) {
2594                         case 0:
2595                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2596                                         push_tag(file, "it", stack_num, stack);
2597                                         shape_type= 1;
2598                                 }
2599                                 else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2600                                         push_tag(file, "sl", stack_num, stack);
2601                                         shape_type= 2;
2602                                 }
2603                                 break;
2604                         case 1:
2605                                 pop_tag(file, "it", stack_num, stack);
2606                                 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2607                                         push_tag(file, "sl", stack_num, stack);
2608                                         shape_type= 2;
2609                                 }
2610                                 else {
2611                                         shape_type= 0;
2612                                 }
2613                                 break;
2614                         case 2:
2615                                 pop_tag(file, "sl", stack_num, stack);
2616                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2617                                         push_tag(file, "it", stack_num, stack);
2618                                         shape_type= 1;
2619                                 }
2620                                 else {
2621                                         shape_type= 0;
2622                                 }
2623                         }
2624                 }
2625                 /* handle <em> tag */
2626                 if (font1.emph() != font2.emph()) {
2627                         if (font2.emph() == LyXFont::ON) {
2628                                 push_tag(file, "em", stack_num, stack);
2629                                 is_em = true;
2630                         } else if (is_em) {
2631                                 pop_tag(file, "em", stack_num, stack);
2632                                 is_em = false;
2633                         }
2634                 }
2635
2636                 c = par->GetChar(i);
2637       
2638                 if (font2.latex() == LyXFont::ON) {
2639                         // "TeX"-Mode on == > SGML-Mode on.
2640                         if (c!= '\0')
2641                                 fprintf(file, "%c", c); // see LaTeX-Generation...
2642                         char_line_count++;
2643                 } else if (c == LyXParagraph::META_INSET) {
2644                         inset = par->GetInset(i);
2645                         string tmp_out;
2646                         inset->Linuxdoc(tmp_out);
2647                         fprintf(file, "%s", tmp_out.c_str());
2648                 }
2649                 else {
2650                         string sgml_string;
2651                         if (par->linuxDocConvertChar(c, sgml_string)
2652                             && !style.free_spacing) { // in freespacing
2653                                                      // mode, spaces are
2654                                                      // non-breaking characters
2655                                 // char is ' '
2656                                 if (desc_on == 1) {
2657                                         char_line_count++;
2658                                         linux_doc_line_break(file, char_line_count, 6);
2659                                         fprintf(file, "</tag>");
2660                                         desc_on = 2;
2661                                 }
2662                                 else  {
2663                                         linux_doc_line_break(file, char_line_count, 1);
2664                                         fprintf(file, "%c", c);
2665                                 }
2666                         }
2667                         else {
2668                                 fprintf(file, "%s", sgml_string.c_str());
2669                                 char_line_count += sgml_string.length();
2670                         }
2671                 }
2672                 font1 = font2;
2673         }
2674
2675         /* needed if there is an optional argument but no contents */
2676         if (main_body > 0 && main_body == par->size()) {
2677                 font1 = style.font;
2678         }
2679
2680         /* pop all defined Styles */
2681         for (j = stack_num; j >= 0; j--) {
2682                 linux_doc_line_break(file, 
2683                                      char_line_count, 
2684                                      3+strlen(stack[j]));
2685                 fprintf(file, "</%s>", stack[j]);
2686         }
2687
2688         /* resets description flag correctly */
2689         switch(desc_on){
2690         case 1:
2691                 /* <tag> not closed... */
2692                 linux_doc_line_break(file, char_line_count, 6);
2693                 fprintf(file, "</tag>");
2694                 break;
2695         case 2:
2696                 /* fprintf(file, "</p>");*/
2697                 break;
2698         }
2699 }
2700
2701
2702 /* print an error message */
2703 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2704                            char const * message) 
2705 {
2706         InsetError * new_inset;
2707
2708         /* insert an error marker in text */
2709         new_inset = new InsetError(message);
2710         par->InsertChar(pos, LyXParagraph::META_INSET);
2711         par->InsertInset(pos, new_inset);
2712 }
2713
2714 // This constant defines the maximum number of 
2715 // environment layouts that can be nesteded.
2716 // The same applies for command layouts.
2717 // These values should be more than enough.
2718 //           José Matos (1999/07/22)
2719
2720 enum { MAX_NEST_LEVEL = 25};
2721
2722 void Buffer::makeDocBookFile(string const & filename, int column)
2723 {
2724         LyXParagraph * par = paragraph;
2725
2726         string top_element= textclasslist.LatexnameOfClass(params.textclass);
2727         string environment_stack[MAX_NEST_LEVEL];
2728         string environment_inner[MAX_NEST_LEVEL];
2729         string command_stack[MAX_NEST_LEVEL];
2730         bool command_flag= false;
2731         int command_depth= 0, command_base= 0, cmd_depth= 0;
2732
2733         string item_name, command_name;
2734         string c_depth, c_params, tmps;
2735
2736         int depth= 0;              /* paragraph depth */
2737
2738         FilePtr file(filename, FilePtr::write);
2739         tex_code_break_column = column; 
2740
2741         if (!file()) {
2742                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), filename);
2743                 return;
2744         }
2745    
2746         //ResetTexRow();
2747         texrow.reset();
2748
2749         fprintf(file,
2750                 "<!doctype %s public \"-//OASIS//DTD DocBook V3.1//EN\"",
2751                 top_element.c_str());
2752
2753         if (params.preamble.empty())
2754                 fprintf(file, ">\n\n");
2755         else
2756                 fprintf(file, "\n [ %s \n]>\n\n", params.preamble.c_str() );
2757
2758         string userName(getUserName());
2759         fprintf(file,
2760                 "<!-- DocBook file was created by LyX 1.0 (C) 1995-1999\n");
2761         fprintf(file, "by <%s> %s -->\n", userName.c_str(), (char *)date());
2762
2763         if(params.options.empty())
2764                 sgmlOpenTag(file, 0, top_element);
2765         else {
2766                 string top = top_element;
2767                 top += " ";
2768                 top += params.options;
2769                 sgmlOpenTag(file, 0, top);
2770         }
2771
2772         while (par) {
2773                 int desc_on= 0;            /* description mode*/
2774                 LyXLayout const & style = textclasslist.Style(GetCurrentTextClass(),
2775                                                    par->layout);
2776                 par->AutoDeleteInsets();
2777
2778                 /* environment tag closing */
2779                 for( ;depth > par->depth; depth--) {
2780                         if(environment_inner[depth] != "!-- --") {
2781                                 item_name= "listitem";
2782                                 sgmlCloseTag(file, command_depth+depth,
2783                                              item_name);
2784                                 if( environment_inner[depth] == "varlistentry")
2785                                         sgmlCloseTag(file, depth+command_depth,
2786                                                      environment_inner[depth]);
2787                         }
2788                         sgmlCloseTag(file, depth+command_depth,
2789                                      environment_stack[depth]);
2790                         environment_stack[depth].clear();
2791                         environment_inner[depth].clear();
2792                 }
2793
2794                 if(depth == par->depth
2795                    && environment_stack[depth] != style.latexname()
2796                    && !environment_stack[depth].empty()) {
2797                         if(environment_inner[depth] != "!-- --") {
2798                                 item_name= "listitem";
2799                                 sgmlCloseTag(file, command_depth+depth,
2800                                              item_name);
2801                                 if( environment_inner[depth] == "varlistentry")
2802                                         sgmlCloseTag(file, depth+command_depth,
2803                                                      environment_inner[depth]);
2804                         }
2805                         
2806                         sgmlCloseTag(file, depth+command_depth,
2807                                      environment_stack[depth]);
2808                         
2809                         environment_stack[depth].clear();
2810                         environment_inner[depth].clear();
2811                 }
2812
2813                 // Write opening SGML tags.
2814                 switch(style.latextype) {
2815                 case LATEX_PARAGRAPH:
2816                         if(style.latexname() != "dummy")
2817                                sgmlOpenTag(file, depth+command_depth,
2818                                            style.latexname());
2819                         break;
2820
2821                 case LATEX_COMMAND:
2822                         if (depth!= 0)
2823                                 LinuxDocError(par, 0,
2824                                               _("Error : Wrong depth for "
2825                                                 "LatexType Command.\n"));
2826                         
2827                         command_name = style.latexname();
2828                         
2829                         tmps = style.latexparam();
2830                         c_params = split(tmps, c_depth,'|');
2831                         
2832                         cmd_depth= atoi(c_depth.c_str());
2833                         
2834                         if(command_flag) {
2835                                 if(cmd_depth<command_base) {
2836                                         for(int j = command_depth;
2837                                             j >= command_base; j--)
2838                                                 if(!command_stack[j].empty())
2839                                                         sgmlCloseTag(file, j, command_stack[j]);
2840                                         command_depth= command_base= cmd_depth;
2841                                 }
2842                                 else if(cmd_depth<= command_depth) {
2843                                         for(int j= command_depth;
2844                                             j >= cmd_depth; j--)
2845
2846                                                 if(!command_stack[j].empty())
2847                                                         sgmlCloseTag(file, j, command_stack[j]);
2848                                         command_depth= cmd_depth;
2849                                 }
2850                                 else
2851                                         command_depth= cmd_depth;
2852                         }
2853                         else {
2854                                 command_depth = command_base = cmd_depth;
2855                                 command_flag = true;
2856                         }
2857                         command_stack[command_depth]= command_name;
2858
2859                         // treat label as a special case for
2860                         // more WYSIWYM handling.
2861                         if (par->GetChar(0) == LyXParagraph::META_INSET) {
2862                                 Inset *inset = par->GetInset(0);
2863                                 char  lyx_code = inset->LyxCode();
2864                                 if (lyx_code == Inset::LABEL_CODE){
2865                                         command_name+= " id= \"";
2866                                         command_name+= ((InsetCommand *) inset)->getContents();
2867                                         command_name+= "\"";
2868                                         desc_on= 3;
2869                                 }
2870                         }
2871
2872                         sgmlOpenTag(file, depth+command_depth, command_name);
2873                         item_name= "title";
2874                         sgmlOpenTag(file, depth+1+command_depth, item_name);
2875                         break;
2876
2877                 case LATEX_ENVIRONMENT:
2878                 case LATEX_ITEM_ENVIRONMENT:
2879                         if (depth < par->depth) {
2880                                 depth = par->depth;
2881                                 environment_stack[depth].clear();
2882                         }
2883
2884                         if (environment_stack[depth] != style.latexname()) {
2885                                 environment_stack[depth]= style.latexname();
2886                                 environment_inner[depth]= "!-- --";
2887                                 sgmlOpenTag(file, depth + command_depth,
2888                                             environment_stack[depth]);
2889                         } else {
2890                                 if(environment_inner[depth] != "!-- --") {
2891                                         item_name= "listitem";
2892                                         sgmlCloseTag(file,
2893                                                      command_depth + depth,
2894                                                      item_name);
2895                                         if (environment_inner[depth] == "varlistentry")
2896                                                 sgmlCloseTag(file,
2897                                                              depth+command_depth,
2898                                                              environment_inner[depth]);
2899                                 }
2900                         }
2901                         
2902                         if(style.latextype == LATEX_ENVIRONMENT) {
2903                                 if(!style.latexparam().empty())
2904                                         sgmlOpenTag(file, depth+command_depth,
2905                                                     style.latexparam());
2906                                 break;
2907                         }
2908
2909                         desc_on = (style.labeltype == LABEL_MANUAL);
2910
2911                         if(desc_on)
2912                                 environment_inner[depth]= "varlistentry";
2913                         else
2914                                 environment_inner[depth]= "listitem";
2915
2916                         sgmlOpenTag(file, depth+1+command_depth,
2917                                     environment_inner[depth]);
2918
2919                         if(desc_on) {
2920                                 item_name= "term";
2921                                 sgmlOpenTag(file, depth+1+command_depth,
2922                                             item_name);
2923                         }
2924                         else {
2925                                 item_name= "para";
2926                                 sgmlOpenTag(file, depth+1+command_depth,
2927                                             item_name);
2928                         }
2929                         break;
2930                 default:
2931                         sgmlOpenTag(file, depth + command_depth,
2932                                     style.latexname());
2933                         break;
2934                 }
2935
2936                 do {
2937                         string tmp_par, extra_par;
2938
2939                         SimpleDocBookOnePar(tmp_par, extra_par, par, desc_on,
2940                                             depth+1+command_depth);
2941                         fprintf(file, "%s", tmp_par.c_str());
2942
2943                         par = par->next;
2944                         DocBookHandleFootnote(file, par, depth+1+command_depth);
2945                 }
2946                 while(par && par->IsDummy());
2947
2948                 string end_tag;
2949                 /* write closing SGML tags */
2950                 switch(style.latextype) {
2951                 case LATEX_COMMAND:
2952                         end_tag = "title";
2953                         sgmlCloseTag(file, depth + command_depth, end_tag);
2954                         break;
2955                 case LATEX_ENVIRONMENT:
2956                         if(!style.latexparam().empty())
2957                                 sgmlCloseTag(file, depth + command_depth,
2958                                              style.latexparam());
2959                         break;
2960                 case LATEX_ITEM_ENVIRONMENT:
2961                         if(desc_on == 1) break;
2962                         end_tag= "para";
2963                         sgmlCloseTag(file, depth+1+command_depth, end_tag);
2964                         break;
2965                 case LATEX_PARAGRAPH:
2966                         if(style.latexname() != "dummy")
2967                                 sgmlCloseTag(file, depth + command_depth,
2968                                              style.latexname());
2969                         break;
2970                 default:
2971                         sgmlCloseTag(file, depth+command_depth,
2972                                      style.latexname());
2973                         break;
2974                 }
2975         }
2976
2977         // Close open tags
2978         for(;depth>= 0;depth--) {
2979                 if(!environment_stack[depth].empty()) {
2980                         if(environment_inner[depth] != "!-- --") {
2981                                 item_name= "listitem";
2982                                 sgmlCloseTag(file, command_depth+depth,
2983                                              item_name);
2984                                if( environment_inner[depth] == "varlistentry")
2985                                        sgmlCloseTag(file, depth+command_depth,
2986                                                     environment_inner[depth]);
2987                         }
2988                         
2989                         sgmlCloseTag(file, depth+command_depth,
2990                                      environment_stack[depth]);
2991                 }
2992         }
2993         
2994         for(int j= command_depth;j>= command_base;j--)
2995                 if(!command_stack[j].empty())
2996                         sgmlCloseTag(file, j, command_stack[j]);
2997
2998         fprintf(file, "\n\n");
2999         sgmlCloseTag(file, 0, top_element);
3000
3001         if (file.close()) {
3002                 WriteFSAlert(_("Error! Could not close file properly:"),
3003                              filename);
3004         }
3005 }
3006
3007
3008 void Buffer::SimpleDocBookOnePar(string & file, string & extra,
3009                                  LyXParagraph * par, int & desc_on,
3010                                  int const depth) 
3011 {
3012         if (par->table) {
3013                 par->SimpleDocBookOneTablePar(file, extra, desc_on, depth);
3014                 return;
3015         }
3016         LyXFont font1, font2;
3017         char c;
3018         Inset *inset;
3019         LyXParagraph::size_type main_body;
3020         int j;
3021         string emph= "emphasis";
3022         bool emph_flag= false;
3023         int char_line_count= 0;
3024
3025         LyXLayout const & style = textclasslist.Style(params.textclass,
3026                                                       par->GetLayout());
3027
3028         if (style.labeltype != LABEL_MANUAL)
3029                 main_body = 0;
3030         else
3031                 main_body = par->BeginningOfMainBody();
3032
3033         /* gets paragraph main font */
3034         if (main_body > 0)
3035                 font1 = style.labelfont;
3036         else
3037                 font1 = style.font;
3038
3039         char_line_count = depth;
3040         if(!style.free_spacing)
3041                 for (j= 0;j< depth;j++)
3042                         file += ' ';
3043
3044         /* parsing main loop */
3045         for (LyXParagraph::size_type i = 0;
3046              i < par->size(); ++i) {
3047                 font2 = par->getFont(i);
3048
3049                 /* handle <emphasis> tag */
3050                 if (font1.emph() != font2.emph() && i) {
3051                         if (font2.emph() == LyXFont::ON) {
3052                                 file += "<emphasis>";
3053                                 emph_flag= true;
3054                         }else {
3055                                 file += "</emphasis>";
3056                                 emph_flag= false;
3057                         }
3058                 }
3059       
3060                 c = par->GetChar(i);
3061
3062                 if (c == LyXParagraph::META_INSET) {
3063                         inset = par->GetInset(i);
3064                         string tmp_out;
3065                         inset->DocBook(tmp_out);
3066                         //
3067                         // This code needs some explanation:
3068                         // Two insets are treated specially
3069                         //   label if it is the first element in a command paragraph
3070                         //         desc_on == 3
3071                         //   graphics inside tables or figure floats can't go on
3072                         //   title (the equivalente in latex for this case is caption
3073                         //   and title should come first
3074                         //         desc_on == 4
3075                         //
3076                         if(desc_on!= 3 || i!= 0) {
3077                                 if(tmp_out[0] == '@') {
3078                                         if(desc_on == 4)
3079                                                 extra += frontStrip(tmp_out, '@');
3080                                         else
3081                                                 file += frontStrip(tmp_out, '@');
3082                                 }
3083                                 else
3084                                         file += tmp_out;
3085                         }
3086                 } else if (font2.latex() == LyXFont::ON) {
3087                         // "TeX"-Mode on == > SGML-Mode on.
3088                         if (c!= '\0')
3089                                 file += c;
3090                         char_line_count++;
3091                 }
3092                 else {
3093                         string sgml_string;
3094                         if (par->linuxDocConvertChar(c, sgml_string)
3095                             && !style.free_spacing) { // in freespacing
3096                                                      // mode, spaces are
3097                                                      // non-breaking characters
3098                                 // char is ' '
3099                                 if (desc_on == 1) {
3100                                         char_line_count++;
3101                                         file += '\n';
3102                                         file += "</term><listitem><para>";
3103                                         desc_on = 2;
3104                                 }
3105                                 else  {
3106                                         file += c;
3107                                 }
3108                         }
3109                         else {
3110                                 file += sgml_string;
3111                         }
3112                 }
3113                 font1 = font2;
3114         }
3115
3116         /* needed if there is an optional argument but no contents */
3117         if (main_body > 0 && main_body == par->size()) {
3118                 font1 = style.font;
3119         }
3120         if (emph_flag) {
3121                 file += "</emphasis>";
3122         }
3123         
3124         /* resets description flag correctly */
3125         switch(desc_on){
3126         case 1:
3127                 /* <term> not closed... */
3128                 file += "</term>";
3129                 break;
3130         }
3131         file += '\n';
3132 }
3133
3134
3135 bool Buffer::removeAutoInsets()
3136 {
3137         LyXParagraph *par = paragraph;
3138
3139         LyXCursor cursor = text->cursor;
3140         LyXCursor tmpcursor = cursor;
3141         cursor.par = tmpcursor.par->ParFromPos(tmpcursor.pos);
3142         cursor.pos = tmpcursor.par->PositionInParFromPos(tmpcursor.pos);
3143
3144         bool a = false;
3145         while (par) {
3146                 if (par->AutoDeleteInsets()){
3147                         a = true;
3148                         if (par->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE){
3149                                 /* this is possible now, since SetCursor takes
3150                                    care about footnotes */
3151                                 text->SetCursorIntern(par, 0);
3152                                 text->RedoParagraphs(text->cursor, text->cursor.par->Next());
3153                                 text->FullRebreak();
3154                         }
3155                 }
3156                 par = par->next;
3157         }
3158         /* avoid forbidden cursor positions caused by error removing */ 
3159         if (cursor.pos > cursor.par->Last())
3160                 cursor.pos = cursor.par->Last();
3161         text->SetCursorIntern(cursor.par, cursor.pos);
3162
3163         return a;
3164 }
3165
3166
3167 int Buffer::runLaTeX()
3168 {
3169         if (!text) return 0;
3170
3171         ProhibitInput();
3172
3173         // get LaTeX-Filename
3174         string name = SpaceLess(ChangeExtension (filename, ".tex", true));
3175
3176         string path = OnlyPath(filename);
3177
3178         string org_path = path;
3179         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3180                 path = tmppath;  
3181         }
3182
3183         Path p(path); // path to LaTeX file
3184         users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));   
3185
3186         // Remove all error insets
3187         bool a = removeAutoInsets();
3188
3189         // Always generate the LaTeX file
3190         makeLaTeXFile(name, org_path, false);
3191         markDviDirty();
3192
3193         // do the LaTex run(s)
3194         TeXErrors terr;
3195         LaTeX latex(lyxrc->latex_command, name, filepath);
3196         int res = latex.run(terr,
3197                             users->owner()->getMiniBuffer()); // running latex
3198
3199         // check return value from latex.run().
3200         if ((res & LaTeX::NO_LOGFILE)) {
3201                 WriteAlert(_("LaTeX did not work!"),
3202                            _("Missing log file:"), name);
3203         } else if ((res & LaTeX::ERRORS)) {
3204                 users->owner()->getMiniBuffer()->Set(_("Done"));
3205                 // Insert all errors as errors boxes
3206                 insertErrors(terr);
3207                 
3208                 // Dvi should also be kept dirty if the latex run
3209                 // ends up with errors. However it should be possible
3210                 // to view a dirty dvi too.
3211         } else {
3212                 //no errors or any other things to think about so:
3213                 users->owner()->getMiniBuffer()->Set(_("Done"));
3214                 markDviClean();
3215         }
3216
3217         // if we removed error insets before we ran LaTeX or if we inserted
3218         // error insets after we ran LaTeX this must be run:
3219         if (a || (res & LaTeX::ERRORS)){
3220                 users->redraw();
3221                 users->fitCursor();
3222                 users->updateScrollbar();
3223         }
3224         AllowInput();
3225  
3226         return latex.getNumErrors();
3227 }
3228
3229
3230 int Buffer::runLiterate()
3231 {
3232         if (!text) return 0;
3233
3234         ProhibitInput();
3235
3236         // get LaTeX-Filename
3237         string name = SpaceLess(ChangeExtension (filename, ".tex", true));
3238         // get Literate-Filename
3239         string lit_name = SpaceLess(ChangeExtension (filename, lyxrc->literate_extension, true));
3240
3241         string path = OnlyPath(filename);
3242
3243         string org_path = path;
3244         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3245                 path = tmppath;  
3246         }
3247
3248         Path p(path); // path to Literate file
3249         users->owner()->getMiniBuffer()->Set(_("Running Literate..."));   
3250
3251         // Remove all error insets
3252         bool a = removeAutoInsets();
3253
3254         // generate the Literate file if necessary
3255         if (!isDviClean() || a) {
3256                 makeLaTeXFile(lit_name, org_path, false);
3257                 markDviDirty();
3258         }
3259
3260         Literate literate(lyxrc->latex_command, name, filepath, 
3261                           lit_name,
3262                           lyxrc->literate_command, lyxrc->literate_error_filter,
3263                           lyxrc->build_command, lyxrc->build_error_filter);
3264         TeXErrors terr;
3265         int res = literate.weave(terr, users->owner()->getMiniBuffer());
3266
3267         // check return value from literate.weave().
3268         if ((res & Literate::NO_LOGFILE)) {
3269                 WriteAlert(_("Literate command did not work!"),
3270                            _("Missing log file:"), name);
3271         } else if ((res & Literate::ERRORS)) {
3272                 users->owner()->getMiniBuffer()->Set(_("Done"));
3273                 // Insert all errors as errors boxes
3274                 insertErrors(terr);
3275                 
3276                 // Dvi should also be kept dirty if the latex run
3277                 // ends up with errors. However it should be possible
3278                 // to view a dirty dvi too.
3279         } else {
3280                 //no errors or any other things to think about so:
3281                 users->owner()->getMiniBuffer()->Set(_("Done"));
3282                 markDviClean();
3283         }
3284
3285         // if we removed error insets before we ran LaTeX or if we inserted
3286         // error insets after we ran LaTeX this must be run:
3287         if (a || (res & Literate::ERRORS)){
3288                 users->redraw();
3289                 users->fitCursor();
3290                 users->updateScrollbar();
3291         }
3292         AllowInput();
3293  
3294         return literate.getNumErrors();
3295 }
3296
3297
3298 int Buffer::buildProgram()
3299 {
3300         if (!text) return 0;
3301  
3302         ProhibitInput();
3303  
3304         // get LaTeX-Filename
3305         string name = SpaceLess(ChangeExtension (filename, ".tex", true));
3306         // get Literate-Filename
3307         string lit_name = SpaceLess(ChangeExtension (filename, lyxrc->literate_extension, true));
3308  
3309         string path = OnlyPath(filename);
3310  
3311         string org_path = path;
3312         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3313                 path = tmppath;  
3314         }
3315  
3316         Path p(path); // path to Literate file
3317         users->owner()->getMiniBuffer()->Set(_("Building Program..."));   
3318  
3319         // Remove all error insets
3320         bool a = removeAutoInsets();
3321  
3322         // generate the LaTeX file if necessary
3323         if (!isNwClean() || a) {
3324                 makeLaTeXFile(lit_name, org_path, false);
3325                 markNwDirty();
3326         }
3327  
3328         Literate literate(lyxrc->latex_command, name, filepath, 
3329                           lit_name,
3330                           lyxrc->literate_command, lyxrc->literate_error_filter,
3331                           lyxrc->build_command, lyxrc->build_error_filter);
3332         TeXErrors terr;
3333         int res = literate.build(terr, users->owner()->getMiniBuffer());
3334  
3335         // check return value from literate.build().
3336         if ((res & Literate::NO_LOGFILE)) {
3337                 WriteAlert(_("Build did not work!"),
3338                            _("Missing log file:"), name);
3339         } else if ((res & Literate::ERRORS)) {
3340                 users->owner()->getMiniBuffer()->Set(_("Done"));
3341                 // Insert all errors as errors boxes
3342                 insertErrors(terr);
3343                 
3344                 // Literate files should also be kept dirty if the literate 
3345                 // command run ends up with errors.
3346         } else {
3347                 //no errors or any other things to think about so:
3348                 users->owner()->getMiniBuffer()->Set(_("Done"));
3349                 markNwClean();
3350         }
3351  
3352         // if we removed error insets before we ran Literate/Build or if we inserted
3353         // error insets after we ran Literate/Build this must be run:
3354         if (a || (res & Literate::ERRORS)){
3355                 users->redraw();
3356                 users->fitCursor();
3357                 users->updateScrollbar();
3358         }
3359         AllowInput();
3360
3361         return literate.getNumErrors();
3362 }
3363
3364
3365 // This should be enabled when the Chktex class is implemented. (Asger)
3366 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3367 // Other flags: -wall -v0 -x
3368 int Buffer::runChktex()
3369 {
3370         if (!text) return 0;
3371
3372         ProhibitInput();
3373
3374         // get LaTeX-Filename
3375         string name = SpaceLess(ChangeExtension (filename, ".tex", true));
3376         string path = OnlyPath(filename);
3377
3378         string org_path = path;
3379         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3380                 path = tmppath;  
3381         }
3382
3383         Path p(path); // path to LaTeX file
3384         users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3385
3386         // Remove all error insets
3387         bool a = removeAutoInsets();
3388
3389         // Generate the LaTeX file if neccessary
3390         if (!isDviClean() || a) {
3391                 makeLaTeXFile(name, org_path, false);
3392                 markDviDirty();
3393         }
3394
3395         TeXErrors terr;
3396         Chktex chktex(lyxrc->chktex_command, name, filepath);
3397         int res = chktex.run(terr); // run chktex
3398
3399         if (res == -1) {
3400                 WriteAlert(_("chktex did not work!"),
3401                            _("Could not run with file:"), name);
3402         } else if (res > 0) {
3403                 // Insert all errors as errors boxes
3404                 insertErrors(terr);
3405         }
3406
3407         // if we removed error insets before we ran chktex or if we inserted
3408         // error insets after we ran chktex, this must be run:
3409         if (a || res){
3410                 users->redraw();
3411                 users->fitCursor();
3412                 users->updateScrollbar();
3413         }
3414         AllowInput();
3415
3416         return res;
3417 }
3418
3419
3420 extern void AllFloats(char, char);
3421
3422
3423 void Buffer::insertErrors(TeXErrors & terr)
3424 {
3425         // Save the cursor position
3426         LyXCursor cursor = text->cursor;
3427
3428         // This is drastic, but it's the only fix, I could find. (Asger)
3429         AllFloats(1, 0);
3430         AllFloats(1, 1);
3431
3432         for (TeXErrors::Errors::const_iterator cit = terr.begin();
3433              cit != terr.end();
3434              ++cit) {
3435                 string desctext((*cit).error_desc);
3436                 string errortext((*cit).error_text);
3437                 string msgtxt = desctext + '\n' + errortext;
3438                 int errorrow = (*cit).error_in_line;
3439
3440                 // Insert error string for row number
3441                 int tmpid = -1; 
3442                 int tmppos = -1;
3443
3444                 texrow.getIdFromRow(errorrow, tmpid, tmppos);
3445
3446                 LyXParagraph* texrowpar;
3447
3448                 if (tmpid == -1) {
3449                         texrowpar = text->FirstParagraph();
3450                         tmppos = 0;
3451                 } else {
3452                         texrowpar = text->GetParFromID(tmpid);
3453                 }
3454
3455                 if (texrowpar == 0)
3456                         continue;
3457
3458                 InsetError *new_inset = new InsetError(msgtxt);
3459
3460                 text->SetCursorIntern(texrowpar, tmppos);
3461                 text->InsertInset(new_inset);
3462                 text->FullRebreak();
3463         }
3464         // Restore the cursor position
3465         text->SetCursorIntern(cursor.par, cursor.pos);
3466 }
3467
3468
3469 void Buffer::setCursorFromRow (int row)
3470 {
3471         int tmpid = -1; 
3472         int tmppos = -1;
3473
3474         texrow.getIdFromRow(row, tmpid, tmppos);
3475
3476         LyXParagraph* texrowpar;
3477
3478         if (tmpid == -1) {
3479                 texrowpar = text->FirstParagraph();
3480                 tmppos = 0;
3481         } else {
3482                 texrowpar = text->GetParFromID(tmpid);
3483         }
3484         text->SetCursor(texrowpar, tmppos);
3485 }
3486
3487
3488 void Buffer::RoffAsciiTable(FILE * file, LyXParagraph * par)
3489 {
3490         LyXFont
3491                 font1 =  LyXFont(LyXFont::ALL_INHERIT),
3492                 font2;
3493         Inset * inset;
3494         LyXParagraph::size_type i;
3495         int
3496                 j,
3497                 cell = 0;
3498         char
3499                 c;
3500         FILE
3501                 * fp, * fp2;
3502         
3503         string fname1 = TmpFileName(string(), "RAT1");
3504         string fname2 = TmpFileName(string(), "RAT2");
3505         if (!(fp= fopen(fname1.c_str(), "w"))) {
3506                 WriteAlert(_("LYX_ERROR:"),
3507                            _("Cannot open temporary file:"), fname1);
3508                 return;
3509         }
3510         par->table->RoffEndOfCell(fp, -1);
3511         for (i = 0; i < par->size(); ++i) {
3512                 c = par->GetChar(i);
3513                 if (par->table->IsContRow(cell)) {
3514                         if (c == LyXParagraph::META_NEWLINE)
3515                                 cell++;
3516                         continue;
3517                 }
3518                 font2 = par->GetFontSettings(i);
3519                 if (font1.latex() != font2.latex()) {
3520                         if (font2.latex() != LyXFont::OFF)
3521                                 continue;
3522                 }
3523                 switch (c) {
3524                 case LyXParagraph::META_INSET:
3525                         if ((inset = par->GetInset(i))) {
3526                                 if (!(fp2= fopen(fname2.c_str(), "w+"))) {
3527                                         WriteAlert(_("LYX_ERROR:"),
3528                                                    _("Cannot open temporary file:"), fname2);
3529                                         fclose(fp);
3530                                         remove(fname1.c_str());
3531                                         return;
3532                                 }
3533                                 inset->Latex(fp2,-1);
3534                                 rewind(fp2);
3535                                 c = fgetc(fp2);
3536                                 while(!feof(fp2)) {
3537                                         if (c == '\\')
3538                                                 fprintf(fp, "\\\\");
3539                                         else
3540                                                 fputc(c, fp);
3541                                         c = fgetc(fp2);
3542                                 }
3543                                 fclose(fp2);
3544                         }
3545                         break;
3546                 case LyXParagraph::META_NEWLINE:
3547                         if (par->table->CellHasContRow(cell)>= 0)
3548                                 par->RoffContTableRows(fp, i+1, cell);
3549                         par->table->RoffEndOfCell(fp, cell);
3550                         cell++;
3551                         break;
3552                 case LyXParagraph::META_HFILL: 
3553                         break;
3554                 case LyXParagraph::META_PROTECTED_SEPARATOR:
3555                         break;
3556                 case '\\': 
3557                         fprintf(fp, "\\\\");
3558                         break;
3559                 default:
3560                         if (c != '\0')
3561                                 fprintf(fp, "%c", c);
3562                         else if (c == '\0')
3563                                 lyxerr.debug()
3564                                         << "RoffAsciiTable:"
3565                                         " NULL char in structure." << endl;
3566                         break;
3567                 }
3568         }
3569         par->table->RoffEndOfCell(fp, cell);
3570         fclose(fp);
3571         string cmd = lyxrc->ascii_roff_command + " >" + fname2;
3572         cmd = subst(cmd, "$$FName", fname1);
3573         Systemcalls one(Systemcalls::System, cmd);
3574         if (!(lyxerr.debugging(Debug::ROFF))) {
3575                 remove(fname1.c_str());
3576         }
3577         if (!(fp= fopen(fname2.c_str(), "r"))) {
3578                 WriteFSAlert(_("Error! Can't open temporary file:"), fname2);
3579                 return;
3580         }
3581         // now output the produced file
3582         fprintf(file, "\n\n");
3583         c = fgetc(fp);
3584         if (feof(fp))
3585                 WriteAlert(_("Error!"),
3586                            _("Error executing *roff command on table"));
3587         // overread leading blank lines
3588         while(!feof(fp) && (c == '\n'))
3589                 c = fgetc(fp);
3590         while(!feof(fp)) {
3591                 for(j= 0; j<par->depth; j++)
3592                         fprintf(file, "  ");
3593                 while(!feof(fp) && (c != '\n')) {
3594                         fputc(c, file);
3595                         c = fgetc(fp);
3596                 }
3597                 fputc('\n', file);
3598                 // overread trailing blank lines
3599                 while(!feof(fp) && (c == '\n'))
3600                         c = fgetc(fp);
3601         }
3602         fclose(fp);
3603         remove(fname2.c_str());
3604 }
3605
3606         
3607 /// changed Heinrich Bauer, 23/03/98
3608 bool Buffer::isDviClean()
3609 {
3610   if (lyxrc->use_tempdir)
3611     return dvi_clean_tmpd;
3612   else
3613     return dvi_clean_orgd;
3614 }
3615
3616  
3617 /// changed Heinrich Bauer, 23/03/98
3618 void Buffer::markDviClean()
3619 {
3620   if (lyxrc->use_tempdir)
3621     dvi_clean_tmpd = true;
3622   else
3623     dvi_clean_orgd = true;
3624 }
3625
3626
3627 /// changed Heinrich Bauer, 23/03/98
3628 void Buffer::markDviDirty()
3629 {
3630   if (lyxrc->use_tempdir)
3631     dvi_clean_tmpd = false;
3632   else
3633     dvi_clean_orgd = false;
3634 }
3635
3636
3637 void Buffer::update(signed char f)
3638 {
3639         if (!users) return;
3640         
3641         users->owner()->updateLayoutChoice();
3642
3643         if (!text->selection && f > -3)
3644                 text->sel_cursor = text->cursor;
3645         
3646         FreeUpdateTimer();
3647         text->FullRebreak();
3648         users->update();
3649
3650         if (f != 3 && f != -3) {
3651                 users->fitCursor();
3652                 users->updateScrollbar();
3653         }
3654
3655         if (f == 1 || f == -1) {
3656                 if (isLyxClean()) {
3657                         markDirty();
3658                         users->owner()->getMiniBuffer()->setTimer(4);
3659                 } else {
3660                         markDirty();
3661                 }
3662         }
3663 }
3664
3665
3666 void Buffer::validate(LaTeXFeatures & features)
3667 {
3668         LyXParagraph * par = paragraph;
3669         LyXTextClass const & tclass = 
3670                 textclasslist.TextClass(params.textclass);
3671     
3672         // AMS Style is at document level
3673     
3674         features.amsstyle = (params.use_amsmath ||
3675                              tclass.provides(LyXTextClass::amsmath));
3676     
3677         while (par) {
3678                 // We don't use "lyxerr.debug" because of speed. (Asger)
3679                 if (lyxerr.debugging(Debug::LATEX))
3680                         lyxerr << "Paragraph: " <<  par << endl;
3681
3682                 // Now just follow the list of paragraphs and run
3683                 // validate on each of them.
3684                 par->validate(features);
3685
3686                 // and then the next paragraph
3687                 par = par->next;
3688         }
3689
3690         // the bullet shapes are buffer level not paragraph level
3691         // so they are tested here
3692         for (int i = 0; i < 4; ++i) {
3693                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3694                         int font = params.user_defined_bullets[i].getFont();
3695                         if (font == 0) {
3696                                 int c = params
3697                                         .user_defined_bullets[i]
3698                                         .getCharacter();
3699                                 if (c == 16
3700                                    || c == 17
3701                                    || c == 25
3702                                    || c == 26
3703                                    || c == 31) {
3704                                         features.latexsym = true;
3705                                 }
3706                         }
3707                         if (font == 1) {
3708                                 features.amssymb = true;
3709                         }
3710                         else if ((font >= 2 && font <= 5)) {
3711                                 features.pifont = true;
3712                         }
3713                 }
3714         }
3715         
3716         if (lyxerr.debugging(Debug::LATEX)) {
3717                 features.showStruct(params);
3718         }
3719 }
3720
3721
3722 void Buffer::setPaperStuff()
3723 {
3724         params.papersize = BufferParams::PAPER_DEFAULT;
3725         char c1 = params.paperpackage;
3726         if (c1 == BufferParams::PACKAGE_NONE) {
3727                 char c2 = params.papersize2;
3728                 if (c2 == BufferParams::VM_PAPER_USLETTER)
3729                         params.papersize = BufferParams::PAPER_USLETTER;
3730                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3731                         params.papersize = BufferParams::PAPER_LEGALPAPER;
3732                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3733                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3734                 else if (c2 == BufferParams::VM_PAPER_A3)
3735                         params.papersize = BufferParams::PAPER_A3PAPER;
3736                 else if (c2 == BufferParams::VM_PAPER_A4)
3737                         params.papersize = BufferParams::PAPER_A4PAPER;
3738                 else if (c2 == BufferParams::VM_PAPER_A5)
3739                         params.papersize = BufferParams::PAPER_A5PAPER;
3740                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3741                          (c2 == BufferParams::VM_PAPER_B5))
3742                         params.papersize = BufferParams::PAPER_B5PAPER;
3743         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3744                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3745                 params.papersize = BufferParams::PAPER_A4PAPER;
3746 }
3747
3748
3749 #if 0
3750 void Buffer::setOldPaperStuff()
3751 {
3752         char c = params.papersize = params.papersize2;
3753         params.papersize2 = BufferParams::VM_PAPER_DEFAULT;
3754         params.paperpackage = BufferParams::PACKAGE_NONE;
3755         if (c == OLD_PAPER_A4PAPER)
3756                 params.papersize2 = BufferParams::VM_PAPER_A4;
3757         else if (c == OLD_PAPER_A4)
3758                 params.paperpackage = BufferParams::PACKAGE_A4;
3759         else if (c == OLD_PAPER_A4WIDE)
3760                 params.paperpackage = BufferParams::PACKAGE_A4WIDE;
3761         else if (c == OLD_PAPER_WIDEMARGINSA4)
3762                 params.paperpackage = BufferParams::PACKAGE_WIDEMARGINSA4;
3763         else if (c == OLD_PAPER_USLETTER)
3764                 params.papersize2 = BufferParams::VM_PAPER_USLETTER;
3765         else if (c == OLD_PAPER_A5PAPER)
3766                 params.papersize2 = BufferParams::VM_PAPER_A5;
3767         else if (c == OLD_PAPER_B5PAPER)
3768                 params.papersize2 = BufferParams::VM_PAPER_B5;
3769         else if (c == OLD_PAPER_EXECUTIVEPAPER)
3770                 params.papersize2 = BufferParams::VM_PAPER_USEXECUTIVE;
3771         else if (c == OLD_PAPER_LEGALPAPER)
3772                 params.papersize2 = BufferParams::VM_PAPER_USLEGAL;
3773         setPaperStuff();
3774 }
3775 #endif
3776
3777 void Buffer::insertInset(Inset * inset, string const & lout,
3778                          bool no_table)
3779 {
3780         // check for table/list in tables
3781         if (no_table && text->cursor.par->table){
3782                 WriteAlert(_("Impossible Operation!"),
3783                            _("Cannot insert table/list in table."),
3784                            _("Sorry."));
3785                 return;
3786         }
3787         // not quite sure if we want this...
3788         text->SetCursorParUndo();
3789         text->FreezeUndo();
3790         
3791         BeforeChange();
3792         if (!lout.empty()) {
3793                 update(-2);
3794                 text->BreakParagraph();
3795                 update(-1);
3796                 
3797                 if (text->cursor.par->Last()) {
3798                         text->CursorLeft();
3799                         
3800                         text->BreakParagraph();
3801                         update(-1);
3802                 }
3803
3804                 int lay = textclasslist.NumberOfLayout(params.textclass,
3805                                                        lout).second;
3806                 if (lay == -1) // layout not found
3807                         // use default layout "Standard" (0)
3808                         lay = 0;
3809                 
3810                 text->SetLayout(lay);
3811                 
3812                 text->SetParagraph(0, 0,
3813                                    0, 0,
3814                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3815                                    LYX_ALIGN_LAYOUT, 
3816                                    string(),
3817                                    0);
3818                 update(-1);
3819                 
3820                 text->current_font.setLatex(LyXFont::OFF);
3821         }
3822         
3823         text->InsertInset(inset);
3824         update(-1);
3825
3826         text->UnFreezeUndo();   
3827 }
3828
3829
3830 // Open and lock an updatable inset
3831 void Buffer::open_new_inset(UpdatableInset * new_inset)
3832 {
3833         BeforeChange();
3834         text->FinishUndo();
3835         insertInset(new_inset);
3836         text->CursorLeft();
3837         update(1);
3838         new_inset->Edit(0, 0);
3839 }
3840
3841
3842 /* This function should be in Buffer because it's a buffer's property (ale) */
3843 string Buffer::getIncludeonlyList(char delim)
3844 {
3845         string lst;
3846         LyXParagraph * par = paragraph;
3847         LyXParagraph::size_type pos;
3848         Inset * inset;
3849         while (par){
3850                 pos = -1;
3851                 while ((inset = par->ReturnNextInsetPointer(pos))){
3852                         if (inset->LyxCode() == Inset::INCLUDE_CODE) {
3853                                 InsetInclude * insetinc = 
3854                                         static_cast<InsetInclude*>(inset);
3855                                 if (insetinc->isInclude() 
3856                                     && insetinc->isNoLoad()) {
3857                                         if (!lst.empty())
3858                                                 lst += delim;
3859                                         lst += ChangeExtension(insetinc->getContents(), string(), true);
3860                                 }
3861                         }
3862                         pos++;
3863                 } 
3864                 par = par->next;
3865         }
3866         lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3867         return lst;
3868 }
3869
3870
3871 /* This is also a buffer property (ale) */ 
3872 string Buffer::getReferenceList(char delim)
3873 {
3874         /// if this is a child document and the parent is already loaded
3875         /// Use the parent's list instead  [ale990407]
3876         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3877                 Buffer *tmp = bufferlist.getBuffer(params.parentname);
3878                 if (tmp)
3879                   return tmp->getReferenceList(delim);
3880         }
3881
3882         LyXParagraph *par = paragraph;
3883         LyXParagraph::size_type pos;
3884         Inset * inset;
3885         string lst;
3886         while (par){
3887                 pos = -1;
3888                 while ((inset = par->ReturnNextInsetPointer(pos))){     
3889                         for (int i = 0; i < inset->GetNumberOfLabels(); i++) {
3890                                 if (!lst.empty())
3891                                         lst += delim;
3892                                 lst += inset->getLabel(i);
3893                         }
3894                         pos++;
3895                 } 
3896                 par = par->next;
3897         }
3898         lyxerr.debug() << "References(" <<  lst << ")" << endl;
3899         return lst;
3900 }
3901
3902
3903 /* This is also a buffer property (ale) */ 
3904 string Buffer::getBibkeyList(char delim)
3905 {
3906         /// if this is a child document and the parent is already loaded
3907         /// Use the parent's list instead  [ale990412]
3908         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3909                 Buffer *tmp = bufferlist.getBuffer(params.parentname);
3910                 if (tmp)
3911                         return tmp->getBibkeyList(delim);
3912         }
3913
3914         string bibkeys;
3915         LyXParagraph * par = paragraph;
3916         while (par) {
3917                 if (par->bibkey) {
3918                         if (!bibkeys.empty())
3919                                 bibkeys += delim;
3920                         bibkeys += par->bibkey->getContents();
3921                 }
3922                 par = par->next;
3923         }
3924
3925         // Might be either using bibtex or a child has bibliography
3926         if (bibkeys.empty()) {
3927                 par = paragraph;
3928                 while (par) {
3929                         Inset * inset;
3930                         LyXParagraph::size_type pos = -1;
3931
3932                         // Search for Bibtex or Include inset
3933                         while ((inset = par->ReturnNextInsetPointer(pos))) {
3934                                 if (inset-> LyxCode() == Inset::BIBTEX_CODE) {
3935                                         if (!bibkeys.empty())
3936                                                 bibkeys += delim;
3937                                         bibkeys += static_cast<InsetBibtex*>(inset)->getKeys();
3938                                 } else if (inset-> LyxCode() == Inset::INCLUDE_CODE) {
3939                                         string bk = static_cast<InsetInclude*>(inset)->getKeys();
3940                                         if (!bk.empty()) {
3941                                                 if (!bibkeys.empty())
3942                                                         bibkeys += delim;
3943                                                 bibkeys += bk;
3944                                         }
3945                                 }
3946                                 pos++;
3947                         }
3948                         par = par->next;
3949                 }
3950         }
3951  
3952         lyxerr.debug() << "Bibkeys(" << bibkeys << ")" << endl;
3953         return bibkeys;
3954 }
3955
3956
3957 /* This is also a buffer property (ale) */
3958 // Not so sure about that. a goto Label function can not be buffer local, just
3959 // think how this will work in a multiwindo/buffer environment, all the
3960 // cursors in all the views showing this buffer will move. (Lgb)
3961 // OK, then no cursor action should be allowed in buffer. (ale)
3962 bool Buffer::gotoLabel(string const & label)
3963
3964 {
3965         LyXParagraph * par = paragraph;
3966         LyXParagraph::size_type pos;
3967         Inset * inset;
3968         while (par) {
3969                 pos = -1;
3970                 while ((inset = par->ReturnNextInsetPointer(pos))){     
3971                         for (int i = 0; i < inset->GetNumberOfLabels(); i++) {
3972                                 if (label == inset->getLabel(i)) {
3973                                         BeforeChange();
3974                                         text->SetCursor(par, pos);
3975                                         text->sel_cursor = text->cursor;
3976                                         update(0);
3977                                         return true;
3978                                 }
3979                         }
3980                         pos++;
3981                 } 
3982                 par = par->next;
3983         }
3984         return false;
3985 }
3986
3987
3988 bool Buffer::isDepClean(string const & name) const
3989 {
3990         DEPCLEAN * item = dep_clean;
3991         while (item && item->master != name)
3992                 item = item->next;
3993         if (!item) return true;
3994         return item->clean;
3995 }
3996
3997
3998 void Buffer::markDepClean(string const & name)
3999 {
4000         if (!dep_clean) {
4001                 dep_clean = new DEPCLEAN;
4002                 dep_clean->clean = true;
4003                 dep_clean->master = name;
4004                 dep_clean->next = 0;
4005         } else {
4006                 DEPCLEAN* item = dep_clean;
4007                 while (item && item->master != name)
4008                         item = item->next;
4009                 if (item) {
4010                         item->clean = true;
4011                 } else {
4012                         item = new DEPCLEAN;
4013                         item->clean = true;
4014                         item->master = name;
4015                         item->next = 0;;
4016                 }
4017         }
4018 }