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