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