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