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