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