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