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