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