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