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