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