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