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