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