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