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