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