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