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