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