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