]> git.lyx.org Git - lyx.git/blob - src/buffer.C
Various updates for insets mostly regarding fixes for text-insets.
[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                 inset = new InsetSpecialChar;
923                 inset->Read(lex);
924                 par->InsertChar(pos, LyXParagraph::META_INSET); 
925                 par->InsertInset(pos, inset);
926                 par->SetFont(pos, font);
927                 ++pos;
928         } else if (token == "\\Figure") {
929                 inset = new InsetFig(100, 100, this);
930                 inset->Read(lex);
931                 par->InsertChar(pos, LyXParagraph::META_INSET); 
932                 par->InsertInset(pos, inset);
933                 par->SetFont(pos, font);
934                 ++pos;
935         } else if (token == "\\newline") { // soon obsolete
936 #if 1
937                 par->InsertChar(pos, LyXParagraph::META_NEWLINE);
938                 par->SetFont(pos, font);
939 #else
940                 inset = new InsetSpecialChar(InsetSpecialChar::NEWLINE);
941                 par->InsertChar(pos, LyXParagraph::META_INSET);
942                 par->InsertInset(pos, inset);
943                 par->SetFont(pos, font);
944 #endif
945                 ++pos;
946         } else if (token == "\\LyXTable") {
947                 par->table = new LyXTable(lex);
948         } else if (token == "\\hfill") {
949                 par->InsertChar(pos, LyXParagraph::META_HFILL);
950                 par->SetFont(pos, font);
951                 ++pos;
952         } else if (token == "\\protected_separator") { // obsolete
953 #if 1
954                 inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
955                 par->InsertChar(pos, LyXParagraph::META_INSET);
956                 par->InsertInset(pos, inset);
957                 par->SetFont(pos, font);
958 #else
959                 par->InsertChar(pos, LyXParagraph::META_PROTECTED_SEPARATOR);
960                 par->SetFont(pos, font);
961 #endif
962                 ++pos;
963         } else if (token == "\\bibitem") {  // ale970302
964                 if (!par->bibkey)
965                         par->bibkey = new InsetBibKey;
966                 par->bibkey->Read(lex);                 
967         }else if (token == "\\backslash") {
968                 par->InsertChar(pos, '\\');
969                 par->SetFont(pos, font);
970                 ++pos;
971         }else if (token == "\\the_end") {
972                 the_end_read = true;
973         } else {
974                 // This should be insurance for the future: (Asger)
975                 lex.printError("Unknown token `$$Token'. "
976                                "Inserting as text.");
977                 int n = token.length();
978                 for (int i = 0; i < n; ++i) {
979                         par->InsertChar(pos, token[i]);
980                         par->SetFont(pos, font);
981                         ++pos;
982                 }
983         }
984         return the_end_read;
985 }
986
987 bool Buffer::readFile(LyXLex & lex, LyXParagraph * par)
988 {
989         string token;
990
991         if (lex.IsOK()) {
992                 lex.next();
993                 token = lex.GetString();
994                 if (token == "\\lyxformat") { // the first token _must_ be...
995                         lex.next();
996                         format = lex.GetFloat();
997                         if (format > 1) {
998                                 if (LYX_FORMAT - format > 0.05) {
999                                         printf(_("Warning: need lyxformat %.2f but found %.2f\n"),
1000                                                LYX_FORMAT, format);
1001                                 }
1002                                 if (format - LYX_FORMAT > 0.05) {
1003                                         printf(_("ERROR: need lyxformat %.2f but found %.2f\n"),
1004                                                LYX_FORMAT, format);
1005                                 }
1006                                 bool the_end = readLyXformat2(lex, par);
1007                                 // Formats >= 2.13 support "\the_end" marker
1008                                 if (format < 2.13)
1009                                         the_end = true;
1010
1011                                 setPaperStuff();
1012
1013                                 if (!the_end)
1014                                         WriteAlert(_("Warning!"),
1015                                                    _("Reading of document is not complete"),
1016                                                    _("Maybe the document is truncated"));
1017                                 // We simulate a safe reading anyways to allow
1018                                 // users to take the chance... (Asger)
1019                                 return true;
1020                         } // format < 1
1021                         else {
1022                                 WriteAlert(_("ERROR!"),
1023                                            _("Old LyX file format found. "
1024                                              "Use LyX 0.10.x to read this!"));
1025                                 return false;
1026                         }
1027
1028                 } else { // "\\lyxformat" not found
1029                         WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1030                 }
1031         } else
1032                 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1033         return false;
1034 }
1035                     
1036
1037
1038 // Should probably be moved to somewhere else: BufferView? LyXView?
1039 bool Buffer::save(bool makeBackup) const
1040 {
1041         // We don't need autosaves in the immediate future. (Asger)
1042         resetAutosaveTimers();
1043
1044         // make a backup
1045         if (makeBackup) {
1046                 string s = fileName() + '~';
1047                 // Rename is the wrong way of making a backup,
1048                 // this is the correct way.
1049                 /* truss cp fil fil2:
1050                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1051                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1052                    open("LyXVC.lyx", O_RDONLY)                     = 3
1053                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1054                    fstat(4, 0xEFFFF508)                            = 0
1055                    fstat(3, 0xEFFFF508)                            = 0
1056                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1057                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1058                    read(3, 0xEFFFD4A0, 8192)                       = 0
1059                    close(4)                                        = 0
1060                    close(3)                                        = 0
1061                    chmod("LyXVC3.lyx", 0100644)                    = 0
1062                    lseek(0, 0, SEEK_CUR)                           = 46440
1063                    _exit(0)
1064                 */
1065
1066                 // Should proabaly have some more error checking here.
1067                 // Should be cleaned up in 0.13, at least a bit.
1068                 // Doing it this way, also makes the inodes stay the same.
1069                 // This is still not a very good solution, in particular we
1070                 // might loose the owner of the backup.
1071                 FileInfo finfo(fileName());
1072                 if (finfo.exist()) {
1073                         mode_t fmode = finfo.getMode();
1074                         struct utimbuf * times = new struct utimbuf;
1075
1076                         times->actime = finfo.getAccessTime();
1077                         times->modtime = finfo.getModificationTime();
1078                         ifstream ifs(fileName().c_str());
1079                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1080                         if (ifs && ofs) {
1081                                 ofs << ifs.rdbuf();
1082                                 ifs.close();
1083                                 ofs.close();
1084                                 ::chmod(s.c_str(), fmode);
1085                                 
1086                                 if (::utime(s.c_str(), times)) {
1087                                         lyxerr << "utime error." << endl;
1088                                 }
1089                         } else {
1090                                 lyxerr << "LyX was not able to make "
1091                                         "backupcopy. Beware." << endl;
1092                         }
1093                         delete times;
1094                 }
1095         }
1096         
1097         if (writeFile(fileName(), false)) {
1098                 markLyxClean();
1099
1100                 // now delete the autosavefile
1101                 string a = OnlyPath(fileName());
1102                 a += '#';
1103                 a += OnlyFilename(fileName());
1104                 a += '#';
1105                 FileInfo fileinfo(a);
1106                 if (fileinfo.exist()) {
1107                         if (::remove(a.c_str()) != 0) {
1108                                 WriteFSAlert(_("Could not delete "
1109                                                "auto-save file!"), a);
1110                         }
1111                 }
1112         } else {
1113                 // Saving failed, so backup is not backup
1114                 if (makeBackup) {
1115                         string s = fileName() + '~';
1116                         ::rename(s.c_str(), fileName().c_str());
1117                 }
1118                 return false;
1119         }
1120         return true;
1121 }
1122
1123
1124 // Returns false if unsuccesful
1125 bool Buffer::writeFile(string const & fname, bool flag) const
1126 {
1127         // if flag is false writeFile will not create any GUI
1128         // warnings, only cerr.
1129         // Needed for autosave in background or panic save (Matthias 120496)
1130
1131         if (read_only && (fname == filename)) {
1132                 // Here we should come with a question if we should
1133                 // perform the write anyway.
1134                 if (flag)
1135                         lyxerr << _("Error! Document is read-only: ")
1136                                << fname << endl;
1137                 else
1138                         WriteAlert(_("Error! Document is read-only: "),
1139                                    fname);
1140                 return false;
1141         }
1142
1143         FileInfo finfo(fname);
1144         if (finfo.exist() && !finfo.writable()) {
1145                 // Here we should come with a question if we should
1146                 // try to do the save anyway. (i.e. do a chmod first)
1147                 if (flag)
1148                         lyxerr << _("Error! Cannot write file: ")
1149                                << fname << endl;
1150                 else
1151                         WriteFSAlert(_("Error! Cannot write file: "),
1152                                      fname);
1153                 return false;
1154         }
1155
1156         ofstream ofs(fname.c_str());
1157         if (!ofs) {
1158                 if (flag)
1159                         lyxerr << _("Error! Cannot open file: ")
1160                                << fname << endl;
1161                 else
1162                         WriteFSAlert(_("Error! Cannot open file: "),
1163                                      fname);
1164                 return false;
1165         }
1166         // The top of the file should not be written by params.
1167
1168         // write out a comment in the top of the file
1169         ofs << '#' << LYX_DOCVERSION 
1170             << " created this file. For more info see http://www.lyx.org/\n";
1171         ofs.setf(ios::showpoint|ios::fixed);
1172         ofs.precision(2);
1173         ofs << "\\lyxformat " << setw(4) <<  LYX_FORMAT << "\n";
1174
1175         // now write out the buffer paramters.
1176         params.writeFile(ofs);
1177
1178         char footnoteflag = 0;
1179         char depth = 0;
1180
1181         // this will write out all the paragraphs
1182         // using recursive descent.
1183         paragraph->writeFile(ofs, params, footnoteflag, depth);
1184
1185         // Write marker that shows file is complete
1186         ofs << "\n\\the_end" << endl;
1187         ofs.close();
1188         // how to check if close went ok?
1189         return true;
1190 }
1191
1192
1193 void Buffer::writeFileAscii(string const & fname, int linelen) 
1194 {
1195         LyXFont font1, font2;
1196         Inset * inset;
1197         char c, footnoteflag = 0, depth = 0;
1198         string tmp;
1199         LyXParagraph::size_type i;
1200         int j, h, ltype = 0, ltype_depth = 0,
1201                 * clen = 0, actcell = 0, actpos = 0, cell = 0, cells = 0,
1202                 currlinelen = 0;
1203         long fpos = 0;
1204         bool ref_printed = false;
1205
1206         ofstream ofs(fname.c_str());
1207         if (!ofs) {
1208                 WriteFSAlert(_("Error: Cannot write file:"), fname);
1209                 return;
1210         }
1211
1212         string fname1 = TmpFileName();
1213         LyXParagraph * par = paragraph;
1214         while (par) {
1215                 int noparbreak = 0;
1216                 int islatex = 0;
1217                 if (par->footnoteflag != LyXParagraph::NO_FOOTNOTE ||
1218                     !par->previous ||
1219                     par->previous->footnoteflag == LyXParagraph::NO_FOOTNOTE){
1220          
1221                         /* begins a footnote environment ? */ 
1222                         if (footnoteflag != par->footnoteflag) {
1223                                 footnoteflag = par->footnoteflag;
1224                                 if (footnoteflag) {
1225                                         j = strlen(string_footnotekinds[par->footnotekind])+4;
1226                                         if (currlinelen + j > linelen)
1227                                                 ofs << "\n";
1228                                         ofs << "(["
1229                                             << string_footnotekinds[par->footnotekind] << "] ";
1230                                         currlinelen += j;
1231                                 }
1232                         }
1233          
1234                         /* begins or ends a deeper area ?*/ 
1235                         if (depth != par->depth) {
1236                                 if (par->depth > depth) {
1237                                         while (par->depth > depth) {
1238                                                 ++depth;
1239                                         }
1240                                 }
1241                                 else {
1242                                         while (par->depth < depth) {
1243                                                 --depth;
1244                                         }
1245                                 }
1246                         }
1247          
1248                         /* First write the layout */
1249                         tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1250                         if (tmp == "Itemize") {
1251                                 ltype = 1;
1252                                 ltype_depth = depth+1;
1253                         } else if (tmp == "Enumerate") {
1254                                 ltype = 2;
1255                                 ltype_depth = depth+1;
1256                         } else if (strstr(tmp.c_str(), "ection")) {
1257                                 ltype = 3;
1258                                 ltype_depth = depth+1;
1259                         } else if (strstr(tmp.c_str(), "aragraph")) {
1260                                 ltype = 4;
1261                                 ltype_depth = depth+1;
1262                         } else if (tmp == "Description") {
1263                                 ltype = 5;
1264                                 ltype_depth = depth+1;
1265                         } else if (tmp == "Abstract") {
1266                                 ltype = 6;
1267                                 ltype_depth = 0;
1268                         } else if (tmp == "Bibliography") {
1269                                 ltype = 7;
1270                                 ltype_depth = 0;
1271                         } else {
1272                                 ltype = 0;
1273                                 ltype_depth = 0;
1274                         }
1275          
1276                         /* maybe some vertical spaces */ 
1277
1278                         /* the labelwidthstring used in lists */ 
1279          
1280                         /* some lines? */ 
1281          
1282                         /* some pagebreaks? */ 
1283          
1284                         /* noindent ? */ 
1285          
1286                         /* what about the alignment */ 
1287                 }
1288                 else {
1289                         /* dummy layout, that means a footnote ended */ 
1290                         footnoteflag = LyXParagraph::NO_FOOTNOTE;
1291                         ofs << ") ";
1292                         noparbreak = 1;
1293                 }
1294       
1295                 /* It might be a table */ 
1296                 if (par->table){
1297 #if 0
1298                         if (!lyxrc->ascii_roff_command.empty() &&
1299                             lyxrc->ascii_roff_command != "none") {
1300                                 RoffAsciiTable(ofs, par);
1301                                 par = par->next;
1302                                 continue;
1303                         }
1304 #endif
1305                         cell = 1;
1306                         actcell = 0;
1307                         cells = par->table->columns;
1308                         clen = new int [cells];
1309                         memset(clen, 0, sizeof(int) * cells);
1310                         for (i = 0, j = 0, h = 1; i < par->size(); ++i, ++h) {
1311                                 c = par->GetChar(i);
1312                                 if (c == LyXParagraph::META_INSET) {
1313                                         if ((inset = par->GetInset(i))) {
1314 #if 1
1315 #ifdef HAVE_SSTREAM
1316                                                 ostringstream ost;
1317                                                 inset->Latex(ost, -1);
1318                                                 h += ost.str().length();
1319 #else
1320                                                 ostrstream ost;
1321                                                 inset->Latex(ost, -1);
1322                                                 ost << '\0';
1323                                                 char * tmp = ost.str();
1324                                                 string tstr(tmp);
1325                                                 h += tstr.length();
1326                                                 delete [] tmp;
1327 #endif
1328 #else
1329                                                 ofstream fs(fname1.c_str());
1330                                                 if (!fs) {
1331                                                         WriteFSAlert(_("Error: Cannot open temporary file:"), fname1);
1332                                                         return;
1333                                                 }
1334                                                 inset->Latex(fs, -1);
1335                                                 h += fs.tellp() - 1;
1336                                                 ::remove(fname1.c_str());
1337 #endif
1338                                         }
1339                                 } else if (c == LyXParagraph::META_NEWLINE) {
1340                                         if (clen[j] < h)
1341                                                 clen[j] = h;
1342                                         h = 0;
1343                                         j = (++j) % par->table->NumberOfCellsInRow(actcell);
1344                                         ++actcell;
1345                                 }
1346                         }
1347                         if (clen[j] < h)
1348                                 clen[j] = h;
1349                 }
1350       
1351                 font1 = LyXFont(LyXFont::ALL_INHERIT);
1352                 actcell = 0;
1353                 for (i = 0, actpos = 1; i < par->size(); ++i, ++actpos) {
1354                         if (!i && !footnoteflag && !noparbreak){
1355                                 ofs << "\n\n";
1356                                 for(j = 0; j < depth; ++j)
1357                                         ofs << "  ";
1358                                 currlinelen = depth * 2;
1359                                 switch(ltype) {
1360                                 case 0: /* Standard */
1361                                 case 4: /* (Sub)Paragraph */
1362                                 case 5: /* Description */
1363                                         break;
1364                                 case 6: /* Abstract */
1365                                         ofs << "Abstract\n\n";
1366                                         break;
1367                                 case 7: /* Bibliography */
1368                                         if (!ref_printed) {
1369                                                 ofs << "References\n\n";
1370                                                 ref_printed = true;
1371                                         }
1372                                         break;
1373                                 default:
1374                                         ofs << par->labelstring << " ";
1375                                         break;
1376                                 }
1377                                 if (ltype_depth > depth) {
1378                                         for(j = ltype_depth - 1; j > depth; --j)
1379                                                 ofs << "  ";
1380                                         currlinelen += (ltype_depth-depth)*2;
1381                                 }
1382                                 if (par->table) {
1383                                         for(j = 0; j < cells; ++j) {
1384                                                 ofs << '+';
1385                                                 for(h = 0; h < (clen[j] + 1);
1386                                                     ++h)
1387                                                         ofs << '-';
1388                                         }
1389                                         ofs << "+\n";
1390                                         for(j = 0; j < depth; ++j)
1391                                                 ofs << "  ";
1392                                         currlinelen = depth * 2;
1393                                         if (ltype_depth > depth) {
1394                                                 for(j = ltype_depth;
1395                                                     j > depth; --j)
1396                                                         ofs << "  ";
1397                                                 currlinelen += (ltype_depth-depth)*2;
1398                                         }
1399                                         ofs << "| ";
1400                                 }
1401                         }
1402                         font2 = par->GetFontSettings(i);
1403                         if (font1.latex() != font2.latex()) {
1404                                 if (font2.latex() == LyXFont::OFF)
1405                                         islatex = 0;
1406                                 else
1407                                         islatex = 1;
1408                         }
1409                         else {
1410                                 islatex = 0;
1411                         }
1412                         c = par->GetChar(i);
1413                         if (islatex)
1414                                 continue;
1415                         switch (c) {
1416                         case LyXParagraph::META_INSET:
1417                                 if ((inset = par->GetInset(i))) {
1418                                         fpos = ofs.tellp();
1419                                         inset->Latex(ofs, -1);
1420                                         currlinelen += (ofs.tellp() - fpos);
1421                                         actpos += (ofs.tellp() - fpos) - 1;
1422                                 }
1423                                 break;
1424                         case LyXParagraph::META_NEWLINE:
1425                                 if (par->table) {
1426                                         if (par->table->NumberOfCellsInRow(actcell) <= cell) {
1427                                                 for(j = actpos; j < clen[cell - 1]; ++j)
1428                                                         ofs << ' ';
1429                                                 ofs << " |\n";
1430                                                 for(j = 0; j < depth; ++j)
1431                                                         ofs << "  ";
1432                                                 currlinelen = depth*2;
1433                                                 if (ltype_depth > depth) {
1434                                                         for(j = ltype_depth; j > depth; --j)
1435                                                                 ofs << "  ";
1436                                                         currlinelen += (ltype_depth-depth) * 2;
1437                                                 }
1438                                                 for(j = 0; j < cells; ++j) {
1439                                                         ofs << '+';
1440                                                         for(h = 0; h < (clen[j] + 1); ++h)
1441                                                                 ofs << '-';
1442                                                 }
1443                                                 ofs << "+\n";
1444                                                 for(j = 0; j < depth; ++j)
1445                                                         ofs << "  ";
1446                                                 currlinelen = depth * 2;
1447                                                 if (ltype_depth > depth) {
1448                                                         for(j = ltype_depth;
1449                                                             j > depth; --j)
1450                                                                 ofs << "  ";
1451                                                         currlinelen += (ltype_depth-depth)*2;
1452                                                 }
1453                                                 ofs << "| ";
1454                                                 cell = 1;
1455                                         } else {
1456                                                 for(j = actpos;
1457                                                     j < clen[cell - 1]; ++j)
1458                                                         ofs << ' ';
1459                                                 ofs << " | ";
1460                                                 ++cell;
1461                                         }
1462                                         ++actcell;
1463                                         currlinelen = actpos = 0;
1464                                 } else {
1465                                         ofs << "\n";
1466                                         for(j = 0; j < depth; ++j)
1467                                                 ofs << "  ";
1468                                         currlinelen = depth * 2;
1469                                         if (ltype_depth > depth) {
1470                                                 for(j = ltype_depth;
1471                                                     j > depth; --j)
1472                                                         ofs << "  ";
1473                                                 currlinelen += (ltype_depth - depth) * 2;
1474                                         }
1475                                 }
1476                                 break;
1477                         case LyXParagraph::META_HFILL: 
1478                                 ofs << "\t";
1479                                 break;
1480 #if 0
1481                         case LyXParagraph::META_PROTECTED_SEPARATOR:
1482                                 ofs << " ";
1483                                 break;
1484 #endif
1485                         case '\\':
1486                                 ofs << "\\";
1487                                 break;
1488                         default:
1489                                 if (currlinelen > linelen - 10
1490                                     && c == ' ' && i + 2 < par->size()) {
1491                                         ofs << "\n";
1492                                         for(j = 0; j < depth; ++j)
1493                                                 ofs << "  ";
1494                                         currlinelen = depth * 2;
1495                                         if (ltype_depth > depth) {
1496                                                 for(j = ltype_depth;
1497                                                     j > depth; --j)
1498                                                         ofs << "  ";
1499                                                 currlinelen += (ltype_depth-depth)*2;
1500                                         }
1501                                 } else if (c != '\0')
1502                                         ofs << c;
1503                                 else if (c == '\0')
1504                                         lyxerr.debug() << "writeAsciiFile: NULL char in structure." << endl;
1505                                 ++currlinelen;
1506                                 break;
1507                         }
1508                 }
1509                 if (par->table) {
1510                         for(j = actpos; j < clen[cell - 1]; ++j)
1511                                 ofs << ' ';
1512                         ofs << " |\n";
1513                         for(j = 0; j < depth; ++j)
1514                                 ofs << "  ";
1515                         currlinelen = depth * 2;
1516                         if (ltype_depth > depth) {
1517                                 for(j = ltype_depth; j > depth; --j)
1518                                         ofs << "  ";
1519                                 currlinelen += (ltype_depth - depth) * 2;
1520                         }
1521                         for(j = 0; j < cells; ++j) {
1522                                 ofs << '+';
1523                                 for(h = 0; h < (clen[j] + 1); ++h)
1524                                         ofs << '-';
1525                         }
1526                         ofs << "+\n";
1527                         delete [] clen;    
1528                 }      
1529                 par = par->next;
1530         }
1531    
1532         ofs << "\n";
1533 }
1534
1535
1536 #ifdef USE_OSTREAM_ONLY
1537 void Buffer::makeLaTeXFile(string const & fname, 
1538                            string const & original_path,
1539                            bool nice, bool only_body)
1540 {
1541         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1542         
1543         niceFile = nice; // this will be used by Insetincludes.
1544
1545         tex_code_break_column = lyxrc->ascii_linelen;
1546
1547         LyXTextClass const & tclass =
1548                 textclasslist.TextClass(params.textclass);
1549
1550         ofstream ofs(fname.c_str());
1551         if (!ofs) {
1552                 WriteFSAlert(_("Error: Cannot open file: "), fname);
1553                 return;
1554         }
1555         
1556         // validate the buffer.
1557         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1558         LaTeXFeatures features(tclass.numLayouts());
1559         validate(features);
1560         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1561         
1562         texrow.reset();
1563         // The starting paragraph of the coming rows is the 
1564         // first paragraph of the document. (Asger)
1565         texrow.start(paragraph, 0);
1566
1567         if (!only_body && nice) {
1568                 ofs << "%% " LYX_DOCVERSION " created this file.  "
1569                         "For more info, see http://www.lyx.org/.\n"
1570                         "%% Do not edit unless you really know what "
1571                         "you are doing.\n";
1572                 texrow.newline();
1573                 texrow.newline();
1574         }
1575         lyxerr.debug() << "lyx header finished" << endl;
1576         // There are a few differences between nice LaTeX and usual files:
1577         // usual is \batchmode and has a 
1578         // special input@path to allow the including of figures
1579         // with either \input or \includegraphics (what figinsets do).
1580         // batchmode is not set if there is a tex_code_break_column.
1581         // In this case somebody is interested in the generated LaTeX,
1582         // so this is OK. input@path is set when the actual parameter
1583         // original_path is set. This is done for usual tex-file, but not
1584         // for nice-latex-file. (Matthias 250696)
1585         if (!only_body) {
1586                 if (!nice){
1587                         // code for usual, NOT nice-latex-file
1588                         ofs << "\\batchmode\n"; // changed
1589                         // from \nonstopmode
1590                         texrow.newline();
1591                 }
1592                 if (!original_path.empty()) {
1593                         ofs << "\\makeatletter\n"
1594                             << "\\def\\input@path{{"
1595                             << original_path << "/}}\n"
1596                             << "\\makeatother\n";
1597                         texrow.newline();
1598                         texrow.newline();
1599                         texrow.newline();
1600                 }
1601                 
1602                 ofs << "\\documentclass";
1603                 
1604                 string options; // the document class options.
1605                 
1606                 if (tokenPos(tclass.opt_fontsize(), '|', params.fontsize) >= 0) {
1607                         // only write if existing in list (and not default)
1608                         options += params.fontsize;
1609                         options += "pt,";
1610                 }
1611                 
1612                 
1613                 if (!params.use_geometry &&
1614                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1615                         switch (params.papersize) {
1616                         case BufferParams::PAPER_A4PAPER:
1617                                 options += "a4paper,";
1618                                 break;
1619                         case BufferParams::PAPER_USLETTER:
1620                                 options += "letterpaper,";
1621                                 break;
1622                         case BufferParams::PAPER_A5PAPER:
1623                                 options += "a5paper,";
1624                                 break;
1625                         case BufferParams::PAPER_B5PAPER:
1626                                 options += "b5paper,";
1627                                 break;
1628                         case BufferParams::PAPER_EXECUTIVEPAPER:
1629                                 options += "executivepaper,";
1630                                 break;
1631                         case BufferParams::PAPER_LEGALPAPER:
1632                                 options += "legalpaper,";
1633                                 break;
1634                         }
1635                 }
1636
1637                 // if needed
1638                 if (params.sides != tclass.sides()) {
1639                         switch (params.sides) {
1640                         case LyXTextClass::OneSide:
1641                                 options += "oneside,";
1642                                 break;
1643                         case LyXTextClass::TwoSides:
1644                                 options += "twoside,";
1645                                 break;
1646                         }
1647
1648                 }
1649
1650                 // if needed
1651                 if (params.columns != tclass.columns()) {
1652                         if (params.columns == 2)
1653                                 options += "twocolumn,";
1654                         else
1655                                 options += "onecolumn,";
1656                 }
1657
1658                 if (!params.use_geometry 
1659                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1660                         options += "landscape,";
1661                 
1662                 // language should be a parameter to \documentclass             
1663                 if (params.language != "default") {
1664                         if (params.language == "hebrew")
1665                                 options += "english,";
1666                         else if (lyxrc->rtl_support)
1667                                 options += "hebrew,";
1668                         options += params.language + ',';
1669                 } else if (lyxrc->rtl_support)
1670                         options += "hebrew,english,";
1671
1672                 // the user-defined options
1673                 if (!params.options.empty()) {
1674                         options += params.options + ',';
1675                 }
1676                 
1677                 if (!options.empty()){
1678                         options = strip(options, ',');
1679                         ofs << '[' << options << ']';
1680                 }
1681                 
1682                 ofs << '{'
1683                     << textclasslist.LatexnameOfClass(params.textclass)
1684                     << "}\n";
1685                 texrow.newline();
1686                 // end of \documentclass defs
1687                 
1688                 // font selection must be done before loading fontenc.sty
1689                 if (params.fonts != "default") {
1690                         ofs << "\\usepackage{" << params.fonts << "}\n";
1691                         texrow.newline();
1692                 }
1693                 // this one is not per buffer
1694                 if (lyxrc->fontenc != "default") {
1695                         ofs << "\\usepackage[" << lyxrc->fontenc
1696                             << "]{fontenc}\n";
1697                         texrow.newline();
1698                 }
1699                 if (params.inputenc != "default") {
1700                         ofs << "\\usepackage[" << params.inputenc
1701                             << "]{inputenc}\n";
1702                         texrow.newline();
1703                 }
1704                 
1705                 /* at the very beginning the text parameters */
1706                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1707                         switch (params.paperpackage) {
1708                         case BufferParams::PACKAGE_A4:
1709                                 ofs << "\\usepackage{a4}\n";
1710                                 texrow.newline();
1711                                 break;
1712                         case BufferParams::PACKAGE_A4WIDE:
1713                                 ofs << "\\usepackage{a4wide}\n";
1714                                 texrow.newline();
1715                                 break;
1716                         case BufferParams::PACKAGE_WIDEMARGINSA4:
1717                                 ofs << "\\usepackage[widemargins]{a4}\n";
1718                                 texrow.newline();
1719                                 break;
1720                         }
1721                 }
1722                 if (params.use_geometry) {
1723                         ofs << "\\usepackage{geometry}\n";
1724                         texrow.newline();
1725                         ofs << "\\geometry{verbose";
1726                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1727                                 ofs << ",landscape";
1728                         switch (params.papersize2) {
1729                         case BufferParams::VM_PAPER_CUSTOM:
1730                                 if (!params.paperwidth.empty())
1731                                         ofs << ",paperwidth="
1732                                             << params.paperwidth;
1733                                 if (!params.paperheight.empty())
1734                                         ofs << ",paperheight="
1735                                             << params.paperheight;
1736                                 break;
1737                         case BufferParams::VM_PAPER_USLETTER:
1738                                 ofs << ",letterpaper";
1739                                 break;
1740                         case BufferParams::VM_PAPER_USLEGAL:
1741                                 ofs << ",legalpaper";
1742                                 break;
1743                         case BufferParams::VM_PAPER_USEXECUTIVE:
1744                                 ofs << ",executivepaper";
1745                                 break;
1746                         case BufferParams::VM_PAPER_A3:
1747                                 ofs << ",a3paper";
1748                                 break;
1749                         case BufferParams::VM_PAPER_A4:
1750                                 ofs << ",a4paper";
1751                                 break;
1752                         case BufferParams::VM_PAPER_A5:
1753                                 ofs << ",a5paper";
1754                                 break;
1755                         case BufferParams::VM_PAPER_B3:
1756                                 ofs << ",b3paper";
1757                                 break;
1758                         case BufferParams::VM_PAPER_B4:
1759                                 ofs << ",b4paper";
1760                                 break;
1761                         case BufferParams::VM_PAPER_B5:
1762                                 ofs << ",b5paper";
1763                                 break;
1764                         default:
1765                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1766                                 switch (lyxrc->default_papersize) {
1767                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1768                                 case BufferParams::PAPER_USLETTER:
1769                                         ofs << ",letterpaper";
1770                                         break;
1771                                 case BufferParams::PAPER_LEGALPAPER:
1772                                         ofs << ",legalpaper";
1773                                         break;
1774                                 case BufferParams::PAPER_EXECUTIVEPAPER:
1775                                         ofs << ",executivepaper";
1776                                         break;
1777                                 case BufferParams::PAPER_A3PAPER:
1778                                         ofs << ",a3paper";
1779                                         break;
1780                                 case BufferParams::PAPER_A4PAPER:
1781                                         ofs << ",a4paper";
1782                                         break;
1783                                 case BufferParams::PAPER_A5PAPER:
1784                                         ofs << ",a5paper";
1785                                         break;
1786                                 case BufferParams::PAPER_B5PAPER:
1787                                         ofs << ",b5paper";
1788                                         break;
1789                                 }
1790                         }
1791                         if (!params.topmargin.empty())
1792                                 ofs << ",tmargin=" << params.topmargin;
1793                         if (!params.bottommargin.empty())
1794                                 ofs << ",bmargin=" << params.bottommargin;
1795                         if (!params.leftmargin.empty())
1796                                 ofs << ",lmargin=" << params.leftmargin;
1797                         if (!params.rightmargin.empty())
1798                                 ofs << ",rmargin=" << params.rightmargin;
1799                         if (!params.headheight.empty())
1800                                 ofs << ",headheight=" << params.headheight;
1801                         if (!params.headsep.empty())
1802                                 ofs << ",headsep=" << params.headsep;
1803                         if (!params.footskip.empty())
1804                                 ofs << ",footskip=" << params.footskip;
1805                         ofs << "}\n";
1806                         texrow.newline();
1807                 }
1808                 if (params.use_amsmath
1809                     && !prefixIs(textclasslist.LatexnameOfClass(params.textclass), "ams")) {
1810                         ofs << "\\usepackage{amsmath}\n";
1811                         texrow.newline();
1812                 }
1813
1814                 if (tokenPos(tclass.opt_pagestyle(), '|', params.pagestyle) >= 0) {
1815                         if (params.pagestyle == "fancy") {
1816                                 ofs << "\\usepackage{fancyhdr}\n";
1817                                 texrow.newline();
1818                         }
1819                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
1820                         texrow.newline();
1821                 }
1822
1823                 // We try to load babel late, in case it interferes
1824                 // with other packages.
1825                 if (params.language != "default" || lyxrc->rtl_support ) {
1826                         ofs << "\\usepackage{babel}\n";
1827                         texrow.newline();
1828                 }
1829
1830                 if (params.secnumdepth != tclass.secnumdepth()) {
1831                         ofs << "\\setcounter{secnumdepth}{"
1832                             << params.secnumdepth
1833                             << "}\n";
1834                         texrow.newline();
1835                 }
1836                 if (params.tocdepth != tclass.tocdepth()) {
1837                         ofs << "\\setcounter{tocdepth}{"
1838                             << params.tocdepth
1839                             << "}\n";
1840                         texrow.newline();
1841                 }
1842                 
1843                 if (params.paragraph_separation) {
1844                         switch (params.defskip.kind()) {
1845                         case VSpace::SMALLSKIP: 
1846                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
1847                                 break;
1848                         case VSpace::MEDSKIP:
1849                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1850                                 break;
1851                         case VSpace::BIGSKIP:
1852                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
1853                                 break;
1854                         case VSpace::LENGTH:
1855                                 ofs << "\\setlength\\parskip{"
1856                                     << params.defskip.length().asLatexString()
1857                                     << "}\n";
1858                                 break;
1859                         default: // should never happen // Then delete it.
1860                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
1861                                 break;
1862                         }
1863                         texrow.newline();
1864                         
1865                         ofs << "\\setlength\\parindent{0pt}\n";
1866                         texrow.newline();
1867                 }
1868
1869                 // Now insert the LyX specific LaTeX commands...
1870                 string preamble, tmppreamble;
1871
1872                 // The optional packages;
1873                 preamble = features.getPackages(params);
1874
1875                 // this might be useful...
1876                 preamble += "\n\\makeatletter\n\n";
1877
1878                 // Some macros LyX will need
1879                 tmppreamble = features.getMacros(params);
1880
1881                 if (!tmppreamble.empty()) {
1882                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1883                                 "LyX specific LaTeX commands.\n"
1884                                 + tmppreamble + '\n';
1885                 }
1886
1887                 // the text class specific preamble 
1888                 tmppreamble = features.getTClassPreamble(params);
1889                 if (!tmppreamble.empty()) {
1890                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1891                                 "Textclass specific LaTeX commands.\n"
1892                                 + tmppreamble + '\n';
1893                 }
1894
1895                 /* the user-defined preamble */
1896                 if (!params.preamble.empty()) {
1897                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1898                                 "User specified LaTeX commands.\n"
1899                                 + params.preamble + '\n';
1900                 }
1901
1902                 preamble += "\\makeatother\n\n";
1903
1904                 // Itemize bullet settings need to be last in case the user
1905                 // defines their own bullets that use a package included
1906                 // in the user-defined preamble -- ARRae
1907                 // Actually it has to be done much later than that
1908                 // since some packages like frenchb make modifications
1909                 // at \begin{document} time -- JMarc 
1910                 string bullets_def;
1911                 for (int i = 0; i < 4; ++i) {
1912                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1913                                 if (bullets_def.empty())
1914                                         bullets_def="\\AtBeginDocument{\n";
1915                                 bullets_def += "  \\renewcommand{\\labelitemi";
1916                                 switch (i) {
1917                                 // `i' is one less than the item to modify
1918                                 case 0:
1919                                         break;
1920                                 case 1:
1921                                         bullets_def += 'i';
1922                                         break;
1923                                 case 2:
1924                                         bullets_def += "ii";
1925                                         break;
1926                                 case 3:
1927                                         bullets_def += 'v';
1928                                         break;
1929                                 }
1930                                 bullets_def += "}{" + 
1931                                   params.user_defined_bullets[i].getText() 
1932                                   + "}\n";
1933                         }
1934                 }
1935
1936                 if (!bullets_def.empty())
1937                   preamble += bullets_def + "}\n\n";
1938
1939                 for (int j = countChar(preamble, '\n'); j-- ;) {
1940                         texrow.newline();
1941                 }
1942
1943                 ofs << preamble;
1944
1945                 // make the body.
1946                 ofs << "\\begin{document}\n\n";
1947                 texrow.newline();
1948                 texrow.newline();
1949         } // only_body
1950         lyxerr.debug() << "preamble finished, now the body." << endl;
1951         
1952         bool was_title = false;
1953         bool already_title = false;
1954 #ifdef HAVE_SSTREAM
1955         ostringstream ftnote;
1956 #else
1957         char * tmpholder = 0;
1958 #endif
1959         TexRow ft_texrow;
1960         int ftcount = 0;
1961
1962         LyXParagraph * par = paragraph;
1963
1964         // if only_body
1965         while (par) {
1966 #ifndef HAVE_SSTREAM
1967                 ostrstream ftnote;
1968                 if (tmpholder) {
1969                         ftnote << tmpholder;
1970                         delete [] tmpholder;
1971                         tmpholder = 0;
1972                 }
1973 #endif
1974                 if (par->IsDummy())
1975                         lyxerr[Debug::LATEX] << "Error in MakeLateXFile."
1976                                              << endl;
1977                 LyXLayout const & layout =
1978                         textclasslist.Style(params.textclass,
1979                                             par->layout);
1980             
1981                 if (layout.intitle) {
1982                         if (already_title) {
1983                                 lyxerr <<"Error in MakeLatexFile: You"
1984                                         " should not mix title layouts"
1985                                         " with normal ones." << endl;
1986                         } else
1987                                 was_title = true;
1988                 } else if (was_title && !already_title) {
1989                         ofs << "\\maketitle\n";
1990                         texrow.newline();
1991                         already_title = true;
1992                         was_title = false;                  
1993                 }
1994                 // We are at depth 0 so we can just use
1995                 // ordinary \footnote{} generation
1996                 // flag this with ftcount
1997                 ftcount = -1;
1998                 if (layout.isEnvironment()
1999                     || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2000                         par = par->TeXEnvironment(ofs, texrow,
2001                                                   ftnote, ft_texrow, ftcount);
2002                 } else {
2003                         par = par->TeXOnePar(ofs, texrow,
2004                                              ftnote, ft_texrow, ftcount);
2005                 }
2006
2007                 // Write out what we've generated...
2008                 if (ftcount >= 1) {
2009                         if (ftcount > 1) {
2010                                 ofs << "\\addtocounter{footnote}{-"
2011                                     << ftcount - 1
2012                                     << '}';
2013                         }
2014                         ofs << ftnote.str();
2015                         texrow += ft_texrow;
2016 #ifdef HAVE_SSTREAM
2017                         // The extra .c_str() is needed when we use
2018                         // lyxstring instead of the STL string class. 
2019                         ftnote.str(string().c_str());
2020 #else
2021                         delete [] ftnote.str();
2022 #endif
2023                         ft_texrow.reset();
2024                         ftcount = 0;
2025                 }
2026 #ifndef HAVE_SSTREAM
2027                 else {
2028                         // I hate strstreams
2029                         tmpholder = ftnote.str();
2030                 }
2031 #endif
2032         }
2033 #ifndef HAVE_SSTREAM
2034         delete [] tmpholder;
2035 #endif
2036         // It might be that we only have a title in this document
2037         if (was_title && !already_title) {
2038                 ofs << "\\maketitle\n";
2039                 texrow.newline();
2040         }
2041
2042         if (!only_body) {
2043                 ofs << "\\end{document}\n";
2044                 texrow.newline();
2045         
2046                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2047         } else {
2048                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2049                                      << endl;
2050         }
2051
2052         // Just to be sure. (Asger)
2053         texrow.newline();
2054
2055         // tex_code_break_column's value is used to decide
2056         // if we are in batchmode or not (within mathed_write()
2057         // in math_write.C) so we must set it to a non-zero
2058         // value when we leave otherwise we save incorrect .lyx files.
2059         tex_code_break_column = lyxrc->ascii_linelen;
2060
2061         ofs.close();
2062         if (ofs.fail()) {
2063                 lyxerr << "File was not closed properly." << endl;
2064         }
2065         
2066         lyxerr.debug() << "Finished making latex file." << endl;
2067 }
2068 #else
2069 void Buffer::makeLaTeXFile(string const & fname, 
2070                            string const & original_path,
2071                            bool nice, bool only_body)
2072 {
2073         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2074         
2075         niceFile = nice; // this will be used by Insetincludes.
2076
2077         tex_code_break_column = lyxrc->ascii_linelen;
2078
2079         LyXTextClass const & tclass =
2080                 textclasslist.TextClass(params.textclass);
2081
2082         ofstream ofs(fname.c_str());
2083         if (!ofs) {
2084                 WriteFSAlert(_("Error: Cannot open file: "), fname);
2085                 return;
2086         }
2087         
2088         // validate the buffer.
2089         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
2090         LaTeXFeatures features(tclass.numLayouts());
2091         validate(features);
2092         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
2093         
2094         texrow.reset();
2095         // The starting paragraph of the coming rows is the 
2096         // first paragraph of the document. (Asger)
2097         texrow.start(paragraph, 0);
2098
2099         string LFile;
2100         
2101         if (!only_body && nice) {
2102                 LFile += "%% " LYX_DOCVERSION " created this file.  "
2103                          "For more info, see http://www.lyx.org/.\n";
2104                 LFile += "%% Do not edit unless you really know what you are doing.\n";
2105                 texrow.newline();
2106                 texrow.newline();
2107         }
2108         lyxerr.debug() << "lyx header finished" << endl;
2109         // There are a few differences between nice LaTeX and usual files:
2110         // usual is \batchmode and has a 
2111         // special input@path to allow the including of figures
2112         // with either \input or \includegraphics (what figinsets do).
2113         // batchmode is not set if there is a tex_code_break_column.
2114         // In this case somebody is interested in the generated LaTeX,
2115         // so this is OK. input@path is set when the actual parameter
2116         // original_path is set. This is done for usual tex-file, but not
2117         // for nice-latex-file. (Matthias 250696)
2118         if (!only_body) {
2119                 if (!nice){
2120                         // code for usual, NOT nice-latex-file
2121                         LFile += "\\batchmode\n"; // changed
2122                         // from \nonstopmode
2123                         texrow.newline();
2124                 }
2125                 if (!original_path.empty()) {
2126                         LFile += "\\makeatletter\n";
2127                         texrow.newline();
2128                         LFile += "\\def\\input@path{{" + original_path
2129                                  + "/}}\n";
2130                         texrow.newline();
2131                         LFile += "\\makeatother\n";
2132                         texrow.newline();
2133                 }
2134                 
2135                 LFile += "\\documentclass";
2136                 
2137                 string options; // the document class options.
2138                 
2139                 if (tokenPos(tclass.opt_fontsize(), '|', params.fontsize) >= 0) {
2140                         // only write if existing in list (and not default)
2141                         options += params.fontsize;
2142                         options += "pt,";
2143                 }
2144                 
2145                 
2146                 if (!params.use_geometry &&
2147                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2148                         switch (params.papersize) {
2149                         case BufferParams::PAPER_A4PAPER:
2150                                 options += "a4paper,";
2151                                 break;
2152                         case BufferParams::PAPER_USLETTER:
2153                                 options += "letterpaper,";
2154                                 break;
2155                         case BufferParams::PAPER_A5PAPER:
2156                                 options += "a5paper,";
2157                                 break;
2158                         case BufferParams::PAPER_B5PAPER:
2159                                 options += "b5paper,";
2160                                 break;
2161                         case BufferParams::PAPER_EXECUTIVEPAPER:
2162                                 options += "executivepaper,";
2163                                 break;
2164                         case BufferParams::PAPER_LEGALPAPER:
2165                                 options += "legalpaper,";
2166                                 break;
2167                         }
2168                 }
2169
2170                 // if needed
2171                 if (params.sides != tclass.sides()) {
2172                         switch (params.sides) {
2173                         case LyXTextClass::OneSide:
2174                                 options += "oneside,";
2175                                 break;
2176                         case LyXTextClass::TwoSides:
2177                                 options += "twoside,";
2178                                 break;
2179                         }
2180
2181                 }
2182
2183                 // if needed
2184                 if (params.columns != tclass.columns()) {
2185                         if (params.columns == 2)
2186                                 options += "twocolumn,";
2187                         else
2188                                 options += "onecolumn,";
2189                 }
2190
2191                 if (!params.use_geometry 
2192                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2193                         options += "landscape,";
2194                 
2195                 // language should be a parameter to \documentclass             
2196                 if (params.language != "default") {
2197                         if (params.language == "hebrew")
2198                                 options += "english,";
2199                         else if (lyxrc->rtl_support)
2200                                 options += "hebrew,";
2201                         options += params.language + ',';
2202                 } else if (lyxrc->rtl_support)
2203                         options += "hebrew,english,";
2204
2205                 // the user-defined options
2206                 if (!params.options.empty()) {
2207                         options += params.options + ',';
2208                 }
2209                 
2210                 if (!options.empty()){
2211                         options = strip(options, ',');
2212                         LFile += '[';
2213                         LFile += options;
2214                         LFile += ']';
2215                 }
2216                 
2217                 LFile += '{';
2218                 LFile += textclasslist.LatexnameOfClass(params.textclass);
2219                 LFile += "}\n";
2220                 texrow.newline();
2221                 // end of \documentclass defs
2222                 
2223                 // font selection must be done before loading fontenc.sty
2224                 if (params.fonts != "default") {
2225                         LFile += "\\usepackage{" + params.fonts + "}\n";
2226                         texrow.newline();
2227                 }
2228                 // this one is not per buffer
2229                 if (lyxrc->fontenc != "default") {
2230                         LFile += "\\usepackage[" + lyxrc->fontenc
2231                                  + "]{fontenc}\n";
2232                         texrow.newline();
2233                 }
2234                 if (params.inputenc != "default") {
2235                         LFile += "\\usepackage[" + params.inputenc
2236                                  + "]{inputenc}\n";
2237                         texrow.newline();
2238                 }
2239                 
2240                 /* at the very beginning the text parameters */
2241                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2242                         switch (params.paperpackage) {
2243                         case BufferParams::PACKAGE_A4:
2244                                 LFile += "\\usepackage{a4}\n";
2245                                 texrow.newline();
2246                                 break;
2247                         case BufferParams::PACKAGE_A4WIDE:
2248                                 LFile += "\\usepackage{a4wide}\n";
2249                                 texrow.newline();
2250                                 break;
2251                         case BufferParams::PACKAGE_WIDEMARGINSA4:
2252                                 LFile += "\\usepackage[widemargins]{a4}\n";
2253                                 texrow.newline();
2254                                 break;
2255                         }
2256                 }
2257                 if (params.use_geometry) {
2258                         LFile += "\\usepackage{geometry}\n";
2259                         texrow.newline();
2260                         LFile += "\\geometry{verbose";
2261                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2262                                 LFile += ",landscape";
2263                         switch (params.papersize2) {
2264                         case BufferParams::VM_PAPER_CUSTOM:
2265                                 if (!params.paperwidth.empty())
2266                                         LFile += ",paperwidth="
2267                                                  + params.paperwidth;
2268                                 if (!params.paperheight.empty())
2269                                         LFile += ",paperheight="
2270                                                  + params.paperheight;
2271                                 break;
2272                         case BufferParams::VM_PAPER_USLETTER:
2273                                 LFile += ",letterpaper";
2274                                 break;
2275                         case BufferParams::VM_PAPER_USLEGAL:
2276                                 LFile += ",legalpaper";
2277                                 break;
2278                         case BufferParams::VM_PAPER_USEXECUTIVE:
2279                                 LFile += ",executivepaper";
2280                                 break;
2281                         case BufferParams::VM_PAPER_A3:
2282                                 LFile += ",a3paper";
2283                                 break;
2284                         case BufferParams::VM_PAPER_A4:
2285                                 LFile += ",a4paper";
2286                                 break;
2287                         case BufferParams::VM_PAPER_A5:
2288                                 LFile += ",a5paper";
2289                                 break;
2290                         case BufferParams::VM_PAPER_B3:
2291                                 LFile += ",b3paper";
2292                                 break;
2293                         case BufferParams::VM_PAPER_B4:
2294                                 LFile += ",b4paper";
2295                                 break;
2296                         case BufferParams::VM_PAPER_B5:
2297                                 LFile += ",b5paper";
2298                                 break;
2299                         default:
2300                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2301                                 switch (lyxrc->default_papersize) {
2302                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2303                                 case BufferParams::PAPER_USLETTER:
2304                                         LFile += ",letterpaper";
2305                                         break;
2306                                 case BufferParams::PAPER_LEGALPAPER:
2307                                         LFile += ",legalpaper";
2308                                         break;
2309                                 case BufferParams::PAPER_EXECUTIVEPAPER:
2310                                         LFile += ",executivepaper";
2311                                         break;
2312                                 case BufferParams::PAPER_A3PAPER:
2313                                         LFile += ",a3paper";
2314                                         break;
2315                                 case BufferParams::PAPER_A4PAPER:
2316                                         LFile += ",a4paper";
2317                                         break;
2318                                 case BufferParams::PAPER_A5PAPER:
2319                                         LFile += ",a5paper";
2320                                         break;
2321                                 case BufferParams::PAPER_B5PAPER:
2322                                         LFile += ",b5paper";
2323                                         break;
2324                                 }
2325                         }
2326                         if (!params.topmargin.empty())
2327                                 LFile += ",tmargin=" + params.topmargin;
2328                         if (!params.bottommargin.empty())
2329                                 LFile += ",bmargin=" + params.bottommargin;
2330                         if (!params.leftmargin.empty())
2331                                 LFile += ",lmargin=" + params.leftmargin;
2332                         if (!params.rightmargin.empty())
2333                                 LFile += ",rmargin=" + params.rightmargin;
2334                         if (!params.headheight.empty())
2335                                 LFile += ",headheight=" + params.headheight;
2336                         if (!params.headsep.empty())
2337                                 LFile += ",headsep=" + params.headsep;
2338                         if (!params.footskip.empty())
2339                                 LFile += ",footskip=" + params.footskip;
2340                         LFile += "}\n";
2341                         texrow.newline();
2342                 }
2343                 if (params.use_amsmath
2344                     && !prefixIs(textclasslist.LatexnameOfClass(params.textclass), "ams")) {
2345                         LFile += "\\usepackage{amsmath}\n";
2346                 }
2347
2348                 if (tokenPos(tclass.opt_pagestyle(), '|', params.pagestyle) >= 0) {
2349                         if (params.pagestyle == "fancy") {
2350                                 LFile += "\\usepackage{fancyhdr}\n";
2351                                 texrow.newline();
2352                         }
2353                         LFile += "\\pagestyle{" + params.pagestyle + "}\n";
2354                         texrow.newline();
2355                 }
2356
2357                 // We try to load babel late, in case it interferes
2358                 // with other packages.
2359                 if (params.language != "default" || lyxrc->rtl_support ) {
2360                         LFile += "\\usepackage{babel}\n";
2361                         texrow.newline();
2362                 }
2363
2364                 if (params.secnumdepth != tclass.secnumdepth()) {
2365                         LFile += "\\setcounter{secnumdepth}{";
2366                         LFile += tostr(params.secnumdepth);
2367                         LFile += "}\n";
2368                         texrow.newline();
2369                 }
2370                 if (params.tocdepth != tclass.tocdepth()) {
2371                         LFile += "\\setcounter{tocdepth}{";
2372                         LFile += tostr(params.tocdepth);
2373                         LFile += "}\n";
2374                         texrow.newline();
2375                 }
2376                 
2377                 if (params.paragraph_separation) {
2378                         switch (params.defskip.kind()) {
2379                         case VSpace::SMALLSKIP: 
2380                                 LFile += "\\setlength\\parskip{\\smallskipamount}\n";
2381                                 break;
2382                         case VSpace::MEDSKIP:
2383                                 LFile += "\\setlength\\parskip{\\medskipamount}\n";
2384                                 break;
2385                         case VSpace::BIGSKIP:
2386                                 LFile += "\\setlength\\parskip{\\bigskipamount}\n";
2387                                 break;
2388                         case VSpace::LENGTH:
2389                                 LFile += "\\setlength\\parskip{"
2390                                          + params.defskip.length().asLatexString()
2391                                          + "}\n";
2392                                 break;
2393                         default: // should never happen // Then delete it.
2394                                 LFile += "\\setlength\\parskip{\\medskipamount}\n";
2395                                 break;
2396                         }
2397                         texrow.newline();
2398                         
2399                         LFile += "\\setlength\\parindent{0pt}\n";
2400                         texrow.newline();
2401                 }
2402
2403                 // Write out what we've generated so far...and reset LFile
2404                 ofs << LFile;
2405                 LFile.clear(); 
2406
2407                 // Now insert the LyX specific LaTeX commands...
2408                 string preamble, tmppreamble;
2409
2410                 // The optional packages;
2411                 preamble = features.getPackages(params);
2412
2413                 // this might be useful...
2414                 preamble += "\n\\makeatletter\n\n";
2415
2416                 // Some macros LyX will need
2417                 tmppreamble = features.getMacros(params);
2418
2419                 if (!tmppreamble.empty()) {
2420                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2421                                 "LyX specific LaTeX commands.\n"
2422                                 + tmppreamble + '\n';
2423                 }
2424
2425                 // the text class specific preamble 
2426                 tmppreamble = features.getTClassPreamble(params);
2427                 if (!tmppreamble.empty()) {
2428                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2429                                 "Textclass specific LaTeX commands.\n"
2430                                 + tmppreamble + '\n';
2431                 }
2432
2433                 /* the user-defined preamble */
2434                 if (!params.preamble.empty()) {
2435                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2436                                 "User specified LaTeX commands.\n"
2437                                 + params.preamble + '\n';
2438                 }
2439
2440                 preamble += "\\makeatother\n\n";
2441
2442                 // Itemize bullet settings need to be last in case the user
2443                 // defines their own bullets that use a package included
2444                 // in the user-defined preamble -- ARRae
2445                 // Actually it has to be done much later than that
2446                 // since some packages like frenchb make modifications
2447                 // at \begin{document} time -- JMarc 
2448                 string bullets_def;
2449                 for (int i = 0; i < 4; ++i) {
2450                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2451                                 if (bullets_def.empty())
2452                                         bullets_def="\\AtBeginDocument{\n";
2453                                 bullets_def += "  \\renewcommand{\\labelitemi";
2454                                 switch (i) {
2455                                 // `i' is one less than the item to modify
2456                                 case 0:
2457                                         break;
2458                                 case 1:
2459                                         bullets_def += 'i';
2460                                         break;
2461                                 case 2:
2462                                         bullets_def += "ii";
2463                                         break;
2464                                 case 3:
2465                                         bullets_def += 'v';
2466                                         break;
2467                                 }
2468                                 bullets_def += "}{" + 
2469                                   params.user_defined_bullets[i].getText() 
2470                                   + "}\n";
2471                         }
2472                 }
2473
2474                 if (!bullets_def.empty())
2475                   preamble += bullets_def + "}\n\n";
2476
2477                 for (int j = countChar(preamble, '\n'); j-- ;) {
2478                         texrow.newline();
2479                 }
2480
2481                 ofs << preamble;
2482
2483                 // make the body.
2484                 LFile += "\\begin{document}\n\n";
2485                 texrow.newline();
2486                 texrow.newline();
2487         } // only_body
2488         lyxerr.debug() << "preamble finished, now the body." << endl;
2489         
2490         bool was_title = false;
2491         bool already_title = false;
2492         string ftnote;
2493         TexRow ft_texrow;
2494         int ftcount = 0;
2495         int loop_count = 0;
2496
2497         LyXParagraph * par = paragraph;
2498
2499         // if only_body
2500         while (par) {
2501                 ++loop_count;
2502                 if (par->IsDummy())
2503                         lyxerr[Debug::LATEX] << "Error in MakeLateXFile."
2504                                              << endl;
2505                 LyXLayout const & layout =
2506                         textclasslist.Style(params.textclass,
2507                                             par->layout);
2508             
2509                 if (layout.intitle) {
2510                         if (already_title) {
2511                                 lyxerr <<"Error in MakeLatexFile: You"
2512                                         " should not mix title layouts"
2513                                         " with normal ones." << endl;
2514                         } else
2515                                 was_title = true;
2516                 } else if (was_title && !already_title) {
2517                         LFile += "\\maketitle\n";
2518                         texrow.newline();
2519                         already_title = true;
2520                         was_title = false;                  
2521                 }
2522                 // We are at depth 0 so we can just use
2523                 // ordinary \footnote{} generation
2524                 // flag this with ftcount
2525                 ftcount = -1;
2526                 if (layout.isEnvironment()
2527                     || par->pextra_type != LyXParagraph::PEXTRA_NONE) {
2528                         par = par->TeXEnvironment(LFile, texrow,
2529                                                   ftnote, ft_texrow, ftcount);
2530                 } else {
2531                         par = par->TeXOnePar(LFile, texrow,
2532                                              ftnote, ft_texrow, ftcount);
2533                 }
2534
2535                 // Write out what we've generated...and reset LFile
2536                 if (ftcount >= 1) {
2537                         if (ftcount > 1) {
2538                                 LFile += "\\addtocounter{footnote}{-";
2539                                 LFile += tostr(ftcount - 1);
2540                                 LFile += '}';
2541                         }
2542                         LFile += ftnote;
2543                         texrow += ft_texrow;
2544                         ftnote.clear();
2545                         ft_texrow.reset();
2546                         ftcount = 0;
2547                 }
2548                 if (loop_count == 2) {
2549                         // fwrite()ing every second time through the loop
2550                         // gains a few extra % of speed; going higher than
2551                         // 2 will slow things down again.  I'll look at
2552                         // LFile.length() in a future revision.  ARRae
2553                         ofs << LFile;
2554                         LFile.clear();
2555                         loop_count = 0;
2556                 }
2557         }
2558
2559         // It might be that we only have a title in this document
2560         if (was_title && !already_title) {
2561                 LFile += "\\maketitle\n";
2562                 texrow.newline();
2563         }
2564
2565         if (!only_body) {
2566                 LFile += "\\end{document}\n";
2567                 texrow.newline();
2568         
2569                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2570         } else {
2571                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2572                                      << endl;
2573         }
2574
2575         // Just to be sure. (Asger)
2576         texrow.newline();
2577
2578         // Write out what we've generated...and reset LFile
2579         ofs << LFile;
2580         LFile.clear();
2581
2582         // tex_code_break_column's value is used to decide
2583         // if we are in batchmode or not (within mathed_write()
2584         // in math_write.C) so we must set it to a non-zero
2585         // value when we leave otherwise we save incorrect .lyx files.
2586         tex_code_break_column = lyxrc->ascii_linelen;
2587
2588         // How to check if the close went ok when using fstreams
2589         ofs.close();
2590         lyxerr.debug() << "Finished making latex file." << endl;
2591 }
2592 #endif
2593
2594
2595 bool Buffer::isLatex() const
2596 {
2597         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2598 }
2599
2600
2601 bool Buffer::isLinuxDoc() const
2602 {
2603         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2604 }
2605
2606
2607 bool Buffer::isLiterate() const
2608 {
2609         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2610 }
2611
2612
2613 bool Buffer::isDocBook() const
2614 {
2615         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2616 }
2617
2618
2619 bool Buffer::isSGML() const
2620 {
2621         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2622                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2623 }
2624
2625
2626 void Buffer::sgmlOpenTag(ostream & os, int depth,
2627                          string const & latexname) const
2628 {
2629         os << string(depth, ' ') << "<" << latexname << ">\n";
2630 }
2631
2632
2633 void Buffer::sgmlCloseTag(ostream & os, int depth,
2634                           string const & latexname) const
2635 {
2636         os << string(depth, ' ') << "</" << latexname << ">\n";
2637 }
2638
2639
2640 void Buffer::makeLinuxDocFile(string const & fname, int column)
2641 {
2642         LyXParagraph * par = paragraph;
2643
2644         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2645         string environment_stack[10];
2646         string item_name;
2647
2648         int depth = 0;              /* paragraph depth */
2649
2650         ofstream ofs(fname.c_str());
2651
2652         if (!ofs) {
2653                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2654                 return;
2655         }
2656    
2657         tex_code_break_column = column; 
2658         texrow.reset();
2659    
2660         if (params.preamble.empty()) {
2661                 ofs << "<!doctype linuxdoc system>\n\n";
2662         }
2663         else {
2664                 ofs << "<!doctype linuxdoc system \n [ "
2665                     << params.preamble << " \n]>\n\n";
2666         }
2667
2668         ofs << "<!-- "  << LYX_DOCVERSION 
2669             << " created this file. For more info see http://www.lyx.org/"
2670             << " -->\n";
2671
2672         if(params.options.empty())
2673                 sgmlOpenTag(ofs, 0, top_element);
2674         else {
2675                 string top = top_element;
2676                 top += " ";
2677                 top += params.options;
2678                 sgmlOpenTag(ofs, 0, top);
2679         }
2680
2681         while (par) {
2682                 int desc_on = 0;            /* description mode*/
2683                 LyXLayout const & style =
2684                         textclasslist.Style(users->buffer()->params.textclass,
2685                                             par->layout);
2686                 par->AutoDeleteInsets();
2687
2688                 /* treat <toc> as a special case for compatibility with old code */
2689                 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2690                         Inset * inset = par->GetInset(0);
2691                         char  lyx_code = inset->LyxCode();
2692                         if (lyx_code == Inset::TOC_CODE){
2693                                 string temp = "toc";
2694                                 sgmlOpenTag(ofs, depth, temp);
2695
2696                                 par = par->next;
2697                                 linuxDocHandleFootnote(ofs, par, depth);
2698                                 continue;
2699                         }
2700                 }
2701
2702                 // environment tag closing
2703                 for( ; depth > par->depth; --depth) {
2704                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2705                         environment_stack[depth].clear();
2706                 }
2707
2708                 // write opening SGML tags
2709                 switch(style.latextype) {
2710                 case LATEX_PARAGRAPH:
2711                         if(depth == par->depth 
2712                            && !environment_stack[depth].empty()) {
2713                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2714                                 environment_stack[depth].clear();
2715                                 if(depth) 
2716                                         --depth;
2717                                 else
2718                                         ofs << "</p>";
2719                         }
2720                         sgmlOpenTag(ofs, depth, style.latexname());
2721                         break;
2722
2723                 case LATEX_COMMAND:
2724                         if (depth!= 0)
2725                                 LinuxDocError(par, 0, _("Error : Wrong depth for LatexType Command.\n"));
2726
2727                         if (!environment_stack[depth].empty()){
2728                                 sgmlCloseTag(ofs, depth,
2729                                              environment_stack[depth]);
2730                                 ofs << "</p>";
2731                         }
2732
2733                         environment_stack[depth].clear();
2734                         sgmlOpenTag(ofs, depth, style.latexname());
2735                         break;
2736
2737                 case LATEX_ENVIRONMENT:
2738                 case LATEX_ITEM_ENVIRONMENT:
2739                         if(depth == par->depth 
2740                            && environment_stack[depth] != style.latexname()
2741                            && !environment_stack[depth].empty()) {
2742
2743                                 sgmlCloseTag(ofs, depth,
2744                                              environment_stack[depth]);
2745                                 environment_stack[depth].clear();
2746                         }
2747                         if (depth < par->depth) {
2748                                depth = par->depth;
2749                                environment_stack[depth].clear();
2750                         }
2751                         if (environment_stack[depth] != style.latexname()) {
2752                                 if(depth == 0) {
2753                                         string temp = "p";
2754                                         sgmlOpenTag(ofs, depth, temp);
2755                                 }
2756                                 environment_stack[depth] = style.latexname();
2757                                 sgmlOpenTag(ofs, depth, environment_stack[depth]);
2758                         }
2759                         if(style.latextype == LATEX_ENVIRONMENT) break;
2760
2761                         desc_on = (style.labeltype == LABEL_MANUAL);
2762
2763                         if(desc_on)
2764                                 item_name = "tag";
2765                         else
2766                                 item_name = "item";
2767
2768                         sgmlOpenTag(ofs, depth + 1, item_name);
2769                         break;
2770                 default:
2771                         sgmlOpenTag(ofs, depth, style.latexname());
2772                         break;
2773                 }
2774
2775                 do {
2776                         SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2777
2778                         par = par->next;
2779                         linuxDocHandleFootnote(ofs, par, depth);
2780                 }
2781                 while(par && par->IsDummy());
2782
2783                 ofs << "\n";
2784                 /* write closing SGML tags */
2785                 switch(style.latextype) {
2786                 case LATEX_COMMAND:
2787                 case LATEX_ENVIRONMENT:
2788                 case LATEX_ITEM_ENVIRONMENT:
2789                         break;
2790                 default:
2791                         sgmlCloseTag(ofs, depth, style.latexname());
2792                         break;
2793                 }
2794         }
2795    
2796         /* Close open tags */
2797         for(; depth > 0; --depth)
2798                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2799
2800         if(!environment_stack[depth].empty())
2801                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2802
2803         ofs << "\n\n";
2804         sgmlCloseTag(ofs, 0, top_element);
2805
2806         ofs.close();
2807         // How to check for successful close
2808 }
2809
2810
2811 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2812                                     int const depth)
2813 {
2814         string tag = "footnote";
2815
2816         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2817                 sgmlOpenTag(os, depth + 1, tag);
2818                 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2819                 sgmlCloseTag(os, depth + 1, tag);
2820                 par = par->next;
2821         }
2822 }
2823
2824
2825 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2826                                   int const depth, int desc_on,
2827                                   LyXParagraph * & par)
2828 {
2829         LyXParagraph * tpar = par;
2830         while (tpar && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE) &&
2831                (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2832                                                              "Caption").second))
2833                 tpar = tpar->next;
2834         if (tpar &&
2835             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2836                                                          "Caption").second) {
2837                 sgmlOpenTag(os, depth + 1, inner_tag);
2838 #ifdef USE_OSTREAM_ONLY
2839                 string extra_par;
2840                 SimpleDocBookOnePar(os, extra_par, tpar,
2841                                     desc_on, depth + 2);
2842 #else
2843                 string tmp_par, extra_par;
2844                 SimpleDocBookOnePar(tmp_par, extra_par, tpar,
2845                                     desc_on, depth + 2);
2846                 tmp_par = strip(tmp_par);
2847                 tmp_par = frontStrip(tmp_par);
2848                 os << tmp_par;
2849 #endif
2850                 sgmlCloseTag(os, depth+1, inner_tag);
2851                 if(!extra_par.empty())
2852                         os << extra_par;
2853         }
2854 }
2855
2856
2857 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2858                                    int const depth)
2859 {
2860         string tag, inner_tag;
2861         string tmp_par, extra_par;
2862         bool inner_span = false;
2863         int desc_on = 4;
2864
2865         // This is not how I like to see enums. They should not be anonymous
2866         // and variables of its type should not be declared right after the
2867         // last brace. (Lgb)
2868         enum SOME_ENUM {
2869                 NO_ONE,
2870                 FOOTNOTE_LIKE,
2871                 MARGIN_LIKE,
2872                 FIG_LIKE,
2873                 TAB_LIKE
2874         };
2875         SOME_ENUM last = NO_ONE;
2876         SOME_ENUM present = FOOTNOTE_LIKE;
2877
2878         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2879                 if(last == present) {
2880                         if(inner_span) {
2881                                 if(!tmp_par.empty()) {
2882                                         os << tmp_par;
2883                                         tmp_par.clear();
2884                                         sgmlCloseTag(os, depth+1, inner_tag);
2885                                         sgmlOpenTag(os, depth+1, inner_tag);
2886                                 }
2887                         }
2888                         else
2889                                 os << "\n";
2890                 } else {
2891                         os << tmp_par;
2892                         if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1,
2893                                                             inner_tag);
2894                         if(!extra_par.empty()) os << extra_par;
2895                         if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2896                         extra_par.clear();
2897
2898                         switch (par->footnotekind) {
2899                         case LyXParagraph::FOOTNOTE:
2900                         case LyXParagraph::ALGORITHM:
2901                                 tag = "footnote";
2902                                 inner_tag = "para";
2903                                 present = FOOTNOTE_LIKE;
2904                                 inner_span = true;
2905                                 break;
2906                         case LyXParagraph::MARGIN:
2907                                 tag = "sidebar";
2908                                 inner_tag = "para";
2909                                 present = MARGIN_LIKE;
2910                                 inner_span = true;
2911                                 break;
2912                         case LyXParagraph::FIG:
2913                         case LyXParagraph::WIDE_FIG:
2914                                 tag = "figure";
2915                                 inner_tag = "title";
2916                                 present = FIG_LIKE;
2917                                 inner_span = false;
2918                                 break;
2919                         case LyXParagraph::TAB:
2920                         case LyXParagraph::WIDE_TAB:
2921                                 tag = "table";
2922                                 inner_tag = "title";
2923                                 present = TAB_LIKE;
2924                                 inner_span = false;
2925                                 break;
2926                         }
2927                         sgmlOpenTag(os, depth, tag);
2928                         if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2929                                 DocBookHandleCaption(os, inner_tag, depth,
2930                                                      desc_on, par);
2931                                 inner_tag.clear();
2932                         } else {
2933                                 sgmlOpenTag(os, depth + 1, inner_tag);
2934                         }
2935                 }
2936                 // ignore all caption here, we processed them above!!!
2937                 if (par->layout != textclasslist.NumberOfLayout(params.textclass,
2938                                                            "Caption").second) {
2939 #ifdef USE_OSTREAM_ONLY
2940 #ifdef HAVE_SSTREAM
2941                         ostringstream ost;
2942 #else
2943                         ostrstream ost;
2944 #endif
2945                         SimpleDocBookOnePar(ost, extra_par, par,
2946                                             desc_on, depth + 2);
2947 #ifdef HAVE_SSTREAM
2948                         tmp_par += ost.str().c_str();
2949 #else
2950                         ost << '\0';
2951                         char * ctmp = ost.str();
2952                         tmp_par += ctmp;
2953                         delete [] ctmp;
2954 #endif
2955 #else
2956 #endif
2957                 }
2958                 tmp_par = frontStrip(strip(tmp_par));
2959
2960                 last = present;
2961                 par = par->next;
2962         }
2963         os << tmp_par;
2964         if(!inner_tag.empty()) sgmlCloseTag(os, depth + 1, inner_tag);
2965         if(!extra_par.empty()) os << extra_par;
2966         if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2967 }
2968
2969
2970 /* push a tag in a style stack */
2971 void Buffer::push_tag(ostream & os, char const * tag,
2972                       int & pos, char stack[5][3])
2973 {
2974         /* pop all previous tags */
2975         for (int j = pos; j >= 0; --j)
2976                 os << "</" << stack[j] << ">";
2977
2978         /* add new tag */
2979         sprintf(stack[++pos], "%s", tag);
2980
2981         /* push all tags */
2982         for (int i = 0; i <= pos; ++i)
2983                 os << "<" << stack[i] << ">";
2984 }
2985
2986 void Buffer::pop_tag(ostream & os, char const * tag,
2987                      int & pos, char stack[5][3])
2988 {
2989         int j;
2990
2991         // pop all tags till specified one
2992         for (j = pos; (j >= 0) && (strcmp(stack[j], tag)); --j)
2993                 os << "</" << stack[j] << ">";
2994
2995         // closes the tag
2996         os << "</" << tag << ">";
2997
2998         // push all tags, but the specified one
2999         for (j = j + 1; j <= pos; ++j) {
3000                 os << "<" << stack[j] << ">";
3001                 strcpy(stack[j-1], stack[j]);
3002         }
3003         --pos;
3004 }
3005
3006
3007 /* handle internal paragraph parsing -- layout already processed */
3008
3009 // checks, if newcol chars should be put into this line
3010 // writes newline, if necessary.
3011 static
3012 void linux_doc_line_break(ostream & os, unsigned int & colcount,
3013                           const unsigned int newcol)
3014 {
3015         colcount += newcol;
3016         if (colcount > lyxrc->ascii_linelen) {
3017                 os << "\n";
3018                 colcount = newcol; // assume write after this call
3019         }
3020 }
3021
3022
3023 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
3024                                   int desc_on, int const /*depth*/)
3025 {
3026         LyXFont font1, font2;
3027         char c;
3028         Inset * inset;
3029         LyXParagraph::size_type main_body;
3030         int j;
3031         LyXLayout const & style = textclasslist.Style(params.textclass,
3032                                                       par->GetLayout());
3033
3034         char family_type = 0;               // family font flag 
3035         bool is_bold     = false;           // series font flag 
3036         char shape_type  = 0;               // shape font flag 
3037         bool is_em = false;                 // emphasis (italic) font flag 
3038
3039         int stack_num = -1;          // style stack position 
3040         char stack[5][3];            // style stack 
3041         unsigned int char_line_count = 5;     // Heuristic choice ;-) 
3042
3043         if (style.labeltype != LABEL_MANUAL)
3044                 main_body = 0;
3045         else
3046                 main_body = par->BeginningOfMainBody();
3047
3048         /* gets paragraph main font */
3049         if (main_body > 0)
3050                 font1 = style.labelfont;
3051         else
3052                 font1 = style.font;
3053
3054   
3055         /* parsing main loop */
3056         for (LyXParagraph::size_type i = 0;
3057              i < par->size(); ++i) {
3058
3059                 /* handle quote tag */
3060                 if (i == main_body && !par->IsDummy()) {
3061                         if (main_body > 0)
3062                                 font1 = style.font;
3063                 }
3064
3065                 font2 = par->getFont(i);
3066
3067                 if (font1.family() != font2.family()) {
3068                         switch(family_type) {
3069                         case 0:
3070                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
3071                                         push_tag(os, "tt", stack_num, stack);
3072                                         family_type= 1;
3073                                 }
3074                                 else if (font2.family() == LyXFont::SANS_FAMILY) {
3075                                         push_tag(os, "sf", stack_num, stack);
3076                                         family_type= 2;
3077                                 }
3078                                 break;
3079                         case 1:
3080                                 pop_tag(os, "tt", stack_num, stack);
3081                                 if (font2.family() == LyXFont::SANS_FAMILY) {
3082                                         push_tag(os, "sf", stack_num, stack);
3083                                         family_type= 2;
3084                                 }
3085                                 else {
3086                                         family_type= 0;
3087                                 }
3088                                 break;
3089                         case 2:
3090                                 pop_tag(os, "sf", stack_num, stack);
3091                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
3092                                         push_tag(os, "tt", stack_num, stack);
3093                                         family_type= 1;
3094                                 }
3095                                 else {
3096                                         family_type= 0;
3097                                 }
3098                         }
3099                 }
3100
3101                 /* handle bold face */
3102                 if (font1.series() != font2.series()) {
3103                         if (font2.series() == LyXFont::BOLD_SERIES) {
3104                                 push_tag(os, "bf", stack_num, stack);
3105                                 is_bold = true;
3106                         }
3107                         else if (is_bold) {
3108                                 pop_tag(os, "bf", stack_num, stack);
3109                                 is_bold = false;
3110                         }
3111                 }
3112
3113                 /* handle italic and slanted fonts */
3114                 if (font1.shape() != font2.shape()) {
3115                         switch(shape_type) {
3116                         case 0:
3117                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
3118                                         push_tag(os, "it", stack_num, stack);
3119                                         shape_type= 1;
3120                                 }
3121                                 else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
3122                                         push_tag(os, "sl", stack_num, stack);
3123                                         shape_type= 2;
3124                                 }
3125                                 break;
3126                         case 1:
3127                                 pop_tag(os, "it", stack_num, stack);
3128                                 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
3129                                         push_tag(os, "sl", stack_num, stack);
3130                                         shape_type= 2;
3131                                 }
3132                                 else {
3133                                         shape_type= 0;
3134                                 }
3135                                 break;
3136                         case 2:
3137                                 pop_tag(os, "sl", stack_num, stack);
3138                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
3139                                         push_tag(os, "it", stack_num, stack);
3140                                         shape_type= 1;
3141                                 }
3142                                 else {
3143                                         shape_type= 0;
3144                                 }
3145                         }
3146                 }
3147                 /* handle <em> tag */
3148                 if (font1.emph() != font2.emph()) {
3149                         if (font2.emph() == LyXFont::ON) {
3150                                 push_tag(os, "em", stack_num, stack);
3151                                 is_em = true;
3152                         } else if (is_em) {
3153                                 pop_tag(os, "em", stack_num, stack);
3154                                 is_em = false;
3155                         }
3156                 }
3157
3158                 c = par->GetChar(i);
3159       
3160                 if (font2.latex() == LyXFont::ON) {
3161                         // "TeX"-Mode on == > SGML-Mode on.
3162                         if (c!= '\0')
3163                                 os << c; // see LaTeX-Generation...
3164                         ++char_line_count;
3165                 } else if (c == LyXParagraph::META_INSET) {
3166                         inset = par->GetInset(i);
3167 #ifdef USE_OSTREAM_ONLY
3168                         inset->Linuxdoc(os);
3169 #else
3170                         string tmp_out;
3171                         inset->Linuxdoc(tmp_out);
3172                         os << tmp_out;
3173 #endif
3174                 }
3175                 else {
3176                         string sgml_string;
3177                         if (par->linuxDocConvertChar(c, sgml_string)
3178                             && !style.free_spacing) { // in freespacing
3179                                                      // mode, spaces are
3180                                                      // non-breaking characters
3181                                 // char is ' '
3182                                 if (desc_on == 1) {
3183                                         ++char_line_count;
3184                                         linux_doc_line_break(os, char_line_count, 6);
3185                                         os << "</tag>";
3186                                         desc_on = 2;
3187                                 }
3188                                 else  {
3189                                         linux_doc_line_break(os, char_line_count, 1);
3190                                         os << c;
3191                                 }
3192                         }
3193                         else {
3194                                 os << sgml_string;
3195                                 char_line_count += sgml_string.length();
3196                         }
3197                 }
3198                 font1 = font2;
3199         }
3200
3201         /* needed if there is an optional argument but no contents */
3202         if (main_body > 0 && main_body == par->size()) {
3203                 font1 = style.font;
3204         }
3205
3206         /* pop all defined Styles */
3207         for (j = stack_num; j >= 0; --j) {
3208                 linux_doc_line_break(os, 
3209                                      char_line_count, 
3210                                      3 + strlen(stack[j]));
3211                 os << "</" << stack[j] << ">";
3212         }
3213
3214         /* resets description flag correctly */
3215         switch(desc_on){
3216         case 1:
3217                 /* <tag> not closed... */
3218                 linux_doc_line_break(os, char_line_count, 6);
3219                 os << "</tag>";
3220                 break;
3221         case 2:
3222                 /* fprintf(file, "</p>");*/
3223                 break;
3224         }
3225 }
3226
3227
3228 /* print an error message */
3229 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
3230                            char const * message) 
3231 {
3232         InsetError * new_inset;
3233
3234         /* insert an error marker in text */
3235         new_inset = new InsetError(message);
3236         par->InsertChar(pos, LyXParagraph::META_INSET);
3237         par->InsertInset(pos, new_inset);
3238 }
3239
3240 // This constant defines the maximum number of 
3241 // environment layouts that can be nesteded.
3242 // The same applies for command layouts.
3243 // These values should be more than enough.
3244 //           José Matos (1999/07/22)
3245
3246 enum { MAX_NEST_LEVEL = 25};
3247
3248 void Buffer::makeDocBookFile(string const & fname, int column)
3249 {
3250         LyXParagraph * par = paragraph;
3251
3252         string top_element= textclasslist.LatexnameOfClass(params.textclass);
3253         string environment_stack[MAX_NEST_LEVEL];
3254         string environment_inner[MAX_NEST_LEVEL];
3255         string command_stack[MAX_NEST_LEVEL];
3256         bool command_flag= false;
3257         int command_depth= 0, command_base= 0, cmd_depth= 0;
3258
3259         string item_name, command_name;
3260         string c_depth, c_params, tmps;
3261
3262         int depth= 0;              /* paragraph depth */
3263
3264         tex_code_break_column = column; 
3265
3266         ofstream ofs(fname.c_str());
3267         if (!ofs) {
3268                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3269                 return;
3270         }
3271    
3272         texrow.reset();
3273
3274         ofs << "<!doctype " << top_element
3275             << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3276
3277         if (params.preamble.empty())
3278                 ofs << ">\n\n";
3279         else
3280                 ofs << "\n [ " << params.preamble << " \n]>\n\n";
3281
3282         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
3283             << "\n  See http://www.lyx.org/ for more information -->\n";
3284
3285         if(params.options.empty())
3286                 sgmlOpenTag(ofs, 0, top_element);
3287         else {
3288                 string top = top_element;
3289                 top += " ";
3290                 top += params.options;
3291                 sgmlOpenTag(ofs, 0, top);
3292         }
3293
3294         while (par) {
3295                 int desc_on = 0;            /* description mode*/
3296                 LyXLayout const & style =
3297                         textclasslist.Style(users->buffer()->params.textclass,
3298                                             par->layout);
3299                 par->AutoDeleteInsets();
3300
3301                 /* environment tag closing */
3302                 for( ; depth > par->depth; --depth) {
3303                         if(environment_inner[depth] != "!-- --") {
3304                                 item_name= "listitem";
3305                                 sgmlCloseTag(ofs, command_depth + depth,
3306                                              item_name);
3307                                 if( environment_inner[depth] == "varlistentry")
3308                                         sgmlCloseTag(ofs, depth+command_depth,
3309                                                      environment_inner[depth]);
3310                         }
3311                         sgmlCloseTag(ofs, depth + command_depth,
3312                                      environment_stack[depth]);
3313                         environment_stack[depth].clear();
3314                         environment_inner[depth].clear();
3315                 }
3316
3317                 if(depth == par->depth
3318                    && environment_stack[depth] != style.latexname()
3319                    && !environment_stack[depth].empty()) {
3320                         if(environment_inner[depth] != "!-- --") {
3321                                 item_name= "listitem";
3322                                 sgmlCloseTag(ofs, command_depth+depth,
3323                                              item_name);
3324                                 if( environment_inner[depth] == "varlistentry")
3325                                         sgmlCloseTag(ofs,
3326                                                      depth + command_depth,
3327                                                      environment_inner[depth]);
3328                         }
3329                         
3330                         sgmlCloseTag(ofs, depth + command_depth,
3331                                      environment_stack[depth]);
3332                         
3333                         environment_stack[depth].clear();
3334                         environment_inner[depth].clear();
3335                 }
3336
3337                 // Write opening SGML tags.
3338                 switch(style.latextype) {
3339                 case LATEX_PARAGRAPH:
3340                         if(style.latexname() != "dummy")
3341                                sgmlOpenTag(ofs, depth+command_depth,
3342                                            style.latexname());
3343                         break;
3344
3345                 case LATEX_COMMAND:
3346                         if (depth!= 0)
3347                                 LinuxDocError(par, 0,
3348                                               _("Error : Wrong depth for "
3349                                                 "LatexType Command.\n"));
3350                         
3351                         command_name = style.latexname();
3352                         
3353                         tmps = style.latexparam();
3354                         c_params = split(tmps, c_depth,'|');
3355                         
3356                         cmd_depth= atoi(c_depth.c_str());
3357                         
3358                         if(command_flag) {
3359                                 if(cmd_depth<command_base) {
3360                                         for(int j = command_depth;
3361                                             j >= command_base; --j)
3362                                                 if(!command_stack[j].empty())
3363                                                         sgmlCloseTag(ofs, j, command_stack[j]);
3364                                         command_depth= command_base= cmd_depth;
3365                                 }
3366                                 else if(cmd_depth <= command_depth) {
3367                                         for(int j = command_depth;
3368                                             j >= cmd_depth; --j)
3369
3370                                                 if(!command_stack[j].empty())
3371                                                         sgmlCloseTag(ofs, j, command_stack[j]);
3372                                         command_depth= cmd_depth;
3373                                 }
3374                                 else
3375                                         command_depth= cmd_depth;
3376                         }
3377                         else {
3378                                 command_depth = command_base = cmd_depth;
3379                                 command_flag = true;
3380                         }
3381                         command_stack[command_depth]= command_name;
3382
3383                         // treat label as a special case for
3384                         // more WYSIWYM handling.
3385                         if (par->GetChar(0) == LyXParagraph::META_INSET) {
3386                                 Inset * inset = par->GetInset(0);
3387                                 char  lyx_code = inset->LyxCode();
3388                                 if (lyx_code == Inset::LABEL_CODE){
3389                                         command_name += " id=\"";
3390                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3391                                         command_name += "\"";
3392                                         desc_on = 3;
3393                                 }
3394                         }
3395
3396                         sgmlOpenTag(ofs, depth+command_depth, command_name);
3397                         item_name = "title";
3398                         sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3399                         break;
3400
3401                 case LATEX_ENVIRONMENT:
3402                 case LATEX_ITEM_ENVIRONMENT:
3403                         if (depth < par->depth) {
3404                                 depth = par->depth;
3405                                 environment_stack[depth].clear();
3406                         }
3407
3408                         if (environment_stack[depth] != style.latexname()) {
3409                                 environment_stack[depth] = style.latexname();
3410                                 environment_inner[depth] = "!-- --";
3411                                 sgmlOpenTag(ofs, depth + command_depth,
3412                                             environment_stack[depth]);
3413                         } else {
3414                                 if(environment_inner[depth] != "!-- --") {
3415                                         item_name= "listitem";
3416                                         sgmlCloseTag(ofs,
3417                                                      command_depth + depth,
3418                                                      item_name);
3419                                         if (environment_inner[depth] == "varlistentry")
3420                                                 sgmlCloseTag(ofs,
3421                                                              depth + command_depth,
3422                                                              environment_inner[depth]);
3423                                 }
3424                         }
3425                         
3426                         if(style.latextype == LATEX_ENVIRONMENT) {
3427                                 if(!style.latexparam().empty())
3428                                         sgmlOpenTag(ofs, depth + command_depth,
3429                                                     style.latexparam());
3430                                 break;
3431                         }
3432
3433                         desc_on = (style.labeltype == LABEL_MANUAL);
3434
3435                         if(desc_on)
3436                                 environment_inner[depth]= "varlistentry";
3437                         else
3438                                 environment_inner[depth]= "listitem";
3439
3440                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3441                                     environment_inner[depth]);
3442
3443                         if(desc_on) {
3444                                 item_name= "term";
3445                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3446                                             item_name);
3447                         }
3448                         else {
3449                                 item_name= "para";
3450                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3451                                             item_name);
3452                         }
3453                         break;
3454                 default:
3455                         sgmlOpenTag(ofs, depth + command_depth,
3456                                     style.latexname());
3457                         break;
3458                 }
3459
3460                 do {
3461 #ifdef USE_OSTREAM_ONLY
3462                         string extra_par;
3463                         SimpleDocBookOnePar(ofs, extra_par, par, desc_on,
3464                                             depth + 1 + command_depth);
3465                         par = par->next;
3466                         DocBookHandleFootnote(ofs, par,
3467                                               depth + 1 + command_depth);
3468 #else
3469                         string tmp_par, extra_par;
3470
3471                         SimpleDocBookOnePar(tmp_par, extra_par, par, desc_on,
3472                                             depth + 1 + command_depth);
3473                         ofs << tmp_par;
3474
3475                         par = par->next;
3476                         DocBookHandleFootnote(ofs, par,
3477                                               depth + 1 + command_depth);
3478 #endif
3479                 }
3480                 while(par && par->IsDummy());
3481
3482                 string end_tag;
3483                 /* write closing SGML tags */
3484                 switch(style.latextype) {
3485                 case LATEX_COMMAND:
3486                         end_tag = "title";
3487                         sgmlCloseTag(ofs, depth + command_depth, end_tag);
3488                         break;
3489                 case LATEX_ENVIRONMENT:
3490                         if(!style.latexparam().empty())
3491                                 sgmlCloseTag(ofs, depth + command_depth,
3492                                              style.latexparam());
3493                         break;
3494                 case LATEX_ITEM_ENVIRONMENT:
3495                         if(desc_on == 1) break;
3496                         end_tag= "para";
3497                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3498                         break;
3499                 case LATEX_PARAGRAPH:
3500                         if(style.latexname() != "dummy")
3501                                 sgmlCloseTag(ofs, depth + command_depth,
3502                                              style.latexname());
3503                         break;
3504                 default:
3505                         sgmlCloseTag(ofs, depth + command_depth,
3506                                      style.latexname());
3507                         break;
3508                 }
3509         }
3510
3511         // Close open tags
3512         for(; depth >= 0; --depth) {
3513                 if(!environment_stack[depth].empty()) {
3514                         if(environment_inner[depth] != "!-- --") {
3515                                 item_name= "listitem";
3516                                 sgmlCloseTag(ofs, command_depth + depth,
3517                                              item_name);
3518                                if( environment_inner[depth] == "varlistentry")
3519                                        sgmlCloseTag(ofs, depth + command_depth,
3520                                                     environment_inner[depth]);
3521                         }
3522                         
3523                         sgmlCloseTag(ofs, depth + command_depth,
3524                                      environment_stack[depth]);
3525                 }
3526         }
3527         
3528         for(int j = command_depth; j >= command_base; --j)
3529                 if(!command_stack[j].empty())
3530                         sgmlCloseTag(ofs, j, command_stack[j]);
3531
3532         ofs << "\n\n";
3533         sgmlCloseTag(ofs, 0, top_element);
3534
3535         ofs.close();
3536         // How to check for successful close
3537 }
3538
3539
3540 #ifdef USE_OSTREAM_ONLY
3541 void Buffer::SimpleDocBookOnePar(ostream & os, string & extra,
3542                                  LyXParagraph * par, int & desc_on,
3543                                  int const depth) 
3544 {
3545         if (par->table) {
3546                 par->SimpleDocBookOneTablePar(os, extra, desc_on, depth);
3547                 return;
3548         }
3549         LyXFont font1, font2;
3550         char c;
3551         Inset * inset;
3552         LyXParagraph::size_type main_body;
3553         int j;
3554         //string emph = "emphasis";
3555         bool emph_flag = false;
3556         int char_line_count = 0;
3557
3558         LyXLayout const & style = textclasslist.Style(params.textclass,
3559                                                       par->GetLayout());
3560
3561         if (style.labeltype != LABEL_MANUAL)
3562                 main_body = 0;
3563         else
3564                 main_body = par->BeginningOfMainBody();
3565
3566         // gets paragraph main font
3567         if (main_body > 0)
3568                 font1 = style.labelfont;
3569         else
3570                 font1 = style.font;
3571
3572         char_line_count = depth;
3573         if(!style.free_spacing)
3574                 for (j = 0; j < depth; ++j)
3575                         os << ' ';
3576
3577         // parsing main loop
3578         for (LyXParagraph::size_type i = 0;
3579              i < par->size(); ++i) {
3580                 font2 = par->getFont(i);
3581
3582                 // handle <emphasis> tag
3583                 if (font1.emph() != font2.emph() && i) {
3584                         if (font2.emph() == LyXFont::ON) {
3585                                 os << "<emphasis>";
3586                                 emph_flag= true;
3587                         }else {
3588                                 os << "</emphasis>";
3589                                 emph_flag= false;
3590                         }
3591                 }
3592       
3593                 c = par->GetChar(i);
3594
3595                 if (c == LyXParagraph::META_INSET) {
3596                         inset = par->GetInset(i);
3597 #ifdef HAVE_SSTREAM
3598                         ostringstream ost;
3599                         inset->DocBook(ost);
3600                         string tmp_out = ost.str().c_str();
3601 #else
3602                         ostrstream ost;
3603                         inset->DocBook(ost);
3604                         ost << '\0';
3605                         char * ctmp = ost.str();
3606                         string tmp_out(ctmp);
3607                         delete [] ctmp;
3608 #endif
3609                         //
3610                         // This code needs some explanation:
3611                         // Two insets are treated specially
3612                         //   label if it is the first element in a command paragraph
3613                         //         desc_on == 3
3614                         //   graphics inside tables or figure floats can't go on
3615                         //   title (the equivalente in latex for this case is caption
3616                         //   and title should come first
3617                         //         desc_on == 4
3618                         //
3619                         if(desc_on!= 3 || i!= 0) {
3620                                 if(!tmp_out.empty() && tmp_out[0] == '@') {
3621                                         if(desc_on == 4)
3622                                                 extra += frontStrip(tmp_out, '@');
3623                                         else
3624                                                 os << frontStrip(tmp_out, '@');
3625                                 }
3626                                 else
3627                                         os << tmp_out;
3628                         }
3629                 } else if (font2.latex() == LyXFont::ON) {
3630                         // "TeX"-Mode on ==> SGML-Mode on.
3631                         if (c!= '\0')
3632                                 os << c;
3633                         ++char_line_count;
3634                 }
3635                 else {
3636                         string sgml_string;
3637                         if (par->linuxDocConvertChar(c, sgml_string)
3638                             && !style.free_spacing) { // in freespacing
3639                                                      // mode, spaces are
3640                                                      // non-breaking characters
3641                                 // char is ' '
3642                                 if (desc_on == 1) {
3643                                         ++char_line_count;
3644                                         os << "\n</term><listitem><para>";
3645                                         desc_on = 2;
3646                                 }
3647                                 else  {
3648                                         os << c;
3649                                 }
3650                         }
3651                         else {
3652                                 os << sgml_string;
3653                         }
3654                 }
3655                 font1 = font2;
3656         }
3657
3658         /* needed if there is an optional argument but no contents */
3659         if (main_body > 0 && main_body == par->size()) {
3660                 font1 = style.font;
3661         }
3662         if (emph_flag) {
3663                 os << "</emphasis>";
3664         }
3665         
3666         /* resets description flag correctly */
3667         switch(desc_on){
3668         case 1:
3669                 /* <term> not closed... */
3670                 os << "</term>";
3671                 break;
3672         }
3673         os << '\n';
3674 }
3675 #else
3676 void Buffer::SimpleDocBookOnePar(string & file, string & extra,
3677                                  LyXParagraph * par, int & desc_on,
3678                                  int const depth) 
3679 {
3680         if (par->table) {
3681                 par->SimpleDocBookOneTablePar(file, extra, desc_on, depth);
3682                 return;
3683         }
3684         LyXFont font1, font2;
3685         char c;
3686         Inset * inset;
3687         LyXParagraph::size_type main_body;
3688         int j;
3689         string emph= "emphasis";
3690         bool emph_flag= false;
3691         int char_line_count= 0;
3692
3693         LyXLayout const & style = textclasslist.Style(params.textclass,
3694                                                       par->GetLayout());
3695
3696         if (style.labeltype != LABEL_MANUAL)
3697                 main_body = 0;
3698         else
3699                 main_body = par->BeginningOfMainBody();
3700
3701         /* gets paragraph main font */
3702         if (main_body > 0)
3703                 font1 = style.labelfont;
3704         else
3705                 font1 = style.font;
3706
3707         char_line_count = depth;
3708         if(!style.free_spacing)
3709                 for (j = 0; j < depth; ++j)
3710                         file += ' ';
3711
3712         /* parsing main loop */
3713         for (LyXParagraph::size_type i = 0;
3714              i < par->size(); ++i) {
3715                 font2 = par->getFont(i);
3716
3717                 /* handle <emphasis> tag */
3718                 if (font1.emph() != font2.emph() && i) {
3719                         if (font2.emph() == LyXFont::ON) {
3720                                 file += "<emphasis>";
3721                                 emph_flag= true;
3722                         }else {
3723                                 file += "</emphasis>";
3724                                 emph_flag= false;
3725                         }
3726                 }
3727       
3728                 c = par->GetChar(i);
3729
3730                 if (c == LyXParagraph::META_INSET) {
3731                         inset = par->GetInset(i);
3732 #ifdef USE_OSTREAM_ONLY
3733 #ifdef HAVE_SSTREAM
3734                         ostringstream ost;
3735                         inset->DocBook(ost);
3736                         string tmp_out = ost.str().c_str();
3737 #else
3738                         ostrstream ost;
3739                         inset->DocBook(ost);
3740                         ost << '\0';
3741                         char * ctmp = ost.str();
3742                         string tmp_out(ctmp);
3743                         delete [] ctmp;
3744 #endif
3745 #else
3746                         string tmp_out;
3747                         inset->DocBook(tmp_out);
3748 #endif
3749                         //
3750                         // This code needs some explanation:
3751                         // Two insets are treated specially
3752                         //   label if it is the first element in a command paragraph
3753                         //         desc_on == 3
3754                         //   graphics inside tables or figure floats can't go on
3755                         //   title (the equivalente in latex for this case is caption
3756                         //   and title should come first
3757                         //         desc_on == 4
3758                         //
3759                         if(desc_on!= 3 || i!= 0) {
3760                                 if(!tmp_out.empty() && tmp_out[0] == '@') {
3761                                         if(desc_on == 4)
3762                                                 extra += frontStrip(tmp_out, '@');
3763                                         else
3764                                                 file += frontStrip(tmp_out, '@');
3765                                 }
3766                                 else
3767                                         file += tmp_out;
3768                         }
3769                 } else if (font2.latex() == LyXFont::ON) {
3770                         // "TeX"-Mode on ==> SGML-Mode on.
3771                         if (c!= '\0')
3772                                 file += c;
3773                         ++char_line_count;
3774                 }
3775                 else {
3776                         string sgml_string;
3777                         if (par->linuxDocConvertChar(c, sgml_string)
3778                             && !style.free_spacing) { // in freespacing
3779                                                      // mode, spaces are
3780                                                      // non-breaking characters
3781                                 // char is ' '
3782                                 if (desc_on == 1) {
3783                                         ++char_line_count;
3784                                         file += '\n';
3785                                         file += "</term><listitem><para>";
3786                                         desc_on = 2;
3787                                 }
3788                                 else  {
3789                                         file += c;
3790                                 }
3791                         }
3792                         else {
3793                                 file += sgml_string;
3794                         }
3795                 }
3796                 font1 = font2;
3797         }
3798
3799         /* needed if there is an optional argument but no contents */
3800         if (main_body > 0 && main_body == par->size()) {
3801                 font1 = style.font;
3802         }
3803         if (emph_flag) {
3804                 file += "</emphasis>";
3805         }
3806         
3807         /* resets description flag correctly */
3808         switch(desc_on){
3809         case 1:
3810                 /* <term> not closed... */
3811                 file += "</term>";
3812                 break;
3813         }
3814         file += '\n';
3815 }
3816 #endif
3817
3818
3819 int Buffer::runLaTeX()
3820 {
3821         if (!users->text) return 0;
3822
3823         ProhibitInput();
3824
3825         // get LaTeX-Filename
3826         string name = getLatexName();
3827
3828         string path = OnlyPath(filename);
3829
3830         string org_path = path;
3831         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3832                 path = tmppath;  
3833         }
3834
3835         Path p(path); // path to LaTeX file
3836         users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));   
3837
3838         // Remove all error insets
3839         bool a = users->removeAutoInsets();
3840
3841         // Always generate the LaTeX file
3842         makeLaTeXFile(name, org_path, false);
3843         markDviDirty();
3844
3845         // do the LaTex run(s)
3846         TeXErrors terr;
3847         string latex_command = lyxrc->pdf_mode ?
3848                 lyxrc->pdflatex_command : lyxrc->latex_command;
3849         LaTeX latex(latex_command, name, filepath);
3850         int res = latex.run(terr,
3851                             users->owner()->getMiniBuffer()); // running latex
3852
3853         // check return value from latex.run().
3854         if ((res & LaTeX::NO_LOGFILE)) {
3855                 WriteAlert(_("LaTeX did not work!"),
3856                            _("Missing log file:"), name);
3857         } else if ((res & LaTeX::ERRORS)) {
3858                 users->owner()->getMiniBuffer()->Set(_("Done"));
3859                 // Insert all errors as errors boxes
3860                 users->insertErrors(terr);
3861                 
3862                 // Dvi should also be kept dirty if the latex run
3863                 // ends up with errors. However it should be possible
3864                 // to view a dirty dvi too.
3865         } else {
3866                 //no errors or any other things to think about so:
3867                 users->owner()->getMiniBuffer()->Set(_("Done"));
3868                 markDviClean();
3869         }
3870
3871         // if we removed error insets before we ran LaTeX or if we inserted
3872         // error insets after we ran LaTeX this must be run:
3873         if (a || (res & LaTeX::ERRORS)){
3874                 users->redraw();
3875                 users->fitCursor();
3876                 users->updateScrollbar();
3877         }
3878         AllowInput();
3879  
3880         return latex.getNumErrors();
3881 }
3882
3883
3884 int Buffer::runLiterate()
3885 {
3886         if (!users->text) return 0;
3887
3888         ProhibitInput();
3889
3890         // get LaTeX-Filename
3891         string name = getLatexName();
3892         // get Literate-Filename
3893         string lit_name = ChangeExtension (getLatexName(), 
3894                                            lyxrc->literate_extension, true);
3895
3896         string path = OnlyPath(filename);
3897
3898         string org_path = path;
3899         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3900                 path = tmppath;  
3901         }
3902
3903         Path p(path); // path to Literate file
3904         users->owner()->getMiniBuffer()->Set(_("Running Literate..."));   
3905
3906         // Remove all error insets
3907         bool a = users->removeAutoInsets();
3908
3909         // generate the Literate file if necessary
3910         if (!isDviClean() || a) {
3911                 makeLaTeXFile(lit_name, org_path, false);
3912                 markDviDirty();
3913         }
3914
3915         string latex_command = lyxrc->pdf_mode ?
3916                 lyxrc->pdflatex_command : lyxrc->latex_command;
3917         Literate literate(latex_command, name, filepath, 
3918                           lit_name,
3919                           lyxrc->literate_command, lyxrc->literate_error_filter,
3920                           lyxrc->build_command, lyxrc->build_error_filter);
3921         TeXErrors terr;
3922         int res = literate.weave(terr, users->owner()->getMiniBuffer());
3923
3924         // check return value from literate.weave().
3925         if ((res & Literate::NO_LOGFILE)) {
3926                 WriteAlert(_("Literate command did not work!"),
3927                            _("Missing log file:"), name);
3928         } else if ((res & Literate::ERRORS)) {
3929                 users->owner()->getMiniBuffer()->Set(_("Done"));
3930                 // Insert all errors as errors boxes
3931                 users->insertErrors(terr);
3932                 
3933                 // Dvi should also be kept dirty if the latex run
3934                 // ends up with errors. However it should be possible
3935                 // to view a dirty dvi too.
3936         } else {
3937                 //no errors or any other things to think about so:
3938                 users->owner()->getMiniBuffer()->Set(_("Done"));
3939                 markDviClean();
3940         }
3941
3942         // if we removed error insets before we ran LaTeX or if we inserted
3943         // error insets after we ran LaTeX this must be run:
3944         if (a || (res & Literate::ERRORS)){
3945                 users->redraw();
3946                 users->fitCursor();
3947                 users->updateScrollbar();
3948         }
3949         AllowInput();
3950  
3951         return literate.getNumErrors();
3952 }
3953
3954
3955 int Buffer::buildProgram()
3956 {
3957         if (!users->text) return 0;
3958  
3959         ProhibitInput();
3960  
3961         // get LaTeX-Filename
3962         string name = getLatexName();
3963         // get Literate-Filename
3964         string lit_name = ChangeExtension(getLatexName(), 
3965                                           lyxrc->literate_extension, true);
3966  
3967         string path = OnlyPath(filename);
3968  
3969         string org_path = path;
3970         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3971                 path = tmppath;  
3972         }
3973  
3974         Path p(path); // path to Literate file
3975         users->owner()->getMiniBuffer()->Set(_("Building Program..."));   
3976  
3977         // Remove all error insets
3978         bool a = users->removeAutoInsets();
3979  
3980         // generate the LaTeX file if necessary
3981         if (!isNwClean() || a) {
3982                 makeLaTeXFile(lit_name, org_path, false);
3983                 markNwDirty();
3984         }
3985
3986         string latex_command = lyxrc->pdf_mode ?
3987                 lyxrc->pdflatex_command : lyxrc->latex_command;
3988         Literate literate(latex_command, name, filepath, 
3989                           lit_name,
3990                           lyxrc->literate_command, lyxrc->literate_error_filter,
3991                           lyxrc->build_command, lyxrc->build_error_filter);
3992         TeXErrors terr;
3993         int res = literate.build(terr, users->owner()->getMiniBuffer());
3994  
3995         // check return value from literate.build().
3996         if ((res & Literate::NO_LOGFILE)) {
3997                 WriteAlert(_("Build did not work!"),
3998                            _("Missing log file:"), name);
3999         } else if ((res & Literate::ERRORS)) {
4000                 users->owner()->getMiniBuffer()->Set(_("Done"));
4001                 // Insert all errors as errors boxes
4002                 users->insertErrors(terr);
4003                 
4004                 // Literate files should also be kept dirty if the literate 
4005                 // command run ends up with errors.
4006         } else {
4007                 //no errors or any other things to think about so:
4008                 users->owner()->getMiniBuffer()->Set(_("Done"));
4009                 markNwClean();
4010         }
4011  
4012         // if we removed error insets before we ran Literate/Build or if we inserted
4013         // error insets after we ran Literate/Build this must be run:
4014         if (a || (res & Literate::ERRORS)){
4015                 users->redraw();
4016                 users->fitCursor();
4017                 users->updateScrollbar();
4018         }
4019         AllowInput();
4020
4021         return literate.getNumErrors();
4022 }
4023
4024
4025 // This should be enabled when the Chktex class is implemented. (Asger)
4026 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
4027 // Other flags: -wall -v0 -x
4028 int Buffer::runChktex()
4029 {
4030         if (!users->text) return 0;
4031
4032         ProhibitInput();
4033
4034         // get LaTeX-Filename
4035         string name = getLatexName();
4036         string path = OnlyPath(filename);
4037
4038         string org_path = path;
4039         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
4040                 path = tmppath;  
4041         }
4042
4043         Path p(path); // path to LaTeX file
4044         users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
4045
4046         // Remove all error insets
4047         bool a = users->removeAutoInsets();
4048
4049         // Generate the LaTeX file if neccessary
4050         if (!isDviClean() || a) {
4051                 makeLaTeXFile(name, org_path, false);
4052                 markDviDirty();
4053         }
4054
4055         TeXErrors terr;
4056         Chktex chktex(lyxrc->chktex_command, name, filepath);
4057         int res = chktex.run(terr); // run chktex
4058
4059         if (res == -1) {
4060                 WriteAlert(_("chktex did not work!"),
4061                            _("Could not run with file:"), name);
4062         } else if (res > 0) {
4063                 // Insert all errors as errors boxes
4064                 users->insertErrors(terr);
4065         }
4066
4067         // if we removed error insets before we ran chktex or if we inserted
4068         // error insets after we ran chktex, this must be run:
4069         if (a || res){
4070                 users->redraw();
4071                 users->fitCursor();
4072                 users->updateScrollbar();
4073         }
4074         AllowInput();
4075
4076         return res;
4077 }
4078
4079
4080 #if 0
4081 void Buffer::RoffAsciiTable(ostream & os, LyXParagraph * par)
4082 {
4083         LyXFont font1(LyXFont::ALL_INHERIT);
4084         LyXFont font2;
4085         Inset * inset;
4086         LyXParagraph::size_type i;
4087         int j, cell = 0;
4088         char c;
4089         
4090         string fname1 = TmpFileName(string(), "RAT1");
4091         string fname2 = TmpFileName(string(), "RAT2");
4092
4093         ofstream ofs(fname1.c_str());
4094         if (!ofs) {
4095                 WriteAlert(_("LYX_ERROR:"),
4096                            _("Cannot open temporary file:"), fname1);
4097                 return;
4098         }
4099         par->table->RoffEndOfCell(ofs, -1);
4100         for (i = 0; i < par->size(); ++i) {
4101                 c = par->GetChar(i);
4102                 if (par->table->IsContRow(cell)) {
4103                         if (c == LyXParagraph::META_NEWLINE)
4104                                 ++cell;
4105                         continue;
4106                 }
4107                 font2 = par->GetFontSettings(i);
4108                 if (font1.latex() != font2.latex()) {
4109                         if (font2.latex() != LyXFont::OFF)
4110                                 continue;
4111                 }
4112                 switch (c) {
4113                 case LyXParagraph::META_INSET:
4114                         if ((inset = par->GetInset(i))) {
4115 #if 1
4116 #ifdef HAVE_SSTREAM
4117                                 stringstresm ss(ios::in | ios::out);
4118                                 inset->Latex(ss, -1);
4119                                 ss.seekp(0);
4120                                 ss.get(c);
4121                                 while (!ss) {
4122                                         if (c == '\\')
4123                                                 ofs << "\\\\";
4124                                         else
4125                                                 ofs << c;
4126                                         ss.get(c);
4127                                 }
4128 #else
4129                                 strstream ss;
4130                                 inset->Latex(ss, -1);
4131                                 ss.seekp(0);
4132                                 ss.get(c);
4133                                 while (!ss) {
4134                                         if (c == '\\')
4135                                                 ofs << "\\\\";
4136                                         else
4137                                                 ofs << c;
4138                                         ss.get(c);
4139                                 }
4140                                 delete [] ss.str();
4141 #endif
4142 #else
4143                                 fstream fs(fname2.c_str(), ios::in|ios::out);
4144                                 if (!fs) {
4145                                         WriteAlert(_("LYX_ERROR:"),
4146                                                    _("Cannot open temporary file:"), fname2);
4147                                         ofs.close();
4148                                         remove(fname1.c_str());
4149                                         return;
4150                                 }
4151                                 inset->Latex(fs, -1);
4152                                 fs.seekp(0);
4153                                 fs.get(c);
4154                                 while(!fs) {
4155                                         if (c == '\\')
4156                                                 ofs << "\\\\";
4157                                         else
4158                                                 ofs << c;
4159                                         fs >> c;
4160                                 }
4161                                 fs.close();
4162 #endif
4163                         }
4164                         break;
4165                 case LyXParagraph::META_NEWLINE:
4166                         if (par->table->CellHasContRow(cell)>= 0)
4167                                 par->RoffContTableRows(ofs, i+1, cell);
4168                         par->table->RoffEndOfCell(ofs, cell);
4169                         ++cell;
4170                         break;
4171                 case LyXParagraph::META_HFILL: 
4172                         break;
4173 #if 0
4174                 case LyXParagraph::META_PROTECTED_SEPARATOR:
4175                         break;
4176 #endif
4177                 case '\\': 
4178                         ofs << "\\\\";
4179                         break;
4180                 default:
4181                         if (c != '\0')
4182                                 ofs << c;
4183                         else if (c == '\0')
4184                                 lyxerr.debug()
4185                                         << "RoffAsciiTable:"
4186                                         " NULL char in structure." << endl;
4187                         break;
4188                 }
4189         }
4190         par->table->RoffEndOfCell(ofs, cell);
4191         ofs.close();
4192         string cmd = lyxrc->ascii_roff_command + " >" + fname2;
4193         cmd = subst(cmd, "$$FName", fname1);
4194         Systemcalls one(Systemcalls::System, cmd);
4195         if (!(lyxerr.debugging(Debug::ROFF))) {
4196                 remove(fname1.c_str());
4197         }
4198         ifstream ifs(fname2.c_str());
4199         if (!ifs) {
4200                 WriteFSAlert(_("Error! Can't open temporary file:"), fname2);
4201                 return;
4202         }
4203         // now output the produced file
4204         os << "\n\n";
4205         ifs.get(c);
4206         if (!ifs)
4207                 WriteAlert(_("Error!"),
4208                            _("Error executing *roff command on table"));
4209         // overread leading blank lines
4210         while(!ifs && (c == '\n'))
4211                 ifs.get(c);
4212         while(!ifs) {
4213                 for(j = 0; j < par->depth; ++j)
4214                         os << "  ";
4215                 while(!ifs && (c != '\n')) {
4216                         os << c;
4217                         ifs.get(c);
4218                 }
4219                 os << '\n';
4220                 // overread trailing blank lines
4221                 while(!ifs && (c == '\n'))
4222                         ifs.get(c);
4223         }
4224         ifs.close();
4225         remove(fname2.c_str());
4226 }
4227 #endif
4228
4229         
4230 /// changed Heinrich Bauer, 23/03/98
4231 bool Buffer::isDviClean() const
4232 {
4233   if (lyxrc->use_tempdir)
4234     return dvi_clean_tmpd;
4235   else
4236     return dvi_clean_orgd;
4237 }
4238
4239  
4240 /// changed Heinrich Bauer, 23/03/98
4241 void Buffer::markDviClean()
4242 {
4243   if (lyxrc->use_tempdir)
4244     dvi_clean_tmpd = true;
4245   else
4246     dvi_clean_orgd = true;
4247 }
4248
4249
4250 /// changed Heinrich Bauer, 23/03/98
4251 void Buffer::markDviDirty()
4252 {
4253   if (lyxrc->use_tempdir)
4254     dvi_clean_tmpd = false;
4255   else
4256     dvi_clean_orgd = false;
4257 }
4258
4259
4260 void Buffer::validate(LaTeXFeatures & features) const
4261 {
4262         LyXParagraph * par = paragraph;
4263         LyXTextClass const & tclass = 
4264                 textclasslist.TextClass(params.textclass);
4265     
4266         // AMS Style is at document level
4267     
4268         features.amsstyle = (params.use_amsmath ||
4269                              tclass.provides(LyXTextClass::amsmath));
4270     
4271         while (par) {
4272                 // We don't use "lyxerr.debug" because of speed. (Asger)
4273                 if (lyxerr.debugging(Debug::LATEX))
4274                         lyxerr << "Paragraph: " <<  par << endl;
4275
4276                 // Now just follow the list of paragraphs and run
4277                 // validate on each of them.
4278                 par->validate(features);
4279
4280                 // and then the next paragraph
4281                 par = par->next;
4282         }
4283
4284         // the bullet shapes are buffer level not paragraph level
4285         // so they are tested here
4286         for (int i = 0; i < 4; ++i) {
4287                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
4288                         int font = params.user_defined_bullets[i].getFont();
4289                         if (font == 0) {
4290                                 int c = params
4291                                         .user_defined_bullets[i]
4292                                         .getCharacter();
4293                                 if (c == 16
4294                                    || c == 17
4295                                    || c == 25
4296                                    || c == 26
4297                                    || c == 31) {
4298                                         features.latexsym = true;
4299                                 }
4300                         }
4301                         if (font == 1) {
4302                                 features.amssymb = true;
4303                         }
4304                         else if ((font >= 2 && font <= 5)) {
4305                                 features.pifont = true;
4306                         }
4307                 }
4308         }
4309         
4310         if (lyxerr.debugging(Debug::LATEX)) {
4311                 features.showStruct(params);
4312         }
4313 }
4314
4315
4316 void Buffer::setPaperStuff()
4317 {
4318         params.papersize = BufferParams::PAPER_DEFAULT;
4319         char c1 = params.paperpackage;
4320         if (c1 == BufferParams::PACKAGE_NONE) {
4321                 char c2 = params.papersize2;
4322                 if (c2 == BufferParams::VM_PAPER_USLETTER)
4323                         params.papersize = BufferParams::PAPER_USLETTER;
4324                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
4325                         params.papersize = BufferParams::PAPER_LEGALPAPER;
4326                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
4327                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
4328                 else if (c2 == BufferParams::VM_PAPER_A3)
4329                         params.papersize = BufferParams::PAPER_A3PAPER;
4330                 else if (c2 == BufferParams::VM_PAPER_A4)
4331                         params.papersize = BufferParams::PAPER_A4PAPER;
4332                 else if (c2 == BufferParams::VM_PAPER_A5)
4333                         params.papersize = BufferParams::PAPER_A5PAPER;
4334                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
4335                          (c2 == BufferParams::VM_PAPER_B5))
4336                         params.papersize = BufferParams::PAPER_B5PAPER;
4337         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
4338                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
4339                 params.papersize = BufferParams::PAPER_A4PAPER;
4340 }
4341
4342
4343 // This function should be in Buffer because it's a buffer's property (ale)
4344 string Buffer::getIncludeonlyList(char delim)
4345 {
4346         string lst;
4347         LyXParagraph * par = paragraph;
4348         LyXParagraph::size_type pos;
4349         Inset * inset;
4350         while (par){
4351                 pos = -1;
4352                 while ((inset = par->ReturnNextInsetPointer(pos))){
4353                         if (inset->LyxCode() == Inset::INCLUDE_CODE) {
4354                                 InsetInclude * insetinc = 
4355                                         static_cast<InsetInclude*>(inset);
4356                                 if (insetinc->isInclude() 
4357                                     && insetinc->isNoLoad()) {
4358                                         if (!lst.empty())
4359                                                 lst += delim;
4360                                         lst += ChangeExtension(insetinc->getContents(), string(), true);
4361                                 }
4362                         }
4363                         ++pos;
4364                 } 
4365                 par = par->next;
4366         }
4367         lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
4368         return lst;
4369 }
4370
4371
4372 // This is also a buffer property (ale)
4373 string Buffer::getReferenceList(char delim)
4374 {
4375         /// if this is a child document and the parent is already loaded
4376         /// Use the parent's list instead  [ale990407]
4377         if (!params.parentname.empty()
4378             && bufferlist.exists(params.parentname)) {
4379                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
4380                 if (tmp)
4381                         return tmp->getReferenceList(delim);
4382         }
4383
4384         LyXParagraph * par = paragraph;
4385         LyXParagraph::size_type pos;
4386         Inset * inset;
4387         string lst;
4388         while (par) {
4389                 pos = -1;
4390                 while ((inset = par->ReturnNextInsetPointer(pos))){     
4391                         for (int i = 0; i < inset->GetNumberOfLabels(); ++i) {
4392                                 if (!lst.empty())
4393                                         lst += delim;
4394                                 lst += inset->getLabel(i);
4395                         }
4396                         ++pos;
4397                 }
4398                 par = par->next;
4399         }
4400         lyxerr.debug() << "References(" <<  lst << ")" << endl;
4401         return lst;
4402 }
4403
4404
4405 // This is also a buffer property (ale)
4406 string Buffer::getBibkeyList(char delim)
4407 {
4408         /// if this is a child document and the parent is already loaded
4409         /// Use the parent's list instead  [ale990412]
4410         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
4411                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
4412                 if (tmp)
4413                         return tmp->getBibkeyList(delim);
4414         }
4415
4416         string bibkeys;
4417         LyXParagraph * par = paragraph;
4418         while (par) {
4419                 if (par->bibkey) {
4420                         if (!bibkeys.empty())
4421                                 bibkeys += delim;
4422                         bibkeys += par->bibkey->getContents();
4423                 }
4424                 par = par->next;
4425         }
4426
4427         // Might be either using bibtex or a child has bibliography
4428         if (bibkeys.empty()) {
4429                 par = paragraph;
4430                 while (par) {
4431                         Inset * inset;
4432                         LyXParagraph::size_type pos = -1;
4433
4434                         // Search for Bibtex or Include inset
4435                         while ((inset = par->ReturnNextInsetPointer(pos))) {
4436                                 if (inset-> LyxCode() == Inset::BIBTEX_CODE) {
4437                                         if (!bibkeys.empty())
4438                                                 bibkeys += delim;
4439                                         bibkeys += static_cast<InsetBibtex*>(inset)->getKeys(delim);
4440                                 } else if (inset-> LyxCode() == Inset::INCLUDE_CODE) {
4441                                         string bk = static_cast<InsetInclude*>(inset)->getKeys(delim);
4442                                         if (!bk.empty()) {
4443                                                 if (!bibkeys.empty())
4444                                                         bibkeys += delim;
4445                                                 bibkeys += bk;
4446                                         }
4447                                 }
4448                                 ++pos;
4449                         }
4450                         par = par->next;
4451                 }
4452         }
4453  
4454         lyxerr.debug() << "Bibkeys(" << bibkeys << ")" << endl;
4455         return bibkeys;
4456 }
4457
4458
4459 bool Buffer::isDepClean(string const & name) const
4460 {
4461         DEPCLEAN * item = dep_clean;
4462         while (item && item->master != name)
4463                 item = item->next;
4464         if (!item) return true;
4465         return item->clean;
4466 }
4467
4468
4469 void Buffer::markDepClean(string const & name)
4470 {
4471         if (!dep_clean) {
4472                 dep_clean = new DEPCLEAN;
4473                 dep_clean->clean = true;
4474                 dep_clean->master = name;
4475                 dep_clean->next = 0;
4476         } else {
4477                 DEPCLEAN* item = dep_clean;
4478                 while (item && item->master != name)
4479                         item = item->next;
4480                 if (item) {
4481                         item->clean = true;
4482                 } else {
4483                         item = new DEPCLEAN;
4484                         item->clean = true;
4485                         item->master = name;
4486                         item->next = 0;;
4487                 }
4488         }
4489 }
4490
4491
4492 void Buffer::Dispatch(string const & command)
4493 {
4494         // Split command string into command and argument
4495         string cmd, line = frontStrip(command);
4496         string arg = strip(frontStrip(split(line, cmd, ' ')));
4497
4498         Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
4499 }
4500
4501
4502 void Buffer::Dispatch(int action, string const & argument)
4503 {
4504         switch (action) {
4505                 case LFUN_EXPORT: 
4506                         MenuExport(this, argument);
4507                         break;
4508
4509                 default:
4510                         lyxerr << "A truly unknown func!" << endl;
4511                 break;
4512
4513         } // end of switch
4514 }