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