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