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