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