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