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