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