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