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