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