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