]> git.lyx.org Git - features.git/blob - src/buffer.C
Another clean-up patch from Angus
[features.git] / src / buffer.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2000 The LyX Team.
8  *
9  *           This file is Copyright 1996-1999
10  *           Lars Gullik Bjønnes
11  *
12  * ====================================================== 
13  */
14
15 #include <config.h>
16
17 #include <fstream>
18 #include <iomanip>
19
20 #include <cstdlib>
21 #include <unistd.h>
22 #include <sys/types.h>
23 #include <utime.h>
24
25 #include <algorithm>
26
27 #ifdef __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                         InsetCommandParams p( "Include" );
893                         Inset * inset = new InsetInclude(p, this);
894                         inset->Read(this, lex);
895                         par->InsertInset(pos, inset, font);
896                         ++pos;
897                 } else if (tmptok == "ERT") {
898                         Inset * inset = new InsetERT;
899                         inset->Read(this, lex);
900                         par->InsertInset(pos, inset, font);
901                         ++pos;
902                 } else if (tmptok == "Tabular") {
903                         Inset * inset = new InsetTabular(this);
904                         inset->Read(this, lex);
905                         par->InsertInset(pos, inset, font);
906                         ++pos;
907                 } else if (tmptok == "Text") {
908                         Inset * inset = new InsetText;
909                         inset->Read(this, lex);
910                         par->InsertInset(pos, inset, font);
911                         ++pos;
912                 } else if (tmptok == "Foot") {
913                         Inset * inset = new InsetFoot;
914                         inset->Read(this, lex);
915                         par->InsertInset(pos, inset, font);
916                         ++pos;
917                 } else if (tmptok == "Marginal") {
918                         Inset * inset = new InsetMarginal;
919                         inset->Read(this, lex);
920                         par->InsertInset(pos, inset, font);
921                         ++pos;
922                 } else if (tmptok == "Minipage") {
923                         Inset * inset = new InsetMinipage;
924                         inset->Read(this, lex);
925                         par->InsertInset(pos, inset, font);
926                         ++pos;
927                 } else if (tmptok == "Float") {
928                         lex.next();
929                         string tmptok = lex.GetString();
930                         Inset * inset = new InsetFloat(tmptok);
931                         inset->Read(this, lex);
932                         par->InsertInset(pos, inset, font);
933                         ++pos;
934                 } else if (tmptok == "List") {
935                         Inset * inset = new InsetList;
936                         inset->Read(this, lex);
937                         par->InsertInset(pos, inset, font);
938                         ++pos;
939                 } else if (tmptok == "Theorem") {
940                         Inset * inset = new InsetList;
941                         inset->Read(this, lex);
942                         par->InsertInset(pos, inset, font);
943                         ++pos;
944                 } else if (tmptok == "Caption") {
945                         Inset * inset = new InsetCaption;
946                         inset->Read(this, lex);
947                         par->InsertInset(pos, inset, font);
948                         ++pos;
949                 } else if (tmptok == "Graphics") {
950                         Inset * inset = new InsetGraphics;
951             inset->Read(this, lex);
952                         par->InsertInset(pos, inset, font);
953             ++pos;
954                 } else if (tmptok == "LatexCommand") {
955                         InsetCommandParams inscmd;
956                         inscmd.Read(lex);
957                         Inset * inset = 0;
958                         if (inscmd.getCmdName() == "cite") {
959                                 inset = new InsetCitation(inscmd);
960                         } else if (inscmd.getCmdName() == "bibitem") {
961                                 lex.printError("Wrong place for bibitem");
962                                 inset = new InsetBibKey(inscmd);
963                         } else if (inscmd.getCmdName() == "BibTeX") {
964                                 inset = new InsetBibtex(inscmd, this);
965                         } else if (inscmd.getCmdName() == "index") {
966                                 inset = new InsetIndex(inscmd);
967                         } else if (inscmd.getCmdName() == "include") {
968                                 inset = new InsetInclude(inscmd, this);
969                         } else if (inscmd.getCmdName() == "label") {
970                                 inset = new InsetLabel(inscmd);
971                         } else if (inscmd.getCmdName() == "url"
972                                    || inscmd.getCmdName() == "htmlurl") {
973                                 inset = new InsetUrl(inscmd);
974                         } else if (inscmd.getCmdName() == "ref"
975                                    || inscmd.getCmdName() == "pageref"
976                                    || inscmd.getCmdName() == "vref"
977                                    || inscmd.getCmdName() == "vpageref"
978                                    || inscmd.getCmdName() == "prettyref") {
979                                 if (!inscmd.getOptions().empty() || !inscmd.getContents().empty()) {
980                                         inset = new InsetRef(inscmd, this);
981                                 }
982                         } else if (inscmd.getCmdName() == "tableofcontents"
983                                    || inscmd.getCmdName() == "listofalgorithms"
984                                    || inscmd.getCmdName() == "listoffigures"
985                                    || inscmd.getCmdName() == "listoftables") {
986                                 inset = new InsetTOC(inscmd);
987                         } else if (inscmd.getCmdName() == "printindex") {
988                                 inset = new InsetPrintIndex(inscmd);
989                         } else if (inscmd.getCmdName() == "lyxparent") {
990                                 inset = new InsetParent(inscmd, this);
991                         }
992                                
993                         if (inset) {
994                                 par->InsertInset(pos, inset, font);
995                                 ++pos;
996                         }
997                 }
998 #endif
999         } else if (token == "\\SpecialChar") {
1000                 LyXLayout const & layout =
1001                         textclasslist.Style(params.textclass, 
1002                                             par->GetLayout());
1003
1004                 // Insets don't make sense in a free-spacing context! ---Kayvan
1005                 if (layout.free_spacing) {
1006                         if (lex.IsOK()) {
1007                                 lex.next();
1008                                 string next_token = lex.GetString();
1009                                 if (next_token == "\\-") {
1010                                         par->InsertChar(pos, '-', font);
1011                                 } else if (next_token == "\\protected_separator"
1012                                         || next_token == "~") {
1013                                         par->InsertChar(pos, ' ', font);
1014                                 } else {
1015                                         lex.printError("Token `$$Token' "
1016                                                        "is in free space "
1017                                                        "paragraph layout!");
1018                                         --pos;
1019                                 }
1020                         }
1021                 } else {
1022                         Inset * inset = new InsetSpecialChar;
1023                         inset->Read(this, lex);
1024                         par->InsertInset(pos, inset, font);
1025                 }
1026                 ++pos;
1027         } else if (token == "\\newline") {
1028                 par->InsertChar(pos, LyXParagraph::META_NEWLINE, font);
1029                 ++pos;
1030         } else if (token == "\\LyXTable") {
1031 #ifdef NEW_TABULAR
1032                 Inset * inset = new InsetTabular(this);
1033                 inset->Read(this, lex);
1034                 par->InsertInset(pos, inset, font);
1035                 ++pos;
1036 #else
1037                 par->table = new LyXTable(lex);
1038 #endif
1039         } else if (token == "\\hfill") {
1040                 par->InsertChar(pos, LyXParagraph::META_HFILL, font);
1041                 ++pos;
1042         } else if (token == "\\protected_separator") { // obsolete
1043                 // This is a backward compability thingie. (Lgb)
1044                 // Remove it later some time...introduced with fileformat
1045                 // 2.16. (Lgb)
1046                 LyXLayout const & layout =
1047                         textclasslist.Style(params.textclass, 
1048                                             par->GetLayout());
1049
1050                 if (layout.free_spacing) {
1051                         par->InsertChar(pos, ' ', font);
1052                 } else {
1053                         Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1054                         par->InsertInset(pos, inset, font);
1055                 }
1056                 ++pos;
1057         } else if (token == "\\bibitem") {  // ale970302
1058                 if (!par->bibkey) {
1059                         InsetCommandParams p( "bibitem" );
1060                         par->bibkey = new InsetBibKey(p);
1061                 }
1062                 par->bibkey->Read(this, lex);                   
1063         }else if (token == "\\backslash") {
1064                 par->InsertChar(pos, '\\', font);
1065                 ++pos;
1066         }else if (token == "\\the_end") {
1067                 the_end_read = true;
1068         } else {
1069                 // This should be insurance for the future: (Asger)
1070                 lex.printError("Unknown token `$$Token'. "
1071                                "Inserting as text.");
1072                 for(string::const_iterator cit = token.begin();
1073                     cit != token.end(); ++cit) {
1074                         par->InsertChar(pos, (*cit), font);
1075                         ++pos;
1076                 }
1077         }
1078         return the_end_read;
1079 }
1080
1081
1082 void Buffer::readInset(LyXLex & lex, LyXParagraph *& par,
1083                        int & pos, LyXFont & font)
1084 {
1085         // consistency check
1086         if (lex.GetString() != "\\begin_inset") {
1087                 lyxerr << "Buffer::readInset: Consistency check failed."
1088                        << endl;
1089         }
1090         
1091         lex.next();
1092         string tmptok = lex.GetString();
1093         last_inset_read = tmptok;
1094         // test the different insets
1095         if (tmptok == "Quotes") {
1096                 Inset * inset = new InsetQuotes;
1097                 inset->Read(this, lex);
1098                 par->InsertInset(pos, inset, font);
1099                 ++pos;
1100         } else if (tmptok == "External") {
1101                 Inset * inset = new InsetExternal;
1102                 inset->Read(this, lex);
1103                 par->InsertInset(pos, inset, font);
1104                 ++pos;
1105         } else if (tmptok == "FormulaMacro") {
1106                 Inset * inset = new InsetFormulaMacro;
1107                 inset->Read(this, lex);
1108                 par->InsertInset(pos, inset, font);
1109                 ++pos;
1110         } else if (tmptok == "Formula") {
1111                 Inset * inset = new InsetFormula;
1112                 inset->Read(this, lex);
1113                 par->InsertInset(pos, inset, font);
1114                 ++pos;
1115         } else if (tmptok == "Figure") {
1116                 Inset * inset = new InsetFig(100, 100, this);
1117                 inset->Read(this, lex);
1118                 par->InsertInset(pos, inset, font);
1119                 ++pos;
1120         } else if (tmptok == "Info") {
1121                 Inset * inset = new InsetInfo;
1122                 inset->Read(this, lex);
1123                 par->InsertInset(pos, inset, font);
1124                 ++pos;
1125         } else if (tmptok == "Include") {
1126                 InsetCommandParams p( "Include" );
1127                 Inset * inset = new InsetInclude(p, this);
1128                 inset->Read(this, lex);
1129                 par->InsertInset(pos, inset, font);
1130                 ++pos;
1131         } else if (tmptok == "ERT") {
1132                 Inset * inset = new InsetERT;
1133                 inset->Read(this, lex);
1134                 par->InsertInset(pos, inset, font);
1135                 ++pos;
1136         } else if (tmptok == "Tabular") {
1137                 Inset * inset = new InsetTabular(this);
1138                 inset->Read(this, lex);
1139                 par->InsertInset(pos, inset, font);
1140                 ++pos;
1141         } else if (tmptok == "Text") {
1142                 Inset * inset = new InsetText;
1143                 inset->Read(this, lex);
1144                 par->InsertInset(pos, inset, font);
1145                 ++pos;
1146         } else if (tmptok == "Foot") {
1147                 Inset * inset = new InsetFoot;
1148                 inset->Read(this, lex);
1149                 par->InsertInset(pos, inset, font);
1150                 ++pos;
1151         } else if (tmptok == "Marginal") {
1152                 Inset * inset = new InsetMarginal;
1153                 inset->Read(this, lex);
1154                 par->InsertInset(pos, inset, font);
1155                 ++pos;
1156         } else if (tmptok == "Minipage") {
1157                 Inset * inset = new InsetMinipage;
1158                 inset->Read(this, lex);
1159                 par->InsertInset(pos, inset, font);
1160                 ++pos;
1161         } else if (tmptok == "Float") {
1162                 lex.next();
1163                 string tmptok = lex.GetString();
1164                 Inset * inset = new InsetFloat(tmptok);
1165                 inset->Read(this, lex);
1166                 par->InsertInset(pos, inset, font);
1167                 ++pos;
1168         } else if (tmptok == "List") {
1169                 Inset * inset = new InsetList;
1170                 inset->Read(this, lex);
1171                 par->InsertInset(pos, inset, font);
1172                 ++pos;
1173         } else if (tmptok == "Theorem") {
1174                 Inset * inset = new InsetList;
1175                 inset->Read(this, lex);
1176                 par->InsertInset(pos, inset, font);
1177                 ++pos;
1178         } else if (tmptok == "Caption") {
1179                 Inset * inset = new InsetCaption;
1180                 inset->Read(this, lex);
1181                 par->InsertInset(pos, inset, font);
1182                 ++pos;
1183         } else if (tmptok == "GRAPHICS") {
1184                 Inset * inset = new InsetGraphics;
1185                                 //inset->Read(this, lex);
1186                 par->InsertInset(pos, inset, font);
1187         } else if (tmptok == "LatexCommand") {
1188                 InsetCommandParams inscmd;
1189                 inscmd.Read(lex);
1190                 Inset * inset = 0;
1191                 if (inscmd.getCmdName() == "cite") {
1192                         inset = new InsetCitation(inscmd);
1193                 } else if (inscmd.getCmdName() == "bibitem") {
1194                         lex.printError("Wrong place for bibitem");
1195                         inset = new InsetBibKey(inscmd);
1196                 } else if (inscmd.getCmdName() == "BibTeX") {
1197                         inset = new InsetBibtex(inscmd, this);
1198                 } else if (inscmd.getCmdName() == "index") {
1199                         inset = new InsetIndex(inscmd);
1200                 } else if (inscmd.getCmdName() == "include") {
1201                         inset = new InsetInclude(inscmd, this);
1202                 } else if (inscmd.getCmdName() == "label") {
1203                         inset = new InsetLabel(inscmd);
1204                 } else if (inscmd.getCmdName() == "url"
1205                            || inscmd.getCmdName() == "htmlurl") {
1206                         inset = new InsetUrl(inscmd);
1207                 } else if (inscmd.getCmdName() == "ref"
1208                            || inscmd.getCmdName() == "pageref"
1209                            || inscmd.getCmdName() == "vref"
1210                            || inscmd.getCmdName() == "vpageref"
1211                            || inscmd.getCmdName() == "prettyref") {
1212                         if (!inscmd.getOptions().empty()
1213                             || !inscmd.getContents().empty()) {
1214                                 inset = new InsetRef(inscmd, this);
1215                         }
1216                 } else if (inscmd.getCmdName() == "tableofcontents"
1217                            || inscmd.getCmdName() == "listofalgorithms"
1218                            || inscmd.getCmdName() == "listoffigures"
1219                            || inscmd.getCmdName() == "listoftables") {
1220                         inset = new InsetTOC(inscmd);
1221                 } else if (inscmd.getCmdName() == "printindex") {
1222                         inset = new InsetPrintIndex(inscmd);
1223                 } else if (inscmd.getCmdName() == "lyxparent") {
1224                         inset = new InsetParent(inscmd, this);
1225                 }
1226                 
1227                 if (inset) {
1228                         par->InsertInset(pos, inset, font);
1229                         ++pos;
1230                 }
1231         }
1232 }
1233
1234
1235 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
1236 {
1237         string token;
1238
1239         if (lex.IsOK()) {
1240                 lex.next();
1241                 token = lex.GetString();
1242                 if (token == "\\lyxformat") { // the first token _must_ be...
1243                         lex.next();
1244                         format = lex.GetFloat();
1245                         if (format > 1) {
1246                                 if (LYX_FORMAT - format > 0.05) {
1247                                         printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
1248                                                LYX_FORMAT, format);
1249                                 }
1250                                 if (format - LYX_FORMAT > 0.05) {
1251                                         printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
1252                                                LYX_FORMAT, format);
1253                                 }
1254                                 bool the_end = readLyXformat2(lex, par);
1255                                 // Formats >= 2.13 support "\the_end" marker
1256                                 if (format < 2.13)
1257                                         the_end = true;
1258
1259                                 setPaperStuff();
1260
1261                                 if (!the_end)
1262                                         WriteAlert(_("Warning!"),
1263                                                    _("Reading of document is not complete"),
1264                                                    _("Maybe the document is truncated"));
1265                                 // We simulate a safe reading anyways to allow
1266                                 // users to take the chance... (Asger)
1267                                 return true;
1268                         } // format < 1
1269                         else {
1270                                 WriteAlert(_("ERROR!"),
1271                                            _("Old LyX file format found. "
1272                                              "Use LyX 0.10.x to read this!"));
1273                                 return false;
1274                         }
1275
1276                 } else { // "\\lyxformat" not found
1277                         WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1278                 }
1279         } else
1280                 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1281         return false;
1282 }
1283                     
1284
1285
1286 // Should probably be moved to somewhere else: BufferView? LyXView?
1287 bool Buffer::save() const
1288 {
1289         // We don't need autosaves in the immediate future. (Asger)
1290         resetAutosaveTimers();
1291
1292         // make a backup
1293         string s;
1294         if (lyxrc.make_backup) {
1295                 s = fileName() + '~';
1296                 if (!lyxrc.backupdir_path.empty())
1297                         s = AddName(lyxrc.backupdir_path,
1298                                     subst(CleanupPath(s),'/','!'));
1299
1300                 // Rename is the wrong way of making a backup,
1301                 // this is the correct way.
1302                 /* truss cp fil fil2:
1303                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1304                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1305                    open("LyXVC.lyx", O_RDONLY)                     = 3
1306                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1307                    fstat(4, 0xEFFFF508)                            = 0
1308                    fstat(3, 0xEFFFF508)                            = 0
1309                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1310                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1311                    read(3, 0xEFFFD4A0, 8192)                       = 0
1312                    close(4)                                        = 0
1313                    close(3)                                        = 0
1314                    chmod("LyXVC3.lyx", 0100644)                    = 0
1315                    lseek(0, 0, SEEK_CUR)                           = 46440
1316                    _exit(0)
1317                 */
1318
1319                 // Should proabaly have some more error checking here.
1320                 // Should be cleaned up in 0.13, at least a bit.
1321                 // Doing it this way, also makes the inodes stay the same.
1322                 // This is still not a very good solution, in particular we
1323                 // might loose the owner of the backup.
1324                 FileInfo finfo(fileName());
1325                 if (finfo.exist()) {
1326                         mode_t fmode = finfo.getMode();
1327                         struct utimbuf times = {
1328                                 finfo.getAccessTime(),
1329                                 finfo.getModificationTime() };
1330
1331                         ifstream ifs(fileName().c_str());
1332                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1333                         if (ifs && ofs) {
1334                                 ofs << ifs.rdbuf();
1335                                 ifs.close();
1336                                 ofs.close();
1337                                 ::chmod(s.c_str(), fmode);
1338                                 
1339                                 if (::utime(s.c_str(), &times)) {
1340                                         lyxerr << "utime error." << endl;
1341                                 }
1342                         } else {
1343                                 lyxerr << "LyX was not able to make "
1344                                         "backupcopy. Beware." << endl;
1345                         }
1346                 }
1347         }
1348         
1349         if (writeFile(fileName(), false)) {
1350                 markLyxClean();
1351
1352                 // now delete the autosavefile
1353                 string a = OnlyPath(fileName());
1354                 a += '#';
1355                 a += OnlyFilename(fileName());
1356                 a += '#';
1357                 FileInfo fileinfo(a);
1358                 if (fileinfo.exist()) {
1359                         if (::remove(a.c_str()) != 0) {
1360                                 WriteFSAlert(_("Could not delete "
1361                                                "auto-save file!"), a);
1362                         }
1363                 }
1364         } else {
1365                 // Saving failed, so backup is not backup
1366                 if (lyxrc.make_backup) {
1367                         ::rename(s.c_str(), fileName().c_str());
1368                 }
1369                 return false;
1370         }
1371         return true;
1372 }
1373
1374
1375 // Returns false if unsuccesful
1376 bool Buffer::writeFile(string const & fname, bool flag) const
1377 {
1378         // if flag is false writeFile will not create any GUI
1379         // warnings, only cerr.
1380         // Needed for autosave in background or panic save (Matthias 120496)
1381
1382         if (read_only && (fname == filename)) {
1383                 // Here we should come with a question if we should
1384                 // perform the write anyway.
1385                 if (flag)
1386                         lyxerr << _("Error! Document is read-only: ")
1387                                << fname << endl;
1388                 else
1389                         WriteAlert(_("Error! Document is read-only: "),
1390                                    fname);
1391                 return false;
1392         }
1393
1394         FileInfo finfo(fname);
1395         if (finfo.exist() && !finfo.writable()) {
1396                 // Here we should come with a question if we should
1397                 // try to do the save anyway. (i.e. do a chmod first)
1398                 if (flag)
1399                         lyxerr << _("Error! Cannot write file: ")
1400                                << fname << endl;
1401                 else
1402                         WriteFSAlert(_("Error! Cannot write file: "),
1403                                      fname);
1404                 return false;
1405         }
1406
1407         ofstream ofs(fname.c_str());
1408         if (!ofs) {
1409                 if (flag)
1410                         lyxerr << _("Error! Cannot open file: ")
1411                                << fname << endl;
1412                 else
1413                         WriteFSAlert(_("Error! Cannot open file: "),
1414                                      fname);
1415                 return false;
1416         }
1417         // The top of the file should not be written by params.
1418
1419         // write out a comment in the top of the file
1420         ofs << '#' << LYX_DOCVERSION 
1421             << " created this file. For more info see http://www.lyx.org/\n";
1422         ofs.setf(ios::showpoint|ios::fixed);
1423         ofs.precision(2);
1424         ofs << "\\lyxformat " << setw(4) <<  LYX_FORMAT << "\n";
1425
1426         // now write out the buffer paramters.
1427         params.writeFile(ofs);
1428
1429         char footnoteflag = 0;
1430         char depth = 0;
1431
1432         // this will write out all the paragraphs
1433         // using recursive descent.
1434         paragraph->writeFile(this, ofs, params, footnoteflag, depth);
1435
1436         // Write marker that shows file is complete
1437         ofs << "\n\\the_end" << endl;
1438         ofs.close();
1439         // how to check if close went ok?
1440         return true;
1441 }
1442
1443
1444 void Buffer::writeFileAscii(string const & fname, int linelen) 
1445 {
1446         LyXFont font1, font2;
1447         Inset * inset;
1448         char c, footnoteflag = 0, depth = 0;
1449         string tmp;
1450         LyXParagraph::size_type i;
1451         int j;
1452         int ltype = 0;
1453         int ltype_depth = 0;
1454         int actcell = 0;
1455         int actpos = 0;
1456 #ifndef NEW_TABULAR
1457         int h;
1458         int * clen = 0;
1459         int cell = 0;
1460         int cells = 0;
1461 #endif
1462         int currlinelen = 0;
1463         long fpos = 0;
1464         bool ref_printed = false;
1465
1466         ofstream ofs(fname.c_str());
1467         if (!ofs) {
1468                 WriteFSAlert(_("Error: Cannot write file:"), fname);
1469                 return;
1470         }
1471
1472         string fname1 = TmpFileName();
1473         LyXParagraph * par = paragraph;
1474         while (par) {
1475                 int noparbreak = 0;
1476                 int islatex = 0;
1477                 if (
1478 #ifndef NEW_INSETS
1479                         par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1480 #endif
1481                     !par->previous
1482 #ifndef NEW_INSETS
1483                     || par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE
1484 #endif
1485                         ){
1486
1487 #ifndef NEW_INSETS
1488                         /* begins a footnote environment ? */ 
1489                         if (footnoteflag != par->footnoteflag) {
1490                                 footnoteflag = par->footnoteflag;
1491                                 if (footnoteflag) {
1492                                         j = strlen(string_footnotekinds[par->footnotekind])+4;
1493                                         if (currlinelen + j > linelen)
1494                                                 ofs << "\n";
1495                                         ofs << "(["
1496                                             << string_footnotekinds[par->footnotekind] << "] ";
1497                                         currlinelen += j;
1498                                 }
1499                         }
1500 #endif
1501          
1502                         /* begins or ends a deeper area ?*/ 
1503                         if (depth != par->depth) {
1504                                 if (par->depth > depth) {
1505                                         while (par->depth > depth) {
1506                                                 ++depth;
1507                                         }
1508                                 }
1509                                 else {
1510                                         while (par->depth < depth) {
1511                                                 --depth;
1512                                         }
1513                                 }
1514                         }
1515          
1516                         /* First write the layout */
1517                         tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1518                         if (tmp == "Itemize") {
1519                                 ltype = 1;
1520                                 ltype_depth = depth+1;
1521                         } else if (tmp == "Enumerate") {
1522                                 ltype = 2;
1523                                 ltype_depth = depth+1;
1524                         } else if (strstr(tmp.c_str(), "ection")) {
1525                                 ltype = 3;
1526                                 ltype_depth = depth+1;
1527                         } else if (strstr(tmp.c_str(), "aragraph")) {
1528                                 ltype = 4;
1529                                 ltype_depth = depth+1;
1530                         } else if (tmp == "Description") {
1531                                 ltype = 5;
1532                                 ltype_depth = depth+1;
1533                         } else if (tmp == "Abstract") {
1534                                 ltype = 6;
1535                                 ltype_depth = 0;
1536                         } else if (tmp == "Bibliography") {
1537                                 ltype = 7;
1538                                 ltype_depth = 0;
1539                         } else {
1540                                 ltype = 0;
1541                                 ltype_depth = 0;
1542                         }
1543          
1544                         /* maybe some vertical spaces */ 
1545
1546                         /* the labelwidthstring used in lists */ 
1547          
1548                         /* some lines? */ 
1549          
1550                         /* some pagebreaks? */ 
1551          
1552                         /* noindent ? */ 
1553          
1554                         /* what about the alignment */ 
1555                 } else {
1556 #ifndef NEW_INSETS
1557                         /* dummy layout, that means a footnote ended */ 
1558                         footnoteflag = LyXParagraph::NO_FOOTNOTE;
1559                         ofs << ") ";
1560                         noparbreak = 1;
1561 #else
1562                         lyxerr << "Should this ever happen?" << endl;
1563 #endif
1564                 }
1565       
1566                 //LyXLayout const & layout =
1567                 //      textclasslist.Style(params.textclass, 
1568                 //                          par->GetLayout()); // unused
1569                 //bool free_spc = layout.free_spacing; //unused
1570
1571 #ifndef NEW_TABULAR
1572                 /* It might be a table */ 
1573                 if (par->table){
1574                         cell = 1;
1575                         actcell = 0;
1576                         cells = par->table->columns;
1577                         clen = new int [cells];
1578                         memset(clen, 0, sizeof(int) * cells);
1579
1580                         for (i = 0, j = 0, h = 1; i < par->size(); ++i, ++h) {
1581                                 c = par->GetChar(i);
1582                                 if (c == LyXParagraph::META_INSET) {
1583                                         if ((inset = par->GetInset(i))) {
1584 #ifdef HAVE_SSTREAM
1585                                                 std::ostringstream ost;
1586                                                 inset->Ascii(this, ost);
1587                                                 h += ost.str().length();
1588 #else
1589                                                 ostrstream ost;
1590                                                 inset->Ascii(this, ost);
1591                                                 ost << '\0';
1592                                                 char * tmp = ost.str();
1593                                                 string tstr(tmp);
1594                                                 h += tstr.length();
1595                                                 delete [] tmp;
1596 #endif
1597                                         }
1598                                 } else if (c == LyXParagraph::META_NEWLINE) {
1599                                         if (clen[j] < h)
1600                                                 clen[j] = h;
1601                                         h = 0;
1602                                         j = (++j) % par->table->NumberOfCellsInRow(actcell);
1603                                         ++actcell;
1604                                 }
1605                         }
1606                         if (clen[j] < h)
1607                                 clen[j] = h;
1608                 }
1609 #endif
1610                 font1 = LyXFont(LyXFont::ALL_INHERIT, params.language_info);
1611                 actcell = 0;
1612                 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1613                         if (!i && !footnoteflag && !noparbreak){
1614                                 ofs << "\n\n";
1615                                 for(j = 0; j < depth; ++j)
1616                                         ofs << "  ";
1617                                 currlinelen = depth * 2;
1618                                 switch(ltype) {
1619                                 case 0: /* Standard */
1620                                 case 4: /* (Sub)Paragraph */
1621                                 case 5: /* Description */
1622                                         break;
1623                                 case 6: /* Abstract */
1624                                         ofs << "Abstract\n\n";
1625                                         break;
1626                                 case 7: /* Bibliography */
1627                                         if (!ref_printed) {
1628                                                 ofs << "References\n\n";
1629                                                 ref_printed = true;
1630                                         }
1631                                         break;
1632                                 default:
1633                                         ofs << par->labelstring << " ";
1634                                         break;
1635                                 }
1636                                 if (ltype_depth > depth) {
1637                                         for(j = ltype_depth - 1; j > depth; --j)
1638                                                 ofs << "  ";
1639                                         currlinelen += (ltype_depth-depth)*2;
1640                                 }
1641 #ifndef NEW_TABULAR
1642                                 if (par->table) {
1643                                         for(j = 0; j < cells; ++j) {
1644                                                 ofs << '+';
1645                                                 for(h = 0; h < (clen[j] + 1);
1646                                                     ++h)
1647                                                         ofs << '-';
1648                                         }
1649                                         ofs << "+\n";
1650                                         for(j = 0; j < depth; ++j)
1651                                                 ofs << "  ";
1652                                         currlinelen = depth * 2;
1653                                         if (ltype_depth > depth) {
1654                                                 for(j = ltype_depth;
1655                                                     j > depth; --j)
1656                                                         ofs << "  ";
1657                                                 currlinelen += (ltype_depth-depth)*2;
1658                                         }
1659                                         ofs << "| ";
1660                                 }
1661 #endif
1662                         }
1663                         font2 = par->GetFontSettings(params, i);
1664                         if (font1.latex() != font2.latex()) {
1665                                 if (font2.latex() == LyXFont::OFF)
1666                                         islatex = 0;
1667                                 else
1668                                         islatex = 1;
1669                         } else {
1670                                 islatex = 0;
1671                         }
1672                         c = par->GetChar(i);
1673                         if (islatex)
1674                                 continue;
1675                         switch (c) {
1676                         case LyXParagraph::META_INSET:
1677                                 if ((inset = par->GetInset(i))) {
1678                                         fpos = ofs.tellp();
1679                                         inset->Ascii(this, ofs);
1680                                         currlinelen += (ofs.tellp() - fpos);
1681                                         actpos += (ofs.tellp() - fpos) - 1;
1682                                 }
1683                                 break;
1684                         case LyXParagraph::META_NEWLINE:
1685 #ifndef NEW_TABULAR
1686                                 if (par->table) {
1687                                         if (par->table->NumberOfCellsInRow(actcell) <= cell) {
1688                                                 for(j = actpos; j < clen[cell - 1]; ++j)
1689                                                         ofs << ' ';
1690                                                 ofs << " |\n";
1691                                                 for(j = 0; j < depth; ++j)
1692                                                         ofs << "  ";
1693                                                 currlinelen = depth*2;
1694                                                 if (ltype_depth > depth) {
1695                                                         for(j = ltype_depth; j > depth; --j)
1696                                                                 ofs << "  ";
1697                                                         currlinelen += (ltype_depth-depth) * 2;
1698                                                 }
1699                                                 for(j = 0; j < cells; ++j) {
1700                                                         ofs << '+';
1701                                                         for(h = 0; h < (clen[j] + 1); ++h)
1702                                                                 ofs << '-';
1703                                                 }
1704                                                 ofs << "+\n";
1705                                                 for(j = 0; j < depth; ++j)
1706                                                         ofs << "  ";
1707                                                 currlinelen = depth * 2;
1708                                                 if (ltype_depth > depth) {
1709                                                         for(j = ltype_depth;
1710                                                             j > depth; --j)
1711                                                                 ofs << "  ";
1712                                                         currlinelen += (ltype_depth-depth)*2;
1713                                                 }
1714                                                 ofs << "| ";
1715                                                 cell = 1;
1716                                         } else {
1717                                                 for(j = actpos;
1718                                                     j < clen[cell - 1]; ++j)
1719                                                         ofs << ' ';
1720                                                 ofs << " | ";
1721                                                 ++cell;
1722                                         }
1723                                         ++actcell;
1724                                         currlinelen = actpos = 0;
1725                                 } else {
1726 #endif
1727                                         ofs << "\n";
1728                                         for(j = 0; j < depth; ++j)
1729                                                 ofs << "  ";
1730                                         currlinelen = depth * 2;
1731                                         if (ltype_depth > depth) {
1732                                                 for(j = ltype_depth;
1733                                                     j > depth; --j)
1734                                                         ofs << "  ";
1735                                                 currlinelen += (ltype_depth - depth) * 2;
1736                                         }
1737 #ifndef NEW_TABULAR
1738                                 }
1739 #endif
1740                                 break;
1741                         case LyXParagraph::META_HFILL: 
1742                                 ofs << "\t";
1743                                 break;
1744                         case '\\':
1745                                 ofs << "\\";
1746                                 break;
1747                         default:
1748                                 if (currlinelen > linelen - 10
1749                                     && c == ' ' && i + 2 < par->size()) {
1750                                         ofs << "\n";
1751                                         for(j = 0; j < depth; ++j)
1752                                                 ofs << "  ";
1753                                         currlinelen = depth * 2;
1754                                         if (ltype_depth > depth) {
1755                                                 for(j = ltype_depth;
1756                                                     j > depth; --j)
1757                                                         ofs << "  ";
1758                                                 currlinelen += (ltype_depth-depth)*2;
1759                                         }
1760                                 } else if (c != '\0')
1761                                         ofs << c;
1762                                 else if (c == '\0')
1763                                         lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1764                                 ++currlinelen;
1765                                 break;
1766                         }
1767                 }
1768 #ifndef NEW_TABULAR
1769                 if (par->table) {
1770                         for(j = actpos; j < clen[cell - 1]; ++j)
1771                                 ofs << ' ';
1772                         ofs << " |\n";
1773                         for(j = 0; j < depth; ++j)
1774                                 ofs << "  ";
1775                         currlinelen = depth * 2;
1776                         if (ltype_depth > depth) {
1777                                 for(j = ltype_depth; j > depth; --j)
1778                                         ofs << "  ";
1779                                 currlinelen += (ltype_depth - depth) * 2;
1780                         }
1781                         for(j = 0; j < cells; ++j) {
1782                                 ofs << '+';
1783                                 for(h = 0; h < (clen[j] + 1); ++h)
1784                                         ofs << '-';
1785                         }
1786                         ofs << "+\n";
1787                         delete [] clen;    
1788                 }
1789 #endif
1790                 par = par->next;
1791         }
1792    
1793         ofs << "\n";
1794 }
1795
1796
1797 void Buffer::makeLaTeXFile(string const & fname, 
1798                            string const & original_path,
1799                            bool nice, bool only_body)
1800 {
1801         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1802         
1803         niceFile = nice; // this will be used by Insetincludes.
1804
1805         tex_code_break_column = lyxrc.ascii_linelen;
1806
1807         LyXTextClass const & tclass =
1808                 textclasslist.TextClass(params.textclass);
1809
1810         ofstream ofs(fname.c_str());
1811         if (!ofs) {
1812                 WriteFSAlert(_("Error: Cannot open file: "), fname);
1813                 return;
1814         }
1815         
1816         // validate the buffer.
1817         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1818         LaTeXFeatures features(params, tclass.numLayouts());
1819         validate(features);
1820         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1821         
1822         texrow.reset();
1823         // The starting paragraph of the coming rows is the 
1824         // first paragraph of the document. (Asger)
1825         texrow.start(paragraph, 0);
1826
1827         if (!only_body && nice) {
1828                 ofs << "%% " LYX_DOCVERSION " created this file.  "
1829                         "For more info, see http://www.lyx.org/.\n"
1830                         "%% Do not edit unless you really know what "
1831                         "you are doing.\n";
1832                 texrow.newline();
1833                 texrow.newline();
1834         }
1835         lyxerr.debug() << "lyx header finished" << endl;
1836         // There are a few differences between nice LaTeX and usual files:
1837         // usual is \batchmode and has a 
1838         // special input@path to allow the including of figures
1839         // with either \input or \includegraphics (what figinsets do).
1840         // batchmode is not set if there is a tex_code_break_column.
1841         // In this case somebody is interested in the generated LaTeX,
1842         // so this is OK. input@path is set when the actual parameter
1843         // original_path is set. This is done for usual tex-file, but not
1844         // for nice-latex-file. (Matthias 250696)
1845         if (!only_body) {
1846                 if (!nice){
1847                         // code for usual, NOT nice-latex-file
1848                         ofs << "\\batchmode\n"; // changed
1849                         // from \nonstopmode
1850                         texrow.newline();
1851                 }
1852                 if (!original_path.empty()) {
1853                         ofs << "\\makeatletter\n"
1854                             << "\\def\\input@path{{"
1855                             << original_path << "/}}\n"
1856                             << "\\makeatother\n";
1857                         texrow.newline();
1858                         texrow.newline();
1859                         texrow.newline();
1860                 }
1861                 
1862                 ofs << "\\documentclass";
1863                 
1864                 string options; // the document class options.
1865                 
1866                 if (tokenPos(tclass.opt_fontsize(),
1867                              '|', params.fontsize) >= 0) {
1868                         // only write if existing in list (and not default)
1869                         options += params.fontsize;
1870                         options += "pt,";
1871                 }
1872                 
1873                 
1874                 if (!params.use_geometry &&
1875                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1876                         switch (params.papersize) {
1877                         case BufferParams::PAPER_A4PAPER:
1878                                 options += "a4paper,";
1879                                 break;
1880                         case BufferParams::PAPER_USLETTER:
1881                                 options += "letterpaper,";
1882                                 break;
1883                         case BufferParams::PAPER_A5PAPER:
1884                                 options += "a5paper,";
1885                                 break;
1886                         case BufferParams::PAPER_B5PAPER:
1887                                 options += "b5paper,";
1888                                 break;
1889                         case BufferParams::PAPER_EXECUTIVEPAPER:
1890                                 options += "executivepaper,";
1891                                 break;
1892                         case BufferParams::PAPER_LEGALPAPER:
1893                                 options += "legalpaper,";
1894                                 break;
1895                         }
1896                 }
1897
1898                 // if needed
1899                 if (params.sides != tclass.sides()) {
1900                         switch (params.sides) {
1901                         case LyXTextClass::OneSide:
1902                                 options += "oneside,";
1903                                 break;
1904                         case LyXTextClass::TwoSides:
1905                                 options += "twoside,";
1906                                 break;
1907                         }
1908
1909                 }
1910
1911                 // if needed
1912                 if (params.columns != tclass.columns()) {
1913                         if (params.columns == 2)
1914                                 options += "twocolumn,";
1915                         else
1916                                 options += "onecolumn,";
1917                 }
1918
1919                 if (!params.use_geometry 
1920                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1921                         options += "landscape,";
1922                 
1923                 // language should be a parameter to \documentclass
1924                 bool use_babel = false;
1925                 if (params.language_info->lang() == "hebrew") // This seems necessary
1926                         features.UsedLanguages.insert(default_language);
1927                 if (params.language != "default" ||
1928                     !features.UsedLanguages.empty() ) {
1929                         use_babel = true;
1930                         for (LaTeXFeatures::LanguageList::const_iterator cit =
1931                                      features.UsedLanguages.begin();
1932                              cit != features.UsedLanguages.end(); ++cit)
1933                                 options += (*cit)->lang() + ",";
1934                         options += params.language_info->lang() + ',';
1935                 }
1936
1937                 // the user-defined options
1938                 if (!params.options.empty()) {
1939                         options += params.options + ',';
1940                 }
1941                 
1942                 if (!options.empty()){
1943                         options = strip(options, ',');
1944                         ofs << '[' << options << ']';
1945                 }
1946                 
1947                 ofs << '{'
1948                     << textclasslist.LatexnameOfClass(params.textclass)
1949                     << "}\n";
1950                 texrow.newline();
1951                 // end of \documentclass defs
1952                 
1953                 // font selection must be done before loading fontenc.sty
1954                 if (params.fonts != "default") {
1955                         ofs << "\\usepackage{" << params.fonts << "}\n";
1956                         texrow.newline();
1957                 }
1958                 // this one is not per buffer
1959                 if (lyxrc.fontenc != "default") {
1960                         ofs << "\\usepackage[" << lyxrc.fontenc
1961                             << "]{fontenc}\n";
1962                         texrow.newline();
1963                 }
1964
1965                 if (params.inputenc == "auto") {
1966                         string doc_encoding =
1967                                 params.language_info->encoding()->LatexName();
1968
1969                         // Create a list with all the input encodings used 
1970                         // in the document
1971                         set<string> encodings;
1972                         for (LaTeXFeatures::LanguageList::const_iterator it =
1973                                      features.UsedLanguages.begin();
1974                              it != features.UsedLanguages.end(); ++it)
1975                                 if ((*it)->encoding()->LatexName() != doc_encoding)
1976                                         encodings.insert((*it)->encoding()->LatexName());
1977
1978                         ofs << "\\usepackage[";
1979                         for (set<string>::const_iterator it = encodings.begin();
1980                              it != encodings.end(); ++it)
1981                                 ofs << *it << ",";
1982                         ofs << doc_encoding << "]{inputenc}\n";
1983                         texrow.newline();
1984                 } else if (params.inputenc != "default") {
1985                         ofs << "\\usepackage[" << params.inputenc
1986                             << "]{inputenc}\n";
1987                         texrow.newline();
1988                 }
1989
1990                 // At the very beginning the text parameters.
1991                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1992                         switch (params.paperpackage) {
1993                         case BufferParams::PACKAGE_A4:
1994                                 ofs << "\\usepackage{a4}\n";
1995                                 texrow.newline();
1996                                 break;
1997                         case BufferParams::PACKAGE_A4WIDE:
1998                                 ofs << "\\usepackage{a4wide}\n";
1999                                 texrow.newline();
2000                                 break;
2001                         case BufferParams::PACKAGE_WIDEMARGINSA4:
2002                                 ofs << "\\usepackage[widemargins]{a4}\n";
2003                                 texrow.newline();
2004                                 break;
2005                         }
2006                 }
2007                 if (params.use_geometry) {
2008                         ofs << "\\usepackage{geometry}\n";
2009                         texrow.newline();
2010                         ofs << "\\geometry{verbose";
2011                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2012                                 ofs << ",landscape";
2013                         switch (params.papersize2) {
2014                         case BufferParams::VM_PAPER_CUSTOM:
2015                                 if (!params.paperwidth.empty())
2016                                         ofs << ",paperwidth="
2017                                             << params.paperwidth;
2018                                 if (!params.paperheight.empty())
2019                                         ofs << ",paperheight="
2020                                             << params.paperheight;
2021                                 break;
2022                         case BufferParams::VM_PAPER_USLETTER:
2023                                 ofs << ",letterpaper";
2024                                 break;
2025                         case BufferParams::VM_PAPER_USLEGAL:
2026                                 ofs << ",legalpaper";
2027                                 break;
2028                         case BufferParams::VM_PAPER_USEXECUTIVE:
2029                                 ofs << ",executivepaper";
2030                                 break;
2031                         case BufferParams::VM_PAPER_A3:
2032                                 ofs << ",a3paper";
2033                                 break;
2034                         case BufferParams::VM_PAPER_A4:
2035                                 ofs << ",a4paper";
2036                                 break;
2037                         case BufferParams::VM_PAPER_A5:
2038                                 ofs << ",a5paper";
2039                                 break;
2040                         case BufferParams::VM_PAPER_B3:
2041                                 ofs << ",b3paper";
2042                                 break;
2043                         case BufferParams::VM_PAPER_B4:
2044                                 ofs << ",b4paper";
2045                                 break;
2046                         case BufferParams::VM_PAPER_B5:
2047                                 ofs << ",b5paper";
2048                                 break;
2049                         default:
2050                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2051                                 switch (lyxrc.default_papersize) {
2052                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2053                                 case BufferParams::PAPER_USLETTER:
2054                                         ofs << ",letterpaper";
2055                                         break;
2056                                 case BufferParams::PAPER_LEGALPAPER:
2057                                         ofs << ",legalpaper";
2058                                         break;
2059                                 case BufferParams::PAPER_EXECUTIVEPAPER:
2060                                         ofs << ",executivepaper";
2061                                         break;
2062                                 case BufferParams::PAPER_A3PAPER:
2063                                         ofs << ",a3paper";
2064                                         break;
2065                                 case BufferParams::PAPER_A4PAPER:
2066                                         ofs << ",a4paper";
2067                                         break;
2068                                 case BufferParams::PAPER_A5PAPER:
2069                                         ofs << ",a5paper";
2070                                         break;
2071                                 case BufferParams::PAPER_B5PAPER:
2072                                         ofs << ",b5paper";
2073                                         break;
2074                                 }
2075                         }
2076                         if (!params.topmargin.empty())
2077                                 ofs << ",tmargin=" << params.topmargin;
2078                         if (!params.bottommargin.empty())
2079                                 ofs << ",bmargin=" << params.bottommargin;
2080                         if (!params.leftmargin.empty())
2081                                 ofs << ",lmargin=" << params.leftmargin;
2082                         if (!params.rightmargin.empty())
2083                                 ofs << ",rmargin=" << params.rightmargin;
2084                         if (!params.headheight.empty())
2085                                 ofs << ",headheight=" << params.headheight;
2086                         if (!params.headsep.empty())
2087                                 ofs << ",headsep=" << params.headsep;
2088                         if (!params.footskip.empty())
2089                                 ofs << ",footskip=" << params.footskip;
2090                         ofs << "}\n";
2091                         texrow.newline();
2092                 }
2093                 if (params.use_amsmath
2094                     && !tclass.provides(LyXTextClass::amsmath)) {
2095                         ofs << "\\usepackage{amsmath}\n";
2096                         texrow.newline();
2097                 }
2098
2099                 if (tokenPos(tclass.opt_pagestyle(),
2100                              '|', params.pagestyle) >= 0) {
2101                         if (params.pagestyle == "fancy") {
2102                                 ofs << "\\usepackage{fancyhdr}\n";
2103                                 texrow.newline();
2104                         }
2105                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2106                         texrow.newline();
2107                 }
2108
2109                 // We try to load babel late, in case it interferes
2110                 // with other packages.
2111                 if (use_babel) {
2112                         ofs << lyxrc.language_package << endl;
2113                         texrow.newline();
2114                 }
2115
2116                 if (params.secnumdepth != tclass.secnumdepth()) {
2117                         ofs << "\\setcounter{secnumdepth}{"
2118                             << params.secnumdepth
2119                             << "}\n";
2120                         texrow.newline();
2121                 }
2122                 if (params.tocdepth != tclass.tocdepth()) {
2123                         ofs << "\\setcounter{tocdepth}{"
2124                             << params.tocdepth
2125                             << "}\n";
2126                         texrow.newline();
2127                 }
2128                 
2129                 if (params.paragraph_separation) {
2130                         switch (params.defskip.kind()) {
2131                         case VSpace::SMALLSKIP: 
2132                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2133                                 break;
2134                         case VSpace::MEDSKIP:
2135                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2136                                 break;
2137                         case VSpace::BIGSKIP:
2138                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2139                                 break;
2140                         case VSpace::LENGTH:
2141                                 ofs << "\\setlength\\parskip{"
2142                                     << params.defskip.length().asLatexString()
2143                                     << "}\n";
2144                                 break;
2145                         default: // should never happen // Then delete it.
2146                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2147                                 break;
2148                         }
2149                         texrow.newline();
2150                         
2151                         ofs << "\\setlength\\parindent{0pt}\n";
2152                         texrow.newline();
2153                 }
2154
2155                 // Now insert the LyX specific LaTeX commands...
2156
2157                 // The optional packages;
2158                 string preamble(features.getPackages());
2159
2160                 // this might be useful...
2161                 preamble += "\n\\makeatletter\n";
2162
2163                 // Some macros LyX will need
2164                 string tmppreamble(features.getMacros());
2165
2166                 if (!tmppreamble.empty()) {
2167                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2168                                 "LyX specific LaTeX commands.\n"
2169                                 + tmppreamble + '\n';
2170                 }
2171
2172                 // the text class specific preamble 
2173                 tmppreamble = features.getTClassPreamble();
2174                 if (!tmppreamble.empty()) {
2175                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2176                                 "Textclass specific LaTeX commands.\n"
2177                                 + tmppreamble + '\n';
2178                 }
2179
2180                 /* the user-defined preamble */
2181                 if (!params.preamble.empty()) {
2182                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2183                                 "User specified LaTeX commands.\n"
2184                                 + params.preamble + '\n';
2185                 }
2186
2187                 preamble += "\\makeatother\n";
2188
2189                 // Itemize bullet settings need to be last in case the user
2190                 // defines their own bullets that use a package included
2191                 // in the user-defined preamble -- ARRae
2192                 // Actually it has to be done much later than that
2193                 // since some packages like frenchb make modifications
2194                 // at \begin{document} time -- JMarc 
2195                 string bullets_def;
2196                 for (int i = 0; i < 4; ++i) {
2197                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2198                                 if (bullets_def.empty())
2199                                         bullets_def="\\AtBeginDocument{\n";
2200                                 bullets_def += "  \\renewcommand{\\labelitemi";
2201                                 switch (i) {
2202                                 // `i' is one less than the item to modify
2203                                 case 0:
2204                                         break;
2205                                 case 1:
2206                                         bullets_def += 'i';
2207                                         break;
2208                                 case 2:
2209                                         bullets_def += "ii";
2210                                         break;
2211                                 case 3:
2212                                         bullets_def += 'v';
2213                                         break;
2214                                 }
2215                                 bullets_def += "}{" + 
2216                                   params.user_defined_bullets[i].getText() 
2217                                   + "}\n";
2218                         }
2219                 }
2220
2221                 if (!bullets_def.empty())
2222                   preamble += bullets_def + "}\n\n";
2223
2224                 for (int j = countChar(preamble, '\n'); j-- ;) {
2225                         texrow.newline();
2226                 }
2227
2228                 ofs << preamble;
2229
2230                 // make the body.
2231                 ofs << "\\begin{document}\n";
2232                 texrow.newline();
2233         } // only_body
2234         lyxerr.debug() << "preamble finished, now the body." << endl;
2235         if (!lyxrc.language_auto_begin && params.language != "default") {
2236                 ofs << subst(lyxrc.language_command_begin, "$$lang",
2237                              params.language)
2238                     << endl;
2239                 texrow.newline();
2240         }
2241         
2242         latexParagraphs(ofs, paragraph, 0, texrow);
2243
2244         // add this just in case after all the paragraphs
2245         ofs << endl;
2246         texrow.newline();
2247
2248         if (!lyxrc.language_auto_end && params.language != "default") {
2249                 ofs << subst(lyxrc.language_command_end, "$$lang",
2250                              params.language)
2251                     << endl;
2252                 texrow.newline();
2253         }
2254
2255         if (!only_body) {
2256                 ofs << "\\end{document}\n";
2257                 texrow.newline();
2258         
2259                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2260         } else {
2261                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2262                                      << endl;
2263         }
2264
2265         // Just to be sure. (Asger)
2266         texrow.newline();
2267
2268         // tex_code_break_column's value is used to decide
2269         // if we are in batchmode or not (within mathed_write()
2270         // in math_write.C) so we must set it to a non-zero
2271         // value when we leave otherwise we save incorrect .lyx files.
2272         tex_code_break_column = lyxrc.ascii_linelen;
2273
2274         ofs.close();
2275         if (ofs.fail()) {
2276                 lyxerr << "File was not closed properly." << endl;
2277         }
2278         
2279         lyxerr.debug() << "Finished making latex file." << endl;
2280 }
2281
2282
2283 //
2284 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2285 //
2286 void Buffer::latexParagraphs(ostream & ofs, LyXParagraph * par,
2287                              LyXParagraph * endpar, TexRow & texrow) const
2288 {
2289         bool was_title = false;
2290         bool already_title = false;
2291 #ifdef HAVE_SSTREAM
2292         std::ostringstream ftnote;
2293 #else
2294         char * tmpholder = 0;
2295 #endif
2296         TexRow ft_texrow;
2297         int ftcount = 0;
2298
2299         // if only_body
2300         while (par != endpar) {
2301 #ifndef HAVE_SSTREAM
2302                 ostrstream ftnote;
2303                 if (tmpholder) {
2304                         ftnote << tmpholder;
2305                         delete [] tmpholder;
2306                         tmpholder = 0;
2307                 }
2308 #endif
2309 #ifndef NEW_INSETS
2310                 if (par->IsDummy())
2311                         lyxerr[Debug::LATEX] << "Error in latexParagraphs."
2312                                              << endl;
2313 #endif
2314                 LyXLayout const & layout =
2315                         textclasslist.Style(params.textclass,
2316                                             par->layout);
2317             
2318                 if (layout.intitle) {
2319                         if (already_title) {
2320                                 lyxerr <<"Error in latexParagraphs: You"
2321                                         " should not mix title layouts"
2322                                         " with normal ones." << endl;
2323                         } else
2324                                 was_title = true;
2325                 } else if (was_title && !already_title) {
2326                         ofs << "\\maketitle\n";
2327                         texrow.newline();
2328                         already_title = true;
2329                         was_title = false;                  
2330                 }
2331                 // We are at depth 0 so we can just use
2332                 // ordinary \footnote{} generation
2333                 // flag this with ftcount
2334                 ftcount = -1;
2335                 if (layout.isEnvironment()
2336                     || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2337                         par = par->TeXEnvironment(this, params, ofs, texrow
2338 #ifndef NEW_INSETS
2339                                                   ,ftnote, ft_texrow, ftcount
2340 #endif
2341                                 );
2342                 } else {
2343                         par = par->TeXOnePar(this, params, ofs, texrow, false
2344 #ifndef NEW_INSETS
2345                                              ,
2346                                              ftnote, ft_texrow, ftcount
2347 #endif
2348                                 );
2349                 }
2350
2351                 // Write out what we've generated...
2352                 if (ftcount >= 1) {
2353                         if (ftcount > 1) {
2354                                 ofs << "\\addtocounter{footnote}{-"
2355                                     << ftcount - 1
2356                                     << '}';
2357                         }
2358                         ofs << ftnote.str();
2359                         texrow += ft_texrow;
2360 #ifdef HAVE_SSTREAM
2361                         // The extra .c_str() is needed when we use
2362                         // lyxstring instead of the STL string class. 
2363                         ftnote.str(string().c_str());
2364 #else
2365                         delete [] ftnote.str();
2366 #endif
2367                         ft_texrow.reset();
2368                         ftcount = 0;
2369                 }
2370 #ifndef HAVE_SSTREAM
2371                 else {
2372                         // I hate strstreams
2373                         tmpholder = ftnote.str();
2374                 }
2375 #endif
2376         }
2377 #ifndef HAVE_SSTREAM
2378         delete [] tmpholder;
2379 #endif
2380         // It might be that we only have a title in this document
2381         if (was_title && !already_title) {
2382                 ofs << "\\maketitle\n";
2383                 texrow.newline();
2384         }
2385 }
2386
2387
2388 bool Buffer::isLatex() const
2389 {
2390         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2391 }
2392
2393
2394 bool Buffer::isLinuxDoc() const
2395 {
2396         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2397 }
2398
2399
2400 bool Buffer::isLiterate() const
2401 {
2402         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2403 }
2404
2405
2406 bool Buffer::isDocBook() const
2407 {
2408         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2409 }
2410
2411
2412 bool Buffer::isSGML() const
2413 {
2414         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2415                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2416 }
2417
2418
2419 void Buffer::sgmlOpenTag(ostream & os, int depth,
2420                          string const & latexname) const
2421 {
2422         os << string(depth, ' ') << "<" << latexname << ">\n";
2423 }
2424
2425
2426 void Buffer::sgmlCloseTag(ostream & os, int depth,
2427                           string const & latexname) const
2428 {
2429         os << string(depth, ' ') << "</" << latexname << ">\n";
2430 }
2431
2432
2433 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2434 {
2435         LyXParagraph * par = paragraph;
2436
2437         niceFile = nice; // this will be used by Insetincludes.
2438
2439         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2440         string environment_stack[10];
2441         string item_name;
2442
2443         int depth = 0; // paragraph depth
2444
2445         ofstream ofs(fname.c_str());
2446
2447         if (!ofs) {
2448                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2449                 return;
2450         }
2451
2452         LyXTextClass const & tclass =
2453                 textclasslist.TextClass(params.textclass);
2454
2455         LaTeXFeatures features(params, tclass.numLayouts());
2456         validate(features);
2457
2458         //if(nice)
2459         tex_code_break_column = lyxrc.ascii_linelen;
2460         //else
2461         //tex_code_break_column = 0;
2462
2463         texrow.reset();
2464
2465         if (!body_only) {
2466                 string sgml_includedfiles=features.getIncludedFiles();
2467
2468                 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2469                         ofs << "<!doctype linuxdoc system>\n\n";
2470                 } else {
2471                         ofs << "<!doctype linuxdoc system [ "
2472                             << params.preamble << sgml_includedfiles << " \n]>\n\n";
2473                 }
2474
2475                 if(params.options.empty())
2476                         sgmlOpenTag(ofs, 0, top_element);
2477                 else {
2478                         string top = top_element;
2479                         top += " ";
2480                         top += params.options;
2481                         sgmlOpenTag(ofs, 0, top);
2482                 }
2483         }
2484
2485         ofs << "<!-- "  << LYX_DOCVERSION 
2486             << " created this file. For more info see http://www.lyx.org/"
2487             << " -->\n";
2488
2489         while (par) {
2490                 int desc_on = 0; // description mode
2491                 LyXLayout const & style =
2492                         textclasslist.Style(params.textclass,
2493                                             par->layout);
2494
2495                 // treat <toc> as a special case for compatibility with old code
2496                 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2497                         Inset * inset = par->GetInset(0);
2498                         Inset::Code lyx_code = inset->LyxCode();
2499                         if (lyx_code == Inset::TOC_CODE){
2500                                 string temp = "toc";
2501                                 sgmlOpenTag(ofs, depth, temp);
2502
2503                                 par = par->next;
2504 #ifndef NEW_INSETS
2505                                 linuxDocHandleFootnote(ofs, par, depth);
2506 #endif
2507                                 continue;
2508                         }
2509                 }
2510
2511                 // environment tag closing
2512                 for( ; depth > par->depth; --depth) {
2513                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2514                         environment_stack[depth].erase();
2515                 }
2516
2517                 // write opening SGML tags
2518                 switch(style.latextype) {
2519                 case LATEX_PARAGRAPH:
2520                         if(depth == par->depth 
2521                            && !environment_stack[depth].empty()) {
2522                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2523                                 environment_stack[depth].erase();
2524                                 if(depth) 
2525                                         --depth;
2526                                 else
2527                                         ofs << "</p>";
2528                         }
2529                         sgmlOpenTag(ofs, depth, style.latexname());
2530                         break;
2531
2532                 case LATEX_COMMAND:
2533                         if (depth!= 0)
2534                                 LinuxDocError(par, 0,
2535                                               _("Error : Wrong depth for"
2536                                                 " LatexType Command.\n"));
2537
2538                         if (!environment_stack[depth].empty()){
2539                                 sgmlCloseTag(ofs, depth,
2540                                              environment_stack[depth]);
2541                                 ofs << "</p>";
2542                         }
2543
2544                         environment_stack[depth].erase();
2545                         sgmlOpenTag(ofs, depth, style.latexname());
2546                         break;
2547
2548                 case LATEX_ENVIRONMENT:
2549                 case LATEX_ITEM_ENVIRONMENT:
2550                         if(depth == par->depth 
2551                            && environment_stack[depth] != style.latexname()
2552                            && !environment_stack[depth].empty()) {
2553
2554                                 sgmlCloseTag(ofs, depth,
2555                                              environment_stack[depth]);
2556                                 environment_stack[depth].erase();
2557                         }
2558                         if (depth < par->depth) {
2559                                depth = par->depth;
2560                                environment_stack[depth].erase();
2561                         }
2562                         if (environment_stack[depth] != style.latexname()) {
2563                                 if(depth == 0) {
2564                                         string temp = "p";
2565                                         sgmlOpenTag(ofs, depth, temp);
2566                                 }
2567                                 environment_stack[depth] = style.latexname();
2568                                 sgmlOpenTag(ofs, depth,
2569                                             environment_stack[depth]);
2570                         }
2571                         if(style.latextype == LATEX_ENVIRONMENT) break;
2572
2573                         desc_on = (style.labeltype == LABEL_MANUAL);
2574
2575                         if(desc_on)
2576                                 item_name = "tag";
2577                         else
2578                                 item_name = "item";
2579
2580                         sgmlOpenTag(ofs, depth + 1, item_name);
2581                         break;
2582                 default:
2583                         sgmlOpenTag(ofs, depth, style.latexname());
2584                         break;
2585                 }
2586
2587 #ifndef NEW_INSETS
2588                 do {
2589 #endif
2590                         SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2591
2592                         par = par->next;
2593 #ifndef NEW_INSETS
2594                         linuxDocHandleFootnote(ofs, par, depth);
2595                 }
2596                 while(par && par->IsDummy());
2597 #endif
2598
2599                 ofs << "\n";
2600                 // write closing SGML tags
2601                 switch(style.latextype) {
2602                 case LATEX_COMMAND:
2603                 case LATEX_ENVIRONMENT:
2604                 case LATEX_ITEM_ENVIRONMENT:
2605                         break;
2606                 default:
2607                         sgmlCloseTag(ofs, depth, style.latexname());
2608                         break;
2609                 }
2610         }
2611    
2612         // Close open tags
2613         for(; depth > 0; --depth)
2614                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2615
2616         if(!environment_stack[depth].empty())
2617                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2618
2619         if (!body_only) {
2620                 ofs << "\n\n";
2621                 sgmlCloseTag(ofs, 0, top_element);
2622         }
2623
2624         ofs.close();
2625         // How to check for successful close
2626 }
2627
2628
2629 #ifndef NEW_INSETS
2630 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2631                                     int const depth)
2632 {
2633         string tag = "footnote";
2634
2635         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2636                 sgmlOpenTag(os, depth + 1, tag);
2637                 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2638                 sgmlCloseTag(os, depth + 1, tag);
2639                 par = par->next;
2640         }
2641 }
2642 #endif
2643
2644
2645 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2646                                   int const depth, int desc_on,
2647                                   LyXParagraph * & par)
2648 {
2649         LyXParagraph * tpar = par;
2650         while (tpar
2651 #ifndef NEW_INSETS
2652                && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE)
2653 #endif
2654                && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2655                                                              "Caption").second))
2656                 tpar = tpar->next;
2657         if (tpar &&
2658             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2659                                                          "Caption").second) {
2660                 sgmlOpenTag(os, depth + 1, inner_tag);
2661                 string extra_par;
2662                 SimpleDocBookOnePar(os, extra_par, tpar,
2663                                     desc_on, depth + 2);
2664                 sgmlCloseTag(os, depth+1, inner_tag);
2665                 if(!extra_par.empty())
2666                         os << extra_par;
2667         }
2668 }
2669
2670
2671 #ifndef NEW_INSETS
2672 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2673                                    int const depth)
2674 {
2675         string tag, inner_tag;
2676         string tmp_par, extra_par;
2677         bool inner_span = false;
2678         int desc_on = 4;
2679
2680         // Someone should give this enum a proper name (Lgb)
2681         enum SOME_ENUM {
2682                 NO_ONE,
2683                 FOOTNOTE_LIKE,
2684                 MARGIN_LIKE,
2685                 FIG_LIKE,
2686                 TAB_LIKE
2687         };
2688         SOME_ENUM last = NO_ONE;
2689         SOME_ENUM present = FOOTNOTE_LIKE;
2690
2691         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2692                 if(last == present) {
2693                         if(inner_span) {
2694                                 if(!tmp_par.empty()) {
2695                                         os << tmp_par;
2696                                         tmp_par.erase();
2697                                         sgmlCloseTag(os, depth + 1, inner_tag);
2698                                         sgmlOpenTag(os, depth + 1, inner_tag);
2699                                 }
2700                         } else {
2701                                 os << "\n";
2702                         }
2703                 } else {
2704                         os << tmp_par;
2705                         if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2706                                                             inner_tag);
2707                         if(!extra_par.empty()) os << extra_par;
2708                         if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2709                         extra_par.erase();
2710
2711                         switch (par->footnotekind) {
2712                         case LyXParagraph::FOOTNOTE:
2713                         case LyXParagraph::ALGORITHM:
2714                                 tag = "footnote";
2715                                 inner_tag = "para";
2716                                 present = FOOTNOTE_LIKE;
2717                                 inner_span = true;
2718                                 break;
2719                         case LyXParagraph::MARGIN:
2720                                 tag = "sidebar";
2721                                 inner_tag = "para";
2722                                 present = MARGIN_LIKE;
2723                                 inner_span = true;
2724                                 break;
2725                         case LyXParagraph::FIG:
2726                         case LyXParagraph::WIDE_FIG:
2727                                 tag = "figure";
2728                                 inner_tag = "title";
2729                                 present = FIG_LIKE;
2730                                 inner_span = false;
2731                                 break;
2732                         case LyXParagraph::TAB:
2733                         case LyXParagraph::WIDE_TAB:
2734                                 tag = "table";
2735                                 inner_tag = "title";
2736                                 present = TAB_LIKE;
2737                                 inner_span = false;
2738                                 break;
2739                         }
2740                         sgmlOpenTag(os, depth, tag);
2741                         if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2742                                 DocBookHandleCaption(os, inner_tag, depth,
2743                                                      desc_on, par);
2744                                 inner_tag.erase();
2745                         } else {
2746                                 sgmlOpenTag(os, depth + 1, inner_tag);
2747                         }
2748                 }
2749                 // ignore all caption here, we processed them above!!!
2750                 if (par->layout != textclasslist
2751                     .NumberOfLayout(params.textclass,
2752                                     "Caption").second) {
2753 #ifdef HAVE_SSTREAM
2754                         std::ostringstream ost;
2755 #else
2756                         ostrstream ost;
2757 #endif
2758                         SimpleDocBookOnePar(ost, extra_par, par,
2759                                             desc_on, depth + 2);
2760 #ifdef HAVE_SSTREAM
2761                         tmp_par += ost.str().c_str();
2762 #else
2763                         ost << '\0';
2764                         char * ctmp = ost.str();
2765                         tmp_par += ctmp;
2766                         delete [] ctmp;
2767 #endif
2768                 }
2769                 tmp_par = frontStrip(strip(tmp_par));
2770
2771                 last = present;
2772                 par = par->next;
2773         }
2774         os << tmp_par;
2775         if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2776         if(!extra_par.empty()) os << extra_par;
2777         if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2778 }
2779 #endif
2780
2781
2782 // push a tag in a style stack
2783 void Buffer::push_tag(ostream & os, char const * tag,
2784                       int & pos, char stack[5][3])
2785 {
2786         // pop all previous tags
2787         for (int j = pos; j >= 0; --j)
2788                 os << "</" << stack[j] << ">";
2789
2790         // add new tag
2791         sprintf(stack[++pos], "%s", tag);
2792
2793         // push all tags
2794         for (int i = 0; i <= pos; ++i)
2795                 os << "<" << stack[i] << ">";
2796 }
2797
2798
2799 void Buffer::pop_tag(ostream & os, char const * tag,
2800                      int & pos, char stack[5][3])
2801 {
2802         int j;
2803
2804         // pop all tags till specified one
2805         for (j = pos; (j >= 0) && (strcmp(stack[j], tag)); --j)
2806                 os << "</" << stack[j] << ">";
2807
2808         // closes the tag
2809         os << "</" << tag << ">";
2810
2811         // push all tags, but the specified one
2812         for (j = j + 1; j <= pos; ++j) {
2813                 os << "<" << stack[j] << ">";
2814                 strcpy(stack[j-1], stack[j]);
2815         }
2816         --pos;
2817 }
2818
2819
2820 // Handle internal paragraph parsing -- layout already processed.
2821
2822 // checks, if newcol chars should be put into this line
2823 // writes newline, if necessary.
2824 static
2825 void linux_doc_line_break(ostream & os, unsigned int & colcount,
2826                           const unsigned int newcol)
2827 {
2828         colcount += newcol;
2829         if (colcount > lyxrc.ascii_linelen) {
2830                 os << "\n";
2831                 colcount = newcol; // assume write after this call
2832         }
2833 }
2834
2835
2836 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2837                                   int desc_on, int const /*depth*/)
2838 {
2839         LyXFont font1, font2;
2840         char c;
2841         Inset * inset;
2842         LyXParagraph::size_type main_body;
2843         int j;
2844         LyXLayout const & style = textclasslist.Style(params.textclass,
2845                                                       par->GetLayout());
2846
2847         char family_type = 0;               // family font flag 
2848         bool is_bold     = false;           // series font flag 
2849         char shape_type  = 0;               // shape font flag 
2850         bool is_em = false;                 // emphasis (italic) font flag 
2851
2852         int stack_num = -1;          // style stack position
2853         // Can this be rewritten to use a std::stack, please. (Lgb)
2854         char stack[5][3];            // style stack 
2855         unsigned int char_line_count = 5;     // Heuristic choice ;-) 
2856
2857         if (style.labeltype != LABEL_MANUAL)
2858                 main_body = 0;
2859         else
2860                 main_body = par->BeginningOfMainBody();
2861
2862         // gets paragraph main font
2863         if (main_body > 0)
2864                 font1 = style.labelfont;
2865         else
2866                 font1 = style.font;
2867
2868   
2869         // parsing main loop
2870         for (LyXParagraph::size_type i = 0;
2871              i < par->size(); ++i) {
2872
2873                 // handle quote tag
2874                 if (i == main_body
2875 #ifndef NEW_INSETS
2876                     && !par->IsDummy()
2877 #endif
2878                         ) {
2879                         if (main_body > 0)
2880                                 font1 = style.font;
2881                 }
2882
2883                 font2 = par->getFont(params, i);
2884
2885                 if (font1.family() != font2.family()) {
2886                         switch(family_type) {
2887                         case 0:
2888                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2889                                         push_tag(os, "tt", stack_num, stack);
2890                                         family_type = 1;
2891                                 }
2892                                 else if (font2.family() == LyXFont::SANS_FAMILY) {
2893                                         push_tag(os, "sf", stack_num, stack);
2894                                         family_type = 2;
2895                                 }
2896                                 break;
2897                         case 1:
2898                                 pop_tag(os, "tt", stack_num, stack);
2899                                 if (font2.family() == LyXFont::SANS_FAMILY) {
2900                                         push_tag(os, "sf", stack_num, stack);
2901                                         family_type = 2;
2902                                 } else {
2903                                         family_type = 0;
2904                                 }
2905                                 break;
2906                         case 2:
2907                                 pop_tag(os, "sf", stack_num, stack);
2908                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2909                                         push_tag(os, "tt", stack_num, stack);
2910                                         family_type = 1;
2911                                 } else {
2912                                         family_type = 0;
2913                                 }
2914                         }
2915                 }
2916
2917                 // handle bold face
2918                 if (font1.series() != font2.series()) {
2919                         if (font2.series() == LyXFont::BOLD_SERIES) {
2920                                 push_tag(os, "bf", stack_num, stack);
2921                                 is_bold = true;
2922                         } else if (is_bold) {
2923                                 pop_tag(os, "bf", stack_num, stack);
2924                                 is_bold = false;
2925                         }
2926                 }
2927
2928                 // handle italic and slanted fonts
2929                 if (font1.shape() != font2.shape()) {
2930                         switch(shape_type) {
2931                         case 0:
2932                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2933                                         push_tag(os, "it", stack_num, stack);
2934                                         shape_type = 1;
2935                                 } else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2936                                         push_tag(os, "sl", stack_num, stack);
2937                                         shape_type = 2;
2938                                 }
2939                                 break;
2940                         case 1:
2941                                 pop_tag(os, "it", stack_num, stack);
2942                                 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2943                                         push_tag(os, "sl", stack_num, stack);
2944                                         shape_type = 2;
2945                                 } else {
2946                                         shape_type = 0;
2947                                 }
2948                                 break;
2949                         case 2:
2950                                 pop_tag(os, "sl", stack_num, stack);
2951                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2952                                         push_tag(os, "it", stack_num, stack);
2953                                         shape_type = 1;
2954                                 } else {
2955                                         shape_type = 0;
2956                                 }
2957                         }
2958                 }
2959                 // handle <em> tag
2960                 if (font1.emph() != font2.emph()) {
2961                         if (font2.emph() == LyXFont::ON) {
2962                                 push_tag(os, "em", stack_num, stack);
2963                                 is_em = true;
2964                         } else if (is_em) {
2965                                 pop_tag(os, "em", stack_num, stack);
2966                                 is_em = false;
2967                         }
2968                 }
2969
2970                 c = par->GetChar(i);
2971
2972                 if (c == LyXParagraph::META_INSET) {
2973                         inset = par->GetInset(i);
2974                         inset->Linuxdoc(this, os);
2975                 }
2976
2977                 if (font2.latex() == LyXFont::ON) {
2978                         // "TeX"-Mode on == > SGML-Mode on.
2979                         if (c != '\0')
2980                                 os << c; // see LaTeX-Generation...
2981                         ++char_line_count;
2982                 } else {
2983                         string sgml_string;
2984                         if (par->linuxDocConvertChar(c, sgml_string)
2985                             && !style.free_spacing) { // in freespacing
2986                                                      // mode, spaces are
2987                                                      // non-breaking characters
2988                                 // char is ' '
2989                                 if (desc_on == 1) {
2990                                         ++char_line_count;
2991                                         linux_doc_line_break(os, char_line_count, 6);
2992                                         os << "</tag>";
2993                                         desc_on = 2;
2994                                 } else  {
2995                                         linux_doc_line_break(os, char_line_count, 1);
2996                                         os << c;
2997                                 }
2998                         } else {
2999                                 os << sgml_string;
3000                                 char_line_count += sgml_string.length();
3001                         }
3002                 }
3003                 font1 = font2;
3004         }
3005
3006         // needed if there is an optional argument but no contents
3007         if (main_body > 0 && main_body == par->size()) {
3008                 font1 = style.font;
3009         }
3010
3011         // pop all defined Styles
3012         for (j = stack_num; j >= 0; --j) {
3013                 linux_doc_line_break(os, 
3014                                      char_line_count, 
3015                                      3 + strlen(stack[j]));
3016                 os << "</" << stack[j] << ">";
3017         }
3018
3019         // resets description flag correctly
3020         switch(desc_on){
3021         case 1:
3022                 // <tag> not closed...
3023                 linux_doc_line_break(os, char_line_count, 6);
3024                 os << "</tag>";
3025                 break;
3026         case 2:
3027                 // fprintf(file, "</p>");
3028                 break;
3029         }
3030 }
3031
3032
3033 // Print an error message.
3034 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
3035                            char const * message) 
3036 {
3037         // insert an error marker in text
3038         InsetError * new_inset = new InsetError(message);
3039         par->InsertInset(pos, new_inset);
3040 }
3041
3042 // This constant defines the maximum number of 
3043 // environment layouts that can be nesteded.
3044 // The same applies for command layouts.
3045 // These values should be more than enough.
3046 //           José Matos (1999/07/22)
3047
3048 enum { MAX_NEST_LEVEL = 25};
3049
3050 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3051 {
3052         LyXParagraph * par = paragraph;
3053
3054         niceFile = nice; // this will be used by Insetincludes.
3055
3056         string top_element= textclasslist.LatexnameOfClass(params.textclass);
3057         // Please use a real stack.
3058         string environment_stack[MAX_NEST_LEVEL];
3059         string environment_inner[MAX_NEST_LEVEL];
3060         // Please use a real stack.
3061         string command_stack[MAX_NEST_LEVEL];
3062         bool command_flag= false;
3063         int command_depth= 0, command_base= 0, cmd_depth= 0;
3064
3065         string item_name, command_name;
3066         string c_depth, c_params, tmps;
3067
3068         int depth = 0; // paragraph depth
3069         LyXTextClass const & tclass =
3070                 textclasslist.TextClass(params.textclass);
3071
3072         LaTeXFeatures features(params, tclass.numLayouts());
3073         validate(features);
3074
3075         //if(nice)
3076         tex_code_break_column = lyxrc.ascii_linelen;
3077         //else
3078         //tex_code_break_column = 0;
3079
3080         ofstream ofs(fname.c_str());
3081         if (!ofs) {
3082                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3083                 return;
3084         }
3085    
3086         texrow.reset();
3087
3088         if(!only_body) {
3089                 string sgml_includedfiles=features.getIncludedFiles();
3090
3091                 ofs << "<!doctype " << top_element
3092                     << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3093
3094                 if (params.preamble.empty() && sgml_includedfiles.empty())
3095                         ofs << ">\n\n";
3096                 else
3097                         ofs << "\n [ " << params.preamble 
3098                             << sgml_includedfiles << " \n]>\n\n";
3099
3100                 if(params.options.empty())
3101                         sgmlOpenTag(ofs, 0, top_element);
3102                 else {
3103                         string top = top_element;
3104                         top += " ";
3105                         top += params.options;
3106                         sgmlOpenTag(ofs, 0, top);
3107                 }
3108         }
3109
3110         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
3111             << "\n  See http://www.lyx.org/ for more information -->\n";
3112
3113         while (par) {
3114                 int desc_on = 0; // description mode
3115                 LyXLayout const & style =
3116                         textclasslist.Style(params.textclass,
3117                                             par->layout);
3118
3119                 // environment tag closing
3120                 for( ; depth > par->depth; --depth) {
3121                         if(environment_inner[depth] != "!-- --") {
3122                                 item_name= "listitem";
3123                                 sgmlCloseTag(ofs, command_depth + depth,
3124                                              item_name);
3125                                 if( environment_inner[depth] == "varlistentry")
3126                                         sgmlCloseTag(ofs, depth+command_depth,
3127                                                      environment_inner[depth]);
3128                         }
3129                         sgmlCloseTag(ofs, depth + command_depth,
3130                                      environment_stack[depth]);
3131                         environment_stack[depth].erase();
3132                         environment_inner[depth].erase();
3133                 }
3134
3135                 if(depth == par->depth
3136                    && environment_stack[depth] != style.latexname()
3137                    && !environment_stack[depth].empty()) {
3138                         if(environment_inner[depth] != "!-- --") {
3139                                 item_name= "listitem";
3140                                 sgmlCloseTag(ofs, command_depth+depth,
3141                                              item_name);
3142                                 if( environment_inner[depth] == "varlistentry")
3143                                         sgmlCloseTag(ofs,
3144                                                      depth + command_depth,
3145                                                      environment_inner[depth]);
3146                         }
3147                         
3148                         sgmlCloseTag(ofs, depth + command_depth,
3149                                      environment_stack[depth]);
3150                         
3151                         environment_stack[depth].erase();
3152                         environment_inner[depth].erase();
3153                 }
3154
3155                 // Write opening SGML tags.
3156                 switch(style.latextype) {
3157                 case LATEX_PARAGRAPH:
3158                         if(style.latexname() != "dummy")
3159                                sgmlOpenTag(ofs, depth+command_depth,
3160                                            style.latexname());
3161                         break;
3162
3163                 case LATEX_COMMAND:
3164                         if (depth!= 0)
3165                                 LinuxDocError(par, 0,
3166                                               _("Error : Wrong depth for "
3167                                                 "LatexType Command.\n"));
3168                         
3169                         command_name = style.latexname();
3170                         
3171                         tmps = style.latexparam();
3172                         c_params = split(tmps, c_depth,'|');
3173                         
3174                         cmd_depth= atoi(c_depth.c_str());
3175                         
3176                         if(command_flag) {
3177                                 if(cmd_depth<command_base) {
3178                                         for(int j = command_depth;
3179                                             j >= command_base; --j)
3180                                                 if(!command_stack[j].empty())
3181                                                         sgmlCloseTag(ofs, j, command_stack[j]);
3182                                         command_depth= command_base= cmd_depth;
3183                                 } else if(cmd_depth <= command_depth) {
3184                                         for(int j = command_depth;
3185                                             j >= cmd_depth; --j)
3186
3187                                                 if(!command_stack[j].empty())
3188                                                         sgmlCloseTag(ofs, j, command_stack[j]);
3189                                         command_depth= cmd_depth;
3190                                 } else
3191                                         command_depth= cmd_depth;
3192                         } else {
3193                                 command_depth = command_base = cmd_depth;
3194                                 command_flag = true;
3195                         }
3196                         command_stack[command_depth]= command_name;
3197
3198                         // treat label as a special case for
3199                         // more WYSIWYM handling.
3200                         if (par->GetChar(0) == LyXParagraph::META_INSET) {
3201                                 Inset * inset = par->GetInset(0);
3202                                 Inset::Code lyx_code = inset->LyxCode();
3203                                 if (lyx_code == Inset::LABEL_CODE){
3204                                         command_name += " id=\"";
3205                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3206                                         command_name += "\"";
3207                                         desc_on = 3;
3208                                 }
3209                         }
3210
3211                         sgmlOpenTag(ofs, depth + command_depth, command_name);
3212                         item_name = "title";
3213                         sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3214                         break;
3215
3216                 case LATEX_ENVIRONMENT:
3217                 case LATEX_ITEM_ENVIRONMENT:
3218                         if (depth < par->depth) {
3219                                 depth = par->depth;
3220                                 environment_stack[depth].erase();
3221                         }
3222
3223                         if (environment_stack[depth] != style.latexname()) {
3224                                 environment_stack[depth] = style.latexname();
3225                                 environment_inner[depth] = "!-- --";
3226                                 sgmlOpenTag(ofs, depth + command_depth,
3227                                             environment_stack[depth]);
3228                         } else {
3229                                 if(environment_inner[depth] != "!-- --") {
3230                                         item_name= "listitem";
3231                                         sgmlCloseTag(ofs,
3232                                                      command_depth + depth,
3233                                                      item_name);
3234                                         if (environment_inner[depth] == "varlistentry")
3235                                                 sgmlCloseTag(ofs,
3236                                                              depth + command_depth,
3237                                                              environment_inner[depth]);
3238                                 }
3239                         }
3240                         
3241                         if(style.latextype == LATEX_ENVIRONMENT) {
3242                                 if(!style.latexparam().empty())
3243                                         sgmlOpenTag(ofs, depth + command_depth,
3244                                                     style.latexparam());
3245                                 break;
3246                         }
3247
3248                         desc_on = (style.labeltype == LABEL_MANUAL);
3249
3250                         if(desc_on)
3251                                 environment_inner[depth]= "varlistentry";
3252                         else
3253                                 environment_inner[depth]= "listitem";
3254
3255                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3256                                     environment_inner[depth]);
3257
3258                         if(desc_on) {
3259                                 item_name= "term";
3260                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3261                                             item_name);
3262                         } else {
3263                                 item_name= "para";
3264                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3265                                             item_name);
3266                         }
3267                         break;
3268                 default:
3269                         sgmlOpenTag(ofs, depth + command_depth,
3270                                     style.latexname());
3271                         break;
3272                 }
3273
3274 #ifndef NEW_INSETS
3275                 do {
3276 #endif
3277                         string extra_par;
3278                         SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3279                                             depth + 1 + command_depth);
3280                         par = par->next;
3281 #ifndef NEW_INSETS
3282                         DocBookHandleFootnote(ofs, par,
3283                                               depth + 1 + command_depth);
3284                 }
3285                 while(par && par->IsDummy());
3286 #endif
3287                 string end_tag;
3288                 // write closing SGML tags
3289                 switch(style.latextype) {
3290                 case LATEX_COMMAND:
3291                         end_tag = "title";
3292                         sgmlCloseTag(ofs, depth + command_depth, end_tag);
3293                         break;
3294                 case LATEX_ENVIRONMENT:
3295                         if(!style.latexparam().empty())
3296                                 sgmlCloseTag(ofs, depth + command_depth,
3297                                              style.latexparam());
3298                         break;
3299                 case LATEX_ITEM_ENVIRONMENT:
3300                         if(desc_on == 1) break;
3301                         end_tag= "para";
3302                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3303                         break;
3304                 case LATEX_PARAGRAPH:
3305                         if(style.latexname() != "dummy")
3306                                 sgmlCloseTag(ofs, depth + command_depth,
3307                                              style.latexname());
3308                         break;
3309                 default:
3310                         sgmlCloseTag(ofs, depth + command_depth,
3311                                      style.latexname());
3312                         break;
3313                 }
3314         }
3315
3316         // Close open tags
3317         for(; depth >= 0; --depth) {
3318                 if(!environment_stack[depth].empty()) {
3319                         if(environment_inner[depth] != "!-- --") {
3320                                 item_name= "listitem";
3321                                 sgmlCloseTag(ofs, command_depth + depth,
3322                                              item_name);
3323                                if( environment_inner[depth] == "varlistentry")
3324                                        sgmlCloseTag(ofs, depth + command_depth,
3325                                                     environment_inner[depth]);
3326                         }
3327                         
3328                         sgmlCloseTag(ofs, depth + command_depth,
3329                                      environment_stack[depth]);
3330                 }
3331         }
3332         
3333         for(int j = command_depth; j >= command_base; --j)
3334                 if(!command_stack[j].empty())
3335                         sgmlCloseTag(ofs, j, command_stack[j]);
3336
3337         if (!only_body) {
3338                 ofs << "\n\n";
3339                 sgmlCloseTag(ofs, 0, top_element);
3340         }
3341
3342         ofs.close();
3343         // How to check for successful close
3344 }
3345
3346
3347 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3348                                  LyXParagraph * par, int & desc_on,
3349                                  int const depth) 
3350 {
3351 #ifndef NEW_TABULAR
3352         if (par->table) {
3353                 par->SimpleDocBookOneTablePar(this,
3354                                               os, extra, desc_on, depth);
3355                 return;
3356         }
3357 #endif
3358
3359         bool emph_flag = false;
3360
3361         LyXLayout const & style = textclasslist.Style(params.textclass,
3362                                                       par->GetLayout());
3363
3364         LyXParagraph::size_type main_body;
3365         if (style.labeltype != LABEL_MANUAL)
3366                 main_body = 0;
3367         else
3368                 main_body = par->BeginningOfMainBody();
3369
3370         // gets paragraph main font
3371         LyXFont font1 = main_body > 0 ? style.labelfont : style.font;
3372         
3373         int char_line_count = depth;
3374         if(!style.free_spacing)
3375                 for (int j = 0; j < depth; ++j)
3376                         os << ' ';
3377
3378         // parsing main loop
3379         for (LyXParagraph::size_type i = 0;
3380              i < par->size(); ++i) {
3381                 LyXFont font2 = par->getFont(params, i);
3382
3383                 // handle <emphasis> tag
3384                 if (font1.emph() != font2.emph() && i) {
3385                         if (font2.emph() == LyXFont::ON) {
3386                                 os << "<emphasis>";
3387                                 emph_flag = true;
3388                         }else {
3389                                 os << "</emphasis>";
3390                                 emph_flag = false;
3391                         }
3392                 }
3393       
3394                 char c = par->GetChar(i);
3395
3396                 if (c == LyXParagraph::META_INSET) {
3397                         Inset * inset = par->GetInset(i);
3398 #ifdef HAVE_SSTREAM
3399                         std::ostringstream ost;
3400                         inset->DocBook(this, ost);
3401                         string tmp_out = ost.str().c_str();
3402 #else
3403                         ostrstream ost;
3404                         inset->DocBook(this, ost);
3405                         ost << '\0';
3406                         char * ctmp = ost.str();
3407                         string tmp_out(ctmp);
3408                         delete [] ctmp;
3409 #endif
3410                         //
3411                         // This code needs some explanation:
3412                         // Two insets are treated specially
3413                         //   label if it is the first element in a command paragraph
3414                         //         desc_on == 3
3415                         //   graphics inside tables or figure floats can't go on
3416                         //   title (the equivalente in latex for this case is caption
3417                         //   and title should come first
3418                         //         desc_on == 4
3419                         //
3420                         if(desc_on!= 3 || i!= 0) {
3421                                 if(!tmp_out.empty() && tmp_out[0] == '@') {
3422                                         if(desc_on == 4)
3423                                                 extra += frontStrip(tmp_out, '@');
3424                                         else
3425                                                 os << frontStrip(tmp_out, '@');
3426                                 }
3427                                 else
3428                                         os << tmp_out;
3429                         }
3430                 } else if (font2.latex() == LyXFont::ON) {
3431                         // "TeX"-Mode on ==> SGML-Mode on.
3432                         if (c != '\0')
3433                                 os << c;
3434                         ++char_line_count;
3435                 } else {
3436                         string sgml_string;
3437                         if (par->linuxDocConvertChar(c, sgml_string)
3438                             && !style.free_spacing) { // in freespacing
3439                                                      // mode, spaces are
3440                                                      // non-breaking characters
3441                                 // char is ' '
3442                                 if (desc_on == 1) {
3443                                         ++char_line_count;
3444                                         os << "\n</term><listitem><para>";
3445                                         desc_on = 2;
3446                                 } else {
3447                                         os << c;
3448                                 }
3449                         } else {
3450                                 os << sgml_string;
3451                         }
3452                 }
3453                 font1 = font2;
3454         }
3455
3456         // needed if there is an optional argument but no contents
3457         if (main_body > 0 && main_body == par->size()) {
3458                 font1 = style.font;
3459         }
3460         if (emph_flag) {
3461                 os << "</emphasis>";
3462         }
3463         
3464         // resets description flag correctly
3465         switch(desc_on){
3466         case 1:
3467                 // <term> not closed...
3468                 os << "</term>";
3469                 break;
3470         }
3471         os << '\n';
3472 }
3473
3474
3475 int Buffer::runLaTeX()
3476 {
3477         if (!users->text) return 0;
3478
3479         ProhibitInput(users);
3480
3481         // get LaTeX-Filename
3482         string name = getLatexName();
3483
3484         string path = OnlyPath(filename);
3485
3486         string org_path = path;
3487         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3488                 path = tmppath;  
3489         }
3490
3491         Path p(path); // path to LaTeX file
3492         users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));   
3493
3494         // Remove all error insets
3495         bool a = users->removeAutoInsets();
3496
3497         // Always generate the LaTeX file
3498         makeLaTeXFile(name, org_path, false);
3499
3500         // do the LaTex run(s)
3501         TeXErrors terr;
3502         string latex_command = lyxrc.pdf_mode ?
3503                 lyxrc.pdflatex_command : lyxrc.latex_command;
3504         LaTeX latex(latex_command, name, filepath);
3505         int res = latex.run(terr,
3506                             users->owner()->getMiniBuffer()); // running latex
3507
3508         // check return value from latex.run().
3509         if ((res & LaTeX::NO_LOGFILE)) {
3510                 WriteAlert(_("LaTeX did not work!"),
3511                            _("Missing log file:"), name);
3512         } else if ((res & LaTeX::ERRORS)) {
3513                 users->owner()->getMiniBuffer()->Set(_("Done"));
3514                 // Insert all errors as errors boxes
3515                 users->insertErrors(terr);
3516                 
3517                 // Dvi should also be kept dirty if the latex run
3518                 // ends up with errors. However it should be possible
3519                 // to view a dirty dvi too.
3520         } else {
3521                 //no errors or any other things to think about so:
3522                 users->owner()->getMiniBuffer()->Set(_("Done"));
3523         }
3524
3525         // if we removed error insets before we ran LaTeX or if we inserted
3526         // error insets after we ran LaTeX this must be run:
3527         if (a || (res & LaTeX::ERRORS)){
3528                 users->redraw();
3529                 users->fitCursor();
3530                 //users->updateScrollbar();
3531         }
3532         AllowInput(users);
3533  
3534         return latex.getNumErrors();
3535 }
3536
3537
3538 int Buffer::runLiterate()
3539 {
3540         if (!users->text) return 0;
3541
3542         ProhibitInput(users);
3543
3544         // get LaTeX-Filename
3545         string name = getLatexName();
3546         // get Literate-Filename
3547         string lit_name = OnlyFilename(ChangeExtension (getLatexName(), 
3548                                            lyxrc.literate_extension));
3549
3550         string path = OnlyPath(filename);
3551
3552         string org_path = path;
3553         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3554                 path = tmppath;  
3555         }
3556
3557         Path p(path); // path to Literate file
3558         users->owner()->getMiniBuffer()->Set(_("Running Literate..."));   
3559
3560         // Remove all error insets
3561         bool removedErrorInsets = users->removeAutoInsets();
3562
3563         // generate the Literate file if necessary
3564         makeLaTeXFile(lit_name, org_path, false);
3565
3566         string latex_command = lyxrc.pdf_mode ?
3567                 lyxrc.pdflatex_command : lyxrc.latex_command;
3568         Literate literate(latex_command, name, filepath, 
3569                           lit_name,
3570                           lyxrc.literate_command, lyxrc.literate_error_filter,
3571                           lyxrc.build_command, lyxrc.build_error_filter);
3572         TeXErrors terr;
3573         int res = literate.weave(terr, users->owner()->getMiniBuffer());
3574
3575         // check return value from literate.weave().
3576         if ((res & Literate::NO_LOGFILE)) {
3577                 WriteAlert(_("Literate command did not work!"),
3578                            _("Missing log file:"), name);
3579         } else if ((res & Literate::ERRORS)) {
3580                 users->owner()->getMiniBuffer()->Set(_("Done"));
3581                 // Insert all errors as errors boxes
3582                 users->insertErrors(terr);
3583                 
3584                 // Dvi should also be kept dirty if the latex run
3585                 // ends up with errors. However it should be possible
3586                 // to view a dirty dvi too.
3587         } else {
3588                 //no errors or any other things to think about so:
3589                 users->owner()->getMiniBuffer()->Set(_("Done"));
3590         }
3591
3592         // if we removed error insets before we ran LaTeX or if we inserted
3593         // error insets after we ran LaTeX this must be run:
3594         if (removedErrorInsets || (res & Literate::ERRORS)){
3595                 users->redraw();
3596                 users->fitCursor();
3597                 //users->updateScrollbar();
3598         }
3599         AllowInput(users);
3600  
3601         return literate.getNumErrors();
3602 }
3603
3604
3605 int Buffer::buildProgram()
3606 {
3607         if (!users->text) return 0;
3608  
3609         ProhibitInput(users);
3610  
3611         // get LaTeX-Filename
3612         string name = getLatexName();
3613         // get Literate-Filename
3614         string lit_name = OnlyFilename(ChangeExtension(getLatexName(), 
3615                                                        lyxrc.literate_extension));
3616  
3617         string path = OnlyPath(filename);
3618  
3619         string org_path = path;
3620         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3621                 path = tmppath;  
3622         }
3623  
3624         Path p(path); // path to Literate file
3625         users->owner()->getMiniBuffer()->Set(_("Building Program..."));   
3626  
3627         // Remove all error insets
3628         bool removedErrorInsets = users->removeAutoInsets();
3629  
3630         // generate the LaTeX file if necessary
3631         if (!isNwClean() || removedErrorInsets) {
3632                 makeLaTeXFile(lit_name, org_path, false);
3633                 markNwDirty();
3634         }
3635
3636         string latex_command = lyxrc.pdf_mode ?
3637                 lyxrc.pdflatex_command : lyxrc.latex_command;
3638         Literate literate(latex_command, name, filepath, 
3639                           lit_name,
3640                           lyxrc.literate_command, lyxrc.literate_error_filter,
3641                           lyxrc.build_command, lyxrc.build_error_filter);
3642         TeXErrors terr;
3643         int res = literate.build(terr, users->owner()->getMiniBuffer());
3644  
3645         // check return value from literate.build().
3646         if ((res & Literate::NO_LOGFILE)) {
3647                 WriteAlert(_("Build did not work!"),
3648                            _("Missing log file:"), name);
3649         } else if ((res & Literate::ERRORS)) {
3650                 users->owner()->getMiniBuffer()->Set(_("Done"));
3651                 // Insert all errors as errors boxes
3652                 users->insertErrors(terr);
3653                 
3654                 // Literate files should also be kept dirty if the literate 
3655                 // command run ends up with errors.
3656         } else {
3657                 //no errors or any other things to think about so:
3658                 users->owner()->getMiniBuffer()->Set(_("Done"));
3659                 markNwClean();
3660         }
3661  
3662         // if we removed error insets before we ran Literate/Build or
3663         // if we inserted error insets after we ran Literate/Build this
3664         // must be run:
3665         if (removedErrorInsets || (res & Literate::ERRORS)){
3666                 users->redraw();
3667                 users->fitCursor();
3668                 //users->updateScrollbar();
3669         }
3670         AllowInput(users);
3671
3672         return literate.getNumErrors();
3673 }
3674
3675
3676 // This should be enabled when the Chktex class is implemented. (Asger)
3677 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3678 // Other flags: -wall -v0 -x
3679 int Buffer::runChktex()
3680 {
3681         if (!users->text) return 0;
3682
3683         ProhibitInput(users);
3684
3685         // get LaTeX-Filename
3686         string name = getLatexName();
3687         string path = OnlyPath(filename);
3688
3689         string org_path = path;
3690         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3691                 path = tmppath;  
3692         }
3693
3694         Path p(path); // path to LaTeX file
3695         users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3696
3697         // Remove all error insets
3698         bool removedErrorInsets = users->removeAutoInsets();
3699
3700         // Generate the LaTeX file if neccessary
3701         makeLaTeXFile(name, org_path, false);
3702
3703         TeXErrors terr;
3704         Chktex chktex(lyxrc.chktex_command, name, filepath);
3705         int res = chktex.run(terr); // run chktex
3706
3707         if (res == -1) {
3708                 WriteAlert(_("chktex did not work!"),
3709                            _("Could not run with file:"), name);
3710         } else if (res > 0) {
3711                 // Insert all errors as errors boxes
3712                 users->insertErrors(terr);
3713         }
3714
3715         // if we removed error insets before we ran chktex or if we inserted
3716         // error insets after we ran chktex, this must be run:
3717         if (removedErrorInsets || res){
3718                 users->redraw();
3719                 users->fitCursor();
3720                 //users->updateScrollbar();
3721         }
3722         AllowInput(users);
3723
3724         return res;
3725 }
3726
3727
3728 void Buffer::validate(LaTeXFeatures & features) const
3729 {
3730         LyXParagraph * par = paragraph;
3731         LyXTextClass const & tclass = 
3732                 textclasslist.TextClass(params.textclass);
3733     
3734         // AMS Style is at document level
3735     
3736         features.amsstyle = (params.use_amsmath ||
3737                              tclass.provides(LyXTextClass::amsmath));
3738     
3739         while (par) {
3740                 // We don't use "lyxerr.debug" because of speed. (Asger)
3741                 if (lyxerr.debugging(Debug::LATEX))
3742                         lyxerr << "Paragraph: " <<  par << endl;
3743
3744                 // Now just follow the list of paragraphs and run
3745                 // validate on each of them.
3746                 par->validate(features);
3747
3748                 // and then the next paragraph
3749                 par = par->next;
3750         }
3751
3752         // the bullet shapes are buffer level not paragraph level
3753         // so they are tested here
3754         for (int i = 0; i < 4; ++i) {
3755                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3756                         int font = params.user_defined_bullets[i].getFont();
3757                         if (font == 0) {
3758                                 int c = params
3759                                         .user_defined_bullets[i]
3760                                         .getCharacter();
3761                                 if (c == 16
3762                                    || c == 17
3763                                    || c == 25
3764                                    || c == 26
3765                                    || c == 31) {
3766                                         features.latexsym = true;
3767                                 }
3768                         }
3769                         if (font == 1) {
3770                                 features.amssymb = true;
3771                         }
3772                         else if ((font >= 2 && font <= 5)) {
3773                                 features.pifont = true;
3774                         }
3775                 }
3776         }
3777         
3778         if (lyxerr.debugging(Debug::LATEX)) {
3779                 features.showStruct();
3780         }
3781 }
3782
3783
3784 void Buffer::setPaperStuff()
3785 {
3786         params.papersize = BufferParams::PAPER_DEFAULT;
3787         char c1 = params.paperpackage;
3788         if (c1 == BufferParams::PACKAGE_NONE) {
3789                 char c2 = params.papersize2;
3790                 if (c2 == BufferParams::VM_PAPER_USLETTER)
3791                         params.papersize = BufferParams::PAPER_USLETTER;
3792                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3793                         params.papersize = BufferParams::PAPER_LEGALPAPER;
3794                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3795                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3796                 else if (c2 == BufferParams::VM_PAPER_A3)
3797                         params.papersize = BufferParams::PAPER_A3PAPER;
3798                 else if (c2 == BufferParams::VM_PAPER_A4)
3799                         params.papersize = BufferParams::PAPER_A4PAPER;
3800                 else if (c2 == BufferParams::VM_PAPER_A5)
3801                         params.papersize = BufferParams::PAPER_A5PAPER;
3802                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3803                          (c2 == BufferParams::VM_PAPER_B5))
3804                         params.papersize = BufferParams::PAPER_B5PAPER;
3805         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3806                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3807                 params.papersize = BufferParams::PAPER_A4PAPER;
3808 }
3809
3810
3811 // This function should be in Buffer because it's a buffer's property (ale)
3812 string Buffer::getIncludeonlyList(char delim)
3813 {
3814         string lst;
3815         for (inset_iterator it = inset_iterator_begin();
3816             it != inset_iterator_end(); ++it) {
3817                 if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3818                         InsetInclude * insetinc = 
3819                                 static_cast<InsetInclude *>(*it);
3820                         if (insetinc->isInclude() 
3821                             && insetinc->isNoLoad()) {
3822                                 if (!lst.empty())
3823                                         lst += delim;
3824                                 lst += OnlyFilename(ChangeExtension(insetinc->getContents(), string()));
3825                         }
3826                 }
3827         }
3828         lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3829         return lst;
3830 }
3831
3832
3833 vector<string> Buffer::getLabelList()
3834 {
3835         /// if this is a child document and the parent is already loaded
3836         /// Use the parent's list instead  [ale990407]
3837         if (!params.parentname.empty()
3838             && bufferlist.exists(params.parentname)) {
3839                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3840                 if (tmp)
3841                         return tmp->getLabelList();
3842         }
3843
3844         vector<string> label_list;
3845         for (inset_iterator it = inset_iterator_begin();
3846              it != inset_iterator_end(); ++it) {
3847                 vector<string> l = (*it)->getLabelList();
3848                 label_list.insert(label_list.end(), l.begin(), l.end());
3849         }
3850         return label_list;
3851 }
3852
3853
3854 vector<vector<Buffer::TocItem> > Buffer::getTocList()
3855 {
3856         vector<vector<TocItem> > l(4);
3857         LyXParagraph * par = paragraph;
3858         while (par) {
3859 #ifndef NEW_INSETS
3860                 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
3861                         if (textclasslist.Style(params.textclass, 
3862                                                 par->GetLayout()).labeltype
3863                             == LABEL_SENSITIVE) {
3864                                 TocItem tmp;
3865                                 tmp.par = par;
3866                                 tmp.depth = 0;
3867                                 tmp.str =  par->String(this, false);
3868                                 switch (par->footnotekind) {
3869                                 case LyXParagraph::FIG:
3870                                 case LyXParagraph::WIDE_FIG:
3871                                         l[TOC_LOF].push_back(tmp);
3872                                         break;
3873                                 case LyXParagraph::TAB:
3874                                 case LyXParagraph::WIDE_TAB:
3875                                         l[TOC_LOT].push_back(tmp);
3876                                         break;
3877                                 case LyXParagraph::ALGORITHM:
3878                                         l[TOC_LOA].push_back(tmp);
3879                                         break;
3880                                 case LyXParagraph::FOOTNOTE:
3881                                 case LyXParagraph::MARGIN:
3882                                         break;
3883                                 }
3884                         }
3885                 } else if (!par->IsDummy()) {
3886 #endif
3887                         char labeltype = textclasslist.Style(params.textclass, 
3888                                                              par->GetLayout()).labeltype;
3889       
3890                         if (labeltype >= LABEL_COUNTER_CHAPTER
3891                             && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3892                                 // insert this into the table of contents
3893                                 TocItem tmp;
3894                                 tmp.par = par;
3895                                 tmp.depth = max(0,
3896                                                 labeltype - 
3897                                                 textclasslist.TextClass(params.textclass).maxcounter());
3898                                 tmp.str =  par->String(this, true);
3899                                 l[TOC_TOC].push_back(tmp);
3900                         }
3901 #ifndef NEW_INSETS
3902                 }
3903 #endif
3904                 par = par->next;
3905         }
3906         return l;
3907 }
3908
3909 // This is also a buffer property (ale)
3910 vector<pair<string,string> > Buffer::getBibkeyList()
3911 {
3912         /// if this is a child document and the parent is already loaded
3913         /// Use the parent's list instead  [ale990412]
3914         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3915                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3916                 if (tmp)
3917                         return tmp->getBibkeyList();
3918         }
3919
3920         vector<pair<string, string> > keys;
3921         LyXParagraph * par = paragraph;
3922         while (par) {
3923                 if (par->bibkey)
3924                         keys.push_back(pair<string, string>(par->bibkey->getContents(),
3925                                                            par->String(this, false)));
3926                 par = par->next;
3927         }
3928
3929         // Might be either using bibtex or a child has bibliography
3930         if (keys.empty()) {
3931                 for (inset_iterator it = inset_iterator_begin();
3932                         it != inset_iterator_end(); ++it) {
3933                         // Search for Bibtex or Include inset
3934                         if ((*it)->LyxCode() == Inset::BIBTEX_CODE) {
3935                                 vector<pair<string,string> > tmp =
3936                                         static_cast<InsetBibtex*>(*it)->getKeys();
3937                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3938                         } else if ((*it)->LyxCode() == Inset::INCLUDE_CODE) {
3939                                 vector<pair<string,string> > tmp =
3940                                         static_cast<InsetInclude*>(*it)->getKeys();
3941                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3942                         }
3943                 }
3944         }
3945  
3946         return keys;
3947 }
3948
3949
3950 bool Buffer::isDepClean(string const & name) const
3951 {
3952         DEPCLEAN * item = dep_clean;
3953         while (item && item->master != name)
3954                 item = item->next;
3955         if (!item) return true;
3956         return item->clean;
3957 }
3958
3959
3960 void Buffer::markDepClean(string const & name)
3961 {
3962         if (!dep_clean) {
3963                 dep_clean = new DEPCLEAN;
3964                 dep_clean->clean = true;
3965                 dep_clean->master = name;
3966                 dep_clean->next = 0;
3967         } else {
3968                 DEPCLEAN* item = dep_clean;
3969                 while (item && item->master != name)
3970                         item = item->next;
3971                 if (item) {
3972                         item->clean = true;
3973                 } else {
3974                         item = new DEPCLEAN;
3975                         item->clean = true;
3976                         item->master = name;
3977                         item->next = 0;
3978                 }
3979         }
3980 }
3981
3982
3983 bool Buffer::Dispatch(string const & command)
3984 {
3985         // Split command string into command and argument
3986         string cmd, line = frontStrip(command);
3987         string arg = strip(frontStrip(split(line, cmd, ' ')));
3988
3989         return Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
3990 }
3991
3992
3993 bool Buffer::Dispatch(int action, string const & argument)
3994 {
3995         bool dispatched = true;
3996         switch (action) {
3997                 case LFUN_EXPORT: 
3998                         MenuExport(this, argument);
3999                         break;
4000
4001                 default:
4002                         dispatched = false;
4003         }
4004         return dispatched;
4005 }
4006
4007
4008 void Buffer::resize()
4009 {
4010         /// resize the BufferViews!
4011         if (users)
4012                 users->resize();
4013 }
4014
4015
4016 void Buffer::resizeInsets(BufferView * bv)
4017 {
4018         /// then remove all LyXText in text-insets
4019         LyXParagraph * par = paragraph;
4020         for(;par;par = par->next) {
4021             par->resizeInsetsLyXText(bv);
4022         }
4023 }
4024
4025 void Buffer::ChangeLanguage(Language const * from, Language const * to)
4026 {
4027
4028         LyXParagraph * par = paragraph;
4029         while (par) {
4030                 par->ChangeLanguage(params, from, to);
4031                 par = par->next;
4032         }
4033 }
4034
4035
4036 bool Buffer::isMultiLingual()
4037 {
4038
4039         LyXParagraph * par = paragraph;
4040         while (par) {
4041                 if (par->isMultiLingual(params))
4042                         return true;
4043                 par = par->next;
4044         }
4045         return false;
4046 }
4047
4048
4049 Buffer::inset_iterator::inset_iterator(LyXParagraph * paragraph,
4050                                        LyXParagraph::size_type pos)
4051         : par(paragraph) {
4052         it = par->InsetIterator(pos);
4053         if (it == par->inset_iterator_end()) {
4054                 par = par->next;
4055                 SetParagraph();
4056         }
4057 }
4058
4059
4060 void Buffer::inset_iterator::SetParagraph() {
4061         while (par) {
4062                 it = par->inset_iterator_begin();
4063                 if (it != par->inset_iterator_end())
4064                         return;
4065                 par = par->next;
4066         }
4067         //it = 0;
4068         // We maintain an invariant that whenever par = 0 then it = 0
4069 }