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