]> git.lyx.org Git - features.git/blob - src/buffer.C
db7befb4fc01e357ec4081f01c0d9c38d33ea2df
[features.git] / src / buffer.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-1999 The LyX Team.
8  *
9  *           This file is Copyright 1996-1999
10  *           Lars Gullik Bjønnes
11  *
12  * ====================================================== 
13  */
14
15 // Change Log:
16 // =========== 
17 // 23/03/98   Heinrich Bauer (heinrich.bauer@t-mobil.de)
18 // Spots marked "changed Heinrich Bauer, 23/03/98" modified due to the
19 // following bug: dvi file export did not work after printing (or previewing)
20 // and vice versa as long as the same file was concerned. This happened
21 // every time the LyX-file was left unchanged between the two actions mentioned
22 // above.
23
24 #include <config.h>
25
26 #include <fstream>
27 #include <iomanip>
28 using std::ofstream;
29 using std::ifstream;
30 using std::fstream;
31 using std::ios;
32 using std::setw;
33
34
35 #include <cstdlib>
36 #include <unistd.h>
37
38 #ifdef __GNUG__
39 #pragma implementation "buffer.h"
40 #endif
41
42 #include "buffer.h"
43 #include "bufferlist.h"
44 #include "lyx_main.h"
45 #include "lyx_gui_misc.h"
46 #include "LyXAction.h"
47 #include "lyxrc.h"
48 #include "lyxlex.h"
49 #include "tex-strings.h"
50 #include "layout.h"
51 #include "lyx_cb.h"
52 #include "minibuffer.h"
53 #include "lyxfont.h"
54 #include "version.h"
55 #include "mathed/formulamacro.h"
56 #include "insets/lyxinset.h"
57 #include "insets/inseterror.h"
58 #include "insets/insetlabel.h"
59 #include "insets/insetref.h"
60 #include "insets/inseturl.h"
61 #include "insets/insetinfo.h"
62 #include "insets/insetquotes.h"
63 #if 0
64 #include "insets/insetlatex.h"
65 #endif
66 #include "insets/insetlatexaccent.h"
67 #include "insets/insetbib.h" 
68 #include "insets/insetindex.h" 
69 #include "insets/insetinclude.h"
70 #include "insets/insettoc.h"
71 #include "insets/insetlof.h"
72 #include "insets/insetlot.h"
73 #include "insets/insetloa.h"
74 #include "insets/insetparent.h"
75 #include "insets/insetspecialchar.h"
76 #include "insets/figinset.h"
77 #include "support/filetools.h"
78 #include "support/path.h"
79 #include "LaTeX.h"
80 #include "Literate.h"
81 #include "Chktex.h"
82 #include "LyXView.h"
83 #include "debug.h"
84 #include "LaTeXFeatures.h"
85 #include "support/syscall.h"
86 #include "support/lyxlib.h"
87 #include "support/FileInfo.h"
88 #include "lyxtext.h"
89 #include "gettext.h"
90
91 // Uncomment this line to enable a workaround for the weird behaviour
92 // of the cursor between a displayed inset and last character
93 // at the upper line. (Alejandro 20.9.96)
94 // #define BREAK_BEFORE_INSET
95
96 /* Lars, when changing this file sometime in the future to a list,
97  * please check out the figinsets-sideeffects described at the
98  * beginning of figinset.C    Matthias (04.07.1996)
99  */
100
101
102 // all these externs should eventually be removed.
103 extern BufferList bufferlist;
104 extern 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 fname = MakeAbsPath(filen);
234
235         // check if file exist
236         FileInfo fi(fname);
237
238         if (!fi.readable()) {
239                 WriteAlert(_("Error!"),
240                            _("Specified file is unreadable: "),
241                            MakeDisplayPath(fname, 50));
242                 return false;
243         }
244         
245         BeforeChange();
246
247         FilePtr myfile(fname, FilePtr::read);
248         if (!myfile()) {
249                 WriteAlert(_("Error!"),
250                            _("Cannot open specified file: "),
251                            MakeDisplayPath(fname, 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 & fname, 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 && (fname == 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                                << fname << endl;
1189                 else
1190                         WriteAlert(_("Error! Document is read-only: "),
1191                                    fname);
1192                 return false;
1193         }
1194
1195         FileInfo finfo(fname);
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                                << fname << endl;
1202                 else
1203                         WriteFSAlert(_("Error! Cannot write file: "),
1204                                      fname);
1205                 return false;
1206         }
1207
1208         ofstream ofs(fname.c_str());
1209         if (!ofs) {
1210                 if (flag)
1211                         lyxerr << _("Error! Cannot open file: ")
1212                                << fname << endl;
1213                 else
1214                         WriteFSAlert(_("Error! Cannot open file: "),
1215                                      fname);
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 & fname, 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(fname.c_str());
1259         if (!ofs) {
1260                 WriteFSAlert(_("Error: Cannot write file:"), fname);
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 & fname, 
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(fname.c_str());
1582         if (!ofs) {
1583                 WriteFSAlert(_("Error: Cannot open file: "), fname);
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 #if 0
2124         static char const * space[] = {
2125                 " ","  ", "   ", "    ", "     ", "      ",
2126                 "       ",
2127                 "        ", "         ", "          ",
2128                 "          "};
2129         os << space[depth] << "<" << latexname << ">\n";
2130 #endif
2131         os << string(depth, ' ') << "<" << latexname << ">\n";
2132 }
2133
2134
2135 void Buffer::sgmlCloseTag(ostream & os, int depth,
2136                           string const & latexname) const
2137 {
2138 #if 0
2139         static char * space[] = {" ", "  ", "   ", "    ", "     ",
2140                                  "      ", "       ", "        ",
2141                                  "         ", "          ", "          "};
2142
2143         os << space[depth] << "</" << latexname << ">\n";
2144 #endif
2145         os << string(depth, ' ') << "</" << latexname << ">\n";
2146 }
2147
2148
2149 void Buffer::makeLinuxDocFile(string const & fname, int column)
2150 {
2151         LyXParagraph * par = paragraph;
2152
2153         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2154         string environment_stack[10];
2155         string item_name;
2156
2157         int depth = 0;              /* paragraph depth */
2158
2159         ofstream ofs(fname.c_str());
2160
2161         if (!ofs) {
2162                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2163                 return;
2164         }
2165    
2166         tex_code_break_column = column; 
2167         texrow.reset();
2168    
2169         if (params.preamble.empty()) {
2170                 ofs << "<!doctype linuxdoc system>\n\n";
2171         }
2172         else {
2173                 ofs << "<!doctype linuxdoc system \n [ "
2174                     << params.preamble << " \n]>\n\n";
2175         }
2176
2177         string userName(getUserName());
2178         ofs << "<!-- LinuxDoc file was created by LyX 1.0 (C) 1995-1999 "
2179             << "by <" << userName << "> " << date() << " -->\n";
2180
2181         if(params.options.empty())
2182                 sgmlOpenTag(ofs, 0, top_element);
2183         else {
2184                 string top = top_element;
2185                 top += " ";
2186                 top += params.options;
2187                 sgmlOpenTag(ofs, 0, top);
2188         }
2189
2190         while (par) {
2191                 int desc_on = 0;            /* description mode*/
2192                 LyXLayout const & style =
2193                         textclasslist.Style(GetCurrentTextClass(),
2194                                             par->layout);
2195                 par->AutoDeleteInsets();
2196
2197                 /* treat <toc> as a special case for compatibility with old code */
2198                 if (par->GetChar(0) == LyXParagraph::META_INSET) {
2199                         Inset * inset = par->GetInset(0);
2200                         char  lyx_code = inset->LyxCode();
2201                         if (lyx_code == Inset::TOC_CODE){
2202                                 string temp = "toc";
2203                                 sgmlOpenTag(ofs, depth, temp);
2204
2205                                 par = par->next;
2206                                 linuxDocHandleFootnote(ofs, par, depth);
2207                                 continue;
2208                         }
2209                 }
2210
2211                 /* environment tag closing */
2212                 for( ; depth > par->depth; --depth) {
2213                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2214                         environment_stack[depth].clear();
2215                 }
2216
2217                 /* write opening SGML tags */
2218                 switch(style.latextype) {
2219                 case LATEX_PARAGRAPH:
2220                         if(depth == par->depth 
2221                            && !environment_stack[depth].empty()) {
2222                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2223                                 environment_stack[depth].clear();
2224                                 if(depth) 
2225                                         --depth;
2226                                 else
2227                                         ofs << "</p>";
2228                         }
2229                         sgmlOpenTag(ofs, depth, style.latexname());
2230                         break;
2231
2232                 case LATEX_COMMAND:
2233                         if (depth!= 0)
2234                                 LinuxDocError(par, 0, _("Error : Wrong depth for LatexType Command.\n"));
2235
2236                         if (!environment_stack[depth].empty()){
2237                                 sgmlCloseTag(ofs, depth,
2238                                              environment_stack[depth]);
2239                                 ofs << "</p>";
2240                         }
2241
2242                         environment_stack[depth].clear();
2243                         sgmlOpenTag(ofs, depth, style.latexname());
2244                         break;
2245
2246                 case LATEX_ENVIRONMENT:
2247                 case LATEX_ITEM_ENVIRONMENT:
2248                         if(depth == par->depth 
2249                            && environment_stack[depth] != style.latexname()
2250                            && !environment_stack[depth].empty()) {
2251
2252                                 sgmlCloseTag(ofs, depth,
2253                                              environment_stack[depth]);
2254                                 environment_stack[depth].clear();
2255                         }
2256                         if (depth < par->depth) {
2257                                depth = par->depth;
2258                                environment_stack[depth].clear();
2259                         }
2260                         if (environment_stack[depth] != style.latexname()) {
2261                                 if(depth == 0) {
2262                                         string temp = "p";
2263                                         sgmlOpenTag(ofs, depth, temp);
2264                                 }
2265                                 environment_stack[depth] = style.latexname();
2266                                 sgmlOpenTag(ofs, depth, environment_stack[depth]);
2267                         }
2268                         if(style.latextype == LATEX_ENVIRONMENT) break;
2269
2270                         desc_on = (style.labeltype == LABEL_MANUAL);
2271
2272                         if(desc_on)
2273                                 item_name = "tag";
2274                         else
2275                                 item_name = "item";
2276
2277                         sgmlOpenTag(ofs, depth + 1, item_name);
2278                         break;
2279                 default:
2280                         sgmlOpenTag(ofs, depth, style.latexname());
2281                         break;
2282                 }
2283
2284                 do {
2285                         SimpleLinuxDocOnePar(ofs, par, desc_on, depth);
2286
2287                         par = par->next;
2288                         linuxDocHandleFootnote(ofs, par, depth);
2289                 }
2290                 while(par && par->IsDummy());
2291
2292                 ofs << "\n";
2293                 /* write closing SGML tags */
2294                 switch(style.latextype) {
2295                 case LATEX_COMMAND:
2296                 case LATEX_ENVIRONMENT:
2297                 case LATEX_ITEM_ENVIRONMENT:
2298                         break;
2299                 default:
2300                         sgmlCloseTag(ofs, depth, style.latexname());
2301                         break;
2302                 }
2303         }
2304    
2305         /* Close open tags */
2306         for(; depth > 0; --depth)
2307                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2308
2309         if(!environment_stack[depth].empty())
2310                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2311
2312         ofs << "\n\n";
2313         sgmlCloseTag(ofs, 0, top_element);
2314
2315         ofs.close();
2316         // How to check for successful close
2317 }
2318
2319
2320 void Buffer::linuxDocHandleFootnote(ostream & os, LyXParagraph * & par,
2321                                     int const depth)
2322 {
2323         string tag = "footnote";
2324
2325         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2326                 sgmlOpenTag(os, depth + 1, tag);
2327                 SimpleLinuxDocOnePar(os, par, 0, depth + 1);
2328                 sgmlCloseTag(os, depth + 1, tag);
2329                 par = par->next;
2330         }
2331 }
2332
2333
2334 void Buffer::DocBookHandleCaption(ostream & os, string & inner_tag,
2335                                   int const depth, int desc_on,
2336                                   LyXParagraph * & par)
2337 {
2338         LyXParagraph * tpar = par;
2339         string tmp_par, extra_par;
2340         while (tpar && (tpar->footnoteflag != LyXParagraph::NO_FOOTNOTE) &&
2341                (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2342                                                              "Caption").second))
2343                 tpar = tpar->next;
2344         if (tpar &&
2345             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2346                                                          "Caption").second) {
2347                 sgmlOpenTag(os, depth + 1, inner_tag);
2348                 SimpleDocBookOnePar(tmp_par, extra_par, tpar,
2349                                     desc_on, depth + 2);
2350                 tmp_par = strip(tmp_par);
2351                 tmp_par = frontStrip(tmp_par);
2352                 os << tmp_par;
2353                 sgmlCloseTag(os, depth+1, inner_tag);
2354                 if(!extra_par.empty())
2355                         os << extra_par;
2356         }
2357 }
2358
2359
2360 void Buffer::DocBookHandleFootnote(ostream & os, LyXParagraph * & par,
2361                                    int const depth)
2362 {
2363         string tag, inner_tag;
2364         string tmp_par, extra_par;
2365         bool inner_span = false;
2366         int desc_on = 4;
2367
2368         // This is not how I like to see enums. They should not be anonymous
2369         // and variables of its type should not be declared right after the
2370         // last brace. (Lgb)
2371         enum {
2372                 NO_ONE,
2373                 FOOTNOTE_LIKE,
2374                 MARGIN_LIKE,
2375                 FIG_LIKE,
2376                 TAB_LIKE
2377         } last = NO_ONE, present = FOOTNOTE_LIKE;
2378
2379         while (par && par->footnoteflag != LyXParagraph::NO_FOOTNOTE) {
2380                 if(last == present) {
2381                         if(inner_span) {
2382                                 if(!tmp_par.empty()) {
2383                                         os << tmp_par;
2384                                         tmp_par.clear();
2385                                         sgmlCloseTag(os, depth+1, inner_tag);
2386                                         sgmlOpenTag(os, depth+1, inner_tag);
2387                                 }
2388                         }
2389                         else
2390                                 os << "\n";
2391                 } else {
2392                         os << tmp_par;
2393                         if(!inner_tag.empty()) sgmlCloseTag(os, depth+1, inner_tag);
2394                         if(!extra_par.empty()) os << extra_par;
2395                         if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2396                         extra_par.clear();
2397
2398                         switch (par->footnotekind) {
2399                         case LyXParagraph::FOOTNOTE:
2400                         case LyXParagraph::ALGORITHM:
2401                                 tag = "footnote";
2402                                 inner_tag = "para";
2403                                 present = FOOTNOTE_LIKE;
2404                                 inner_span = true;
2405                                 break;
2406                         case LyXParagraph::MARGIN:
2407                                 tag = "sidebar";
2408                                 inner_tag = "para";
2409                                 present = MARGIN_LIKE;
2410                                 inner_span = true;
2411                                 break;
2412                         case LyXParagraph::FIG:
2413                         case LyXParagraph::WIDE_FIG:
2414                                 tag = "figure";
2415                                 inner_tag = "title";
2416                                 present = FIG_LIKE;
2417                                 inner_span = false;
2418                                 break;
2419                         case LyXParagraph::TAB:
2420                         case LyXParagraph::WIDE_TAB:
2421                                 tag = "table";
2422                                 inner_tag = "title";
2423                                 present = TAB_LIKE;
2424                                 inner_span = false;
2425                                 break;
2426                         }
2427                         sgmlOpenTag(os, depth, tag);
2428                         if ((present == TAB_LIKE) || (present == FIG_LIKE)) {
2429                                 DocBookHandleCaption(os, inner_tag, depth,
2430                                                      desc_on, par);
2431                                 inner_tag.clear();
2432                         } else {
2433                                 sgmlOpenTag(os, depth + 1, inner_tag);
2434                         }
2435                 }
2436                 // ignore all caption here, we processed them above!!!
2437                 if (par->layout != textclasslist.NumberOfLayout(params.textclass,
2438                                                            "Caption").second) {
2439                         SimpleDocBookOnePar(tmp_par, extra_par, par,
2440                                             desc_on, depth + 2);
2441                 }
2442                 tmp_par = frontStrip(strip(tmp_par));
2443
2444                 last = present;
2445                 par = par->next;
2446         }
2447         os << tmp_par;
2448         if(!inner_tag.empty()) sgmlCloseTag(os, depth+1, inner_tag);
2449         if(!extra_par.empty()) os << extra_par;
2450         if(!tag.empty()) sgmlCloseTag(os, depth, tag);
2451 }
2452
2453
2454 /* push a tag in a style stack */
2455 void Buffer::push_tag(ostream & os, char const * tag,
2456                       int & pos, char stack[5][3])
2457 {
2458         int j;
2459
2460         /* pop all previous tags */
2461         for (j = pos; j >= 0; --j)
2462                 os << "</" << stack[j] << ">";
2463
2464         /* add new tag */
2465         sprintf(stack[++pos], "%s", tag);
2466
2467         /* push all tags */
2468         for (j = 0; j <= pos; ++j)
2469                 os << "<" << stack[j] << ">";
2470 }
2471
2472
2473 // pop a tag from a style stack
2474 void Buffer::pop_tag(ostream & os, char const * tag,
2475                      int & pos, char stack[5][3])
2476 {
2477         int j;
2478
2479         // pop all tags till specified one
2480         for (j = pos; (j >= 0) && (strcmp(stack[j], tag)); --j)
2481                 os << "</" << stack[j] << ">";
2482
2483         // closes the tag
2484         os << "</" << tag << ">";
2485
2486         // push all tags, but the specified one
2487         for (j = j + 1; j <= pos; ++j) {
2488                 os << "<" << stack[j] << ">";
2489                 strcpy(stack[j-1], stack[j]);
2490         }
2491         --pos;
2492 }
2493
2494
2495 /* handle internal paragraph parsing -- layout already processed */
2496
2497 // checks, if newcol chars should be put into this line
2498 // writes newline, if necessary.
2499 static
2500 void linux_doc_line_break(ostream & os, unsigned int & colcount,
2501                           const unsigned int newcol)
2502 {
2503         colcount += newcol;
2504         if (colcount > lyxrc->ascii_linelen) {
2505                 os << "\n";
2506                 colcount = newcol; // assume write after this call
2507         }
2508 }
2509
2510
2511 void Buffer::SimpleLinuxDocOnePar(ostream & os, LyXParagraph * par,
2512                                   int desc_on, int const /*depth*/)
2513 {
2514         LyXFont font1, font2;
2515         char c;
2516         Inset * inset;
2517         LyXParagraph::size_type main_body;
2518         int j;
2519         LyXLayout const & style = textclasslist.Style(params.textclass,
2520                                                       par->GetLayout());
2521
2522         char family_type = 0;               // family font flag 
2523         bool is_bold     = false;           // series font flag 
2524         char shape_type  = 0;               // shape font flag 
2525         bool is_em = false;                 // emphasis (italic) font flag 
2526
2527         int stack_num = -1;          // style stack position 
2528         char stack[5][3];            // style stack 
2529         unsigned int char_line_count = 5;     // Heuristic choice ;-) 
2530
2531         if (style.labeltype != LABEL_MANUAL)
2532                 main_body = 0;
2533         else
2534                 main_body = par->BeginningOfMainBody();
2535
2536         /* gets paragraph main font */
2537         if (main_body > 0)
2538                 font1 = style.labelfont;
2539         else
2540                 font1 = style.font;
2541
2542   
2543         /* parsing main loop */
2544         for (LyXParagraph::size_type i = 0;
2545              i < par->size(); ++i) {
2546
2547                 /* handle quote tag */
2548                 if (i == main_body && !par->IsDummy()) {
2549                         if (main_body > 0)
2550                                 font1 = style.font;
2551                 }
2552
2553                 font2 = par->getFont(i);
2554
2555                 if (font1.family() != font2.family()) {
2556                         switch(family_type) {
2557                         case 0:
2558                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2559                                         push_tag(os, "tt", stack_num, stack);
2560                                         family_type= 1;
2561                                 }
2562                                 else if (font2.family() == LyXFont::SANS_FAMILY) {
2563                                         push_tag(os, "sf", stack_num, stack);
2564                                         family_type= 2;
2565                                 }
2566                                 break;
2567                         case 1:
2568                                 pop_tag(os, "tt", stack_num, stack);
2569                                 if (font2.family() == LyXFont::SANS_FAMILY) {
2570                                         push_tag(os, "sf", stack_num, stack);
2571                                         family_type= 2;
2572                                 }
2573                                 else {
2574                                         family_type= 0;
2575                                 }
2576                                 break;
2577                         case 2:
2578                                 pop_tag(os, "sf", stack_num, stack);
2579                                 if (font2.family() == LyXFont::TYPEWRITER_FAMILY) {
2580                                         push_tag(os, "tt", stack_num, stack);
2581                                         family_type= 1;
2582                                 }
2583                                 else {
2584                                         family_type= 0;
2585                                 }
2586                         }
2587                 }
2588
2589                 /* handle bold face */
2590                 if (font1.series() != font2.series()) {
2591                         if (font2.series() == LyXFont::BOLD_SERIES) {
2592                                 push_tag(os, "bf", stack_num, stack);
2593                                 is_bold = true;
2594                         }
2595                         else if (is_bold) {
2596                                 pop_tag(os, "bf", stack_num, stack);
2597                                 is_bold = false;
2598                         }
2599                 }
2600
2601                 /* handle italic and slanted fonts */
2602                 if (font1.shape() != font2.shape()) {
2603                         switch(shape_type) {
2604                         case 0:
2605                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2606                                         push_tag(os, "it", stack_num, stack);
2607                                         shape_type= 1;
2608                                 }
2609                                 else if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2610                                         push_tag(os, "sl", stack_num, stack);
2611                                         shape_type= 2;
2612                                 }
2613                                 break;
2614                         case 1:
2615                                 pop_tag(os, "it", stack_num, stack);
2616                                 if (font2.shape() == LyXFont::SLANTED_SHAPE) {
2617                                         push_tag(os, "sl", stack_num, stack);
2618                                         shape_type= 2;
2619                                 }
2620                                 else {
2621                                         shape_type= 0;
2622                                 }
2623                                 break;
2624                         case 2:
2625                                 pop_tag(os, "sl", stack_num, stack);
2626                                 if (font2.shape() == LyXFont::ITALIC_SHAPE) {
2627                                         push_tag(os, "it", stack_num, stack);
2628                                         shape_type= 1;
2629                                 }
2630                                 else {
2631                                         shape_type= 0;
2632                                 }
2633                         }
2634                 }
2635                 /* handle <em> tag */
2636                 if (font1.emph() != font2.emph()) {
2637                         if (font2.emph() == LyXFont::ON) {
2638                                 push_tag(os, "em", stack_num, stack);
2639                                 is_em = true;
2640                         } else if (is_em) {
2641                                 pop_tag(os, "em", stack_num, stack);
2642                                 is_em = false;
2643                         }
2644                 }
2645
2646                 c = par->GetChar(i);
2647       
2648                 if (font2.latex() == LyXFont::ON) {
2649                         // "TeX"-Mode on == > SGML-Mode on.
2650                         if (c!= '\0')
2651                                 os << c; // see LaTeX-Generation...
2652                         char_line_count++;
2653                 } else if (c == LyXParagraph::META_INSET) {
2654                         inset = par->GetInset(i);
2655                         string tmp_out;
2656                         inset->Linuxdoc(tmp_out);
2657                         os << tmp_out;
2658                 }
2659                 else {
2660                         string sgml_string;
2661                         if (par->linuxDocConvertChar(c, sgml_string)
2662                             && !style.free_spacing) { // in freespacing
2663                                                      // mode, spaces are
2664                                                      // non-breaking characters
2665                                 // char is ' '
2666                                 if (desc_on == 1) {
2667                                         char_line_count++;
2668                                         linux_doc_line_break(os, char_line_count, 6);
2669                                         os << "</tag>";
2670                                         desc_on = 2;
2671                                 }
2672                                 else  {
2673                                         linux_doc_line_break(os, char_line_count, 1);
2674                                         os << c;
2675                                 }
2676                         }
2677                         else {
2678                                 os << sgml_string;
2679                                 char_line_count += sgml_string.length();
2680                         }
2681                 }
2682                 font1 = font2;
2683         }
2684
2685         /* needed if there is an optional argument but no contents */
2686         if (main_body > 0 && main_body == par->size()) {
2687                 font1 = style.font;
2688         }
2689
2690         /* pop all defined Styles */
2691         for (j = stack_num; j >= 0; --j) {
2692                 linux_doc_line_break(os, 
2693                                      char_line_count, 
2694                                      3 + strlen(stack[j]));
2695                 os << "</" << stack[j] << ">";
2696         }
2697
2698         /* resets description flag correctly */
2699         switch(desc_on){
2700         case 1:
2701                 /* <tag> not closed... */
2702                 linux_doc_line_break(os, char_line_count, 6);
2703                 os << "</tag>";
2704                 break;
2705         case 2:
2706                 /* fprintf(file, "</p>");*/
2707                 break;
2708         }
2709 }
2710
2711
2712 /* print an error message */
2713 void Buffer::LinuxDocError(LyXParagraph * par, int pos,
2714                            char const * message) 
2715 {
2716         InsetError * new_inset;
2717
2718         /* insert an error marker in text */
2719         new_inset = new InsetError(message);
2720         par->InsertChar(pos, LyXParagraph::META_INSET);
2721         par->InsertInset(pos, new_inset);
2722 }
2723
2724 // This constant defines the maximum number of 
2725 // environment layouts that can be nesteded.
2726 // The same applies for command layouts.
2727 // These values should be more than enough.
2728 //           José Matos (1999/07/22)
2729
2730 enum { MAX_NEST_LEVEL = 25};
2731
2732 void Buffer::makeDocBookFile(string const & fname, int column)
2733 {
2734         LyXParagraph * par = paragraph;
2735
2736         string top_element= textclasslist.LatexnameOfClass(params.textclass);
2737         string environment_stack[MAX_NEST_LEVEL];
2738         string environment_inner[MAX_NEST_LEVEL];
2739         string command_stack[MAX_NEST_LEVEL];
2740         bool command_flag= false;
2741         int command_depth= 0, command_base= 0, cmd_depth= 0;
2742
2743         string item_name, command_name;
2744         string c_depth, c_params, tmps;
2745
2746         int depth= 0;              /* paragraph depth */
2747
2748         tex_code_break_column = column; 
2749
2750         ofstream ofs(fname.c_str());
2751         if (!ofs) {
2752                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2753                 return;
2754         }
2755    
2756         //ResetTexRow();
2757         texrow.reset();
2758
2759         ofs << "<!doctype " << top_element
2760             << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
2761
2762         if (params.preamble.empty())
2763                 ofs << ">\n\n";
2764         else
2765                 ofs << "\n [ " << params.preamble << " \n]>\n\n";
2766
2767         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
2768             << "\n  See http://www.lyx.org/ for more information -->\n";
2769
2770         if(params.options.empty())
2771                 sgmlOpenTag(ofs, 0, top_element);
2772         else {
2773                 string top = top_element;
2774                 top += " ";
2775                 top += params.options;
2776                 sgmlOpenTag(ofs, 0, top);
2777         }
2778
2779         while (par) {
2780                 int desc_on= 0;            /* description mode*/
2781                 LyXLayout const & style = textclasslist.Style(GetCurrentTextClass(),
2782                                                    par->layout);
2783                 par->AutoDeleteInsets();
2784
2785                 /* environment tag closing */
2786                 for( ; depth > par->depth; --depth) {
2787                         if(environment_inner[depth] != "!-- --") {
2788                                 item_name= "listitem";
2789                                 sgmlCloseTag(ofs, command_depth + depth,
2790                                              item_name);
2791                                 if( environment_inner[depth] == "varlistentry")
2792                                         sgmlCloseTag(ofs, depth+command_depth,
2793                                                      environment_inner[depth]);
2794                         }
2795                         sgmlCloseTag(ofs, depth + command_depth,
2796                                      environment_stack[depth]);
2797                         environment_stack[depth].clear();
2798                         environment_inner[depth].clear();
2799                 }
2800
2801                 if(depth == par->depth
2802                    && environment_stack[depth] != style.latexname()
2803                    && !environment_stack[depth].empty()) {
2804                         if(environment_inner[depth] != "!-- --") {
2805                                 item_name= "listitem";
2806                                 sgmlCloseTag(ofs, command_depth+depth,
2807                                              item_name);
2808                                 if( environment_inner[depth] == "varlistentry")
2809                                         sgmlCloseTag(ofs,
2810                                                      depth + command_depth,
2811                                                      environment_inner[depth]);
2812                         }
2813                         
2814                         sgmlCloseTag(ofs, depth + command_depth,
2815                                      environment_stack[depth]);
2816                         
2817                         environment_stack[depth].clear();
2818                         environment_inner[depth].clear();
2819                 }
2820
2821                 // Write opening SGML tags.
2822                 switch(style.latextype) {
2823                 case LATEX_PARAGRAPH:
2824                         if(style.latexname() != "dummy")
2825                                sgmlOpenTag(ofs, depth+command_depth,
2826                                            style.latexname());
2827                         break;
2828
2829                 case LATEX_COMMAND:
2830                         if (depth!= 0)
2831                                 LinuxDocError(par, 0,
2832                                               _("Error : Wrong depth for "
2833                                                 "LatexType Command.\n"));
2834                         
2835                         command_name = style.latexname();
2836                         
2837                         tmps = style.latexparam();
2838                         c_params = split(tmps, c_depth,'|');
2839                         
2840                         cmd_depth= atoi(c_depth.c_str());
2841                         
2842                         if(command_flag) {
2843                                 if(cmd_depth<command_base) {
2844                                         for(int j = command_depth;
2845                                             j >= command_base; --j)
2846                                                 if(!command_stack[j].empty())
2847                                                         sgmlCloseTag(ofs, j, command_stack[j]);
2848                                         command_depth= command_base= cmd_depth;
2849                                 }
2850                                 else if(cmd_depth <= command_depth) {
2851                                         for(int j = command_depth;
2852                                             j >= cmd_depth; --j)
2853
2854                                                 if(!command_stack[j].empty())
2855                                                         sgmlCloseTag(ofs, j, command_stack[j]);
2856                                         command_depth= cmd_depth;
2857                                 }
2858                                 else
2859                                         command_depth= cmd_depth;
2860                         }
2861                         else {
2862                                 command_depth = command_base = cmd_depth;
2863                                 command_flag = true;
2864                         }
2865                         command_stack[command_depth]= command_name;
2866
2867                         // treat label as a special case for
2868                         // more WYSIWYM handling.
2869                         if (par->GetChar(0) == LyXParagraph::META_INSET) {
2870                                 Inset * inset = par->GetInset(0);
2871                                 char  lyx_code = inset->LyxCode();
2872                                 if (lyx_code == Inset::LABEL_CODE){
2873                                         command_name += " id=\"";
2874                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
2875                                         command_name += "\"";
2876                                         desc_on = 3;
2877                                 }
2878                         }
2879
2880                         sgmlOpenTag(ofs, depth+command_depth, command_name);
2881                         item_name = "title";
2882                         sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
2883                         break;
2884
2885                 case LATEX_ENVIRONMENT:
2886                 case LATEX_ITEM_ENVIRONMENT:
2887                         if (depth < par->depth) {
2888                                 depth = par->depth;
2889                                 environment_stack[depth].clear();
2890                         }
2891
2892                         if (environment_stack[depth] != style.latexname()) {
2893                                 environment_stack[depth] = style.latexname();
2894                                 environment_inner[depth] = "!-- --";
2895                                 sgmlOpenTag(ofs, depth + command_depth,
2896                                             environment_stack[depth]);
2897                         } else {
2898                                 if(environment_inner[depth] != "!-- --") {
2899                                         item_name= "listitem";
2900                                         sgmlCloseTag(ofs,
2901                                                      command_depth + depth,
2902                                                      item_name);
2903                                         if (environment_inner[depth] == "varlistentry")
2904                                                 sgmlCloseTag(ofs,
2905                                                              depth + command_depth,
2906                                                              environment_inner[depth]);
2907                                 }
2908                         }
2909                         
2910                         if(style.latextype == LATEX_ENVIRONMENT) {
2911                                 if(!style.latexparam().empty())
2912                                         sgmlOpenTag(ofs, depth + command_depth,
2913                                                     style.latexparam());
2914                                 break;
2915                         }
2916
2917                         desc_on = (style.labeltype == LABEL_MANUAL);
2918
2919                         if(desc_on)
2920                                 environment_inner[depth]= "varlistentry";
2921                         else
2922                                 environment_inner[depth]= "listitem";
2923
2924                         sgmlOpenTag(ofs, depth + 1 + command_depth,
2925                                     environment_inner[depth]);
2926
2927                         if(desc_on) {
2928                                 item_name= "term";
2929                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
2930                                             item_name);
2931                         }
2932                         else {
2933                                 item_name= "para";
2934                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
2935                                             item_name);
2936                         }
2937                         break;
2938                 default:
2939                         sgmlOpenTag(ofs, depth + command_depth,
2940                                     style.latexname());
2941                         break;
2942                 }
2943
2944                 do {
2945                         string tmp_par, extra_par;
2946
2947                         SimpleDocBookOnePar(tmp_par, extra_par, par, desc_on,
2948                                             depth + 1 + command_depth);
2949                         ofs << tmp_par;
2950
2951                         par = par->next;
2952                         DocBookHandleFootnote(ofs, par,
2953                                               depth + 1 + command_depth);
2954                 }
2955                 while(par && par->IsDummy());
2956
2957                 string end_tag;
2958                 /* write closing SGML tags */
2959                 switch(style.latextype) {
2960                 case LATEX_COMMAND:
2961                         end_tag = "title";
2962                         sgmlCloseTag(ofs, depth + command_depth, end_tag);
2963                         break;
2964                 case LATEX_ENVIRONMENT:
2965                         if(!style.latexparam().empty())
2966                                 sgmlCloseTag(ofs, depth + command_depth,
2967                                              style.latexparam());
2968                         break;
2969                 case LATEX_ITEM_ENVIRONMENT:
2970                         if(desc_on == 1) break;
2971                         end_tag= "para";
2972                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
2973                         break;
2974                 case LATEX_PARAGRAPH:
2975                         if(style.latexname() != "dummy")
2976                                 sgmlCloseTag(ofs, depth + command_depth,
2977                                              style.latexname());
2978                         break;
2979                 default:
2980                         sgmlCloseTag(ofs, depth + command_depth,
2981                                      style.latexname());
2982                         break;
2983                 }
2984         }
2985
2986         // Close open tags
2987         for(; depth >= 0; --depth) {
2988                 if(!environment_stack[depth].empty()) {
2989                         if(environment_inner[depth] != "!-- --") {
2990                                 item_name= "listitem";
2991                                 sgmlCloseTag(ofs, command_depth + depth,
2992                                              item_name);
2993                                if( environment_inner[depth] == "varlistentry")
2994                                        sgmlCloseTag(ofs, depth + command_depth,
2995                                                     environment_inner[depth]);
2996                         }
2997                         
2998                         sgmlCloseTag(ofs, depth + command_depth,
2999                                      environment_stack[depth]);
3000                 }
3001         }
3002         
3003         for(int j = command_depth; j >= command_base; --j)
3004                 if(!command_stack[j].empty())
3005                         sgmlCloseTag(ofs, j, command_stack[j]);
3006
3007         ofs << "\n\n";
3008         sgmlCloseTag(ofs, 0, top_element);
3009
3010         ofs.close();
3011         // How to check for successful close
3012 }
3013
3014
3015 void Buffer::SimpleDocBookOnePar(string & file, string & extra,
3016                                  LyXParagraph * par, int & desc_on,
3017                                  int const depth) 
3018 {
3019         if (par->table) {
3020                 par->SimpleDocBookOneTablePar(file, extra, desc_on, depth);
3021                 return;
3022         }
3023         LyXFont font1, font2;
3024         char c;
3025         Inset *inset;
3026         LyXParagraph::size_type main_body;
3027         int j;
3028         string emph= "emphasis";
3029         bool emph_flag= false;
3030         int char_line_count= 0;
3031
3032         LyXLayout const & style = textclasslist.Style(params.textclass,
3033                                                       par->GetLayout());
3034
3035         if (style.labeltype != LABEL_MANUAL)
3036                 main_body = 0;
3037         else
3038                 main_body = par->BeginningOfMainBody();
3039
3040         /* gets paragraph main font */
3041         if (main_body > 0)
3042                 font1 = style.labelfont;
3043         else
3044                 font1 = style.font;
3045
3046         char_line_count = depth;
3047         if(!style.free_spacing)
3048                 for (j= 0;j< depth;j++)
3049                         file += ' ';
3050
3051         /* parsing main loop */
3052         for (LyXParagraph::size_type i = 0;
3053              i < par->size(); ++i) {
3054                 font2 = par->getFont(i);
3055
3056                 /* handle <emphasis> tag */
3057                 if (font1.emph() != font2.emph() && i) {
3058                         if (font2.emph() == LyXFont::ON) {
3059                                 file += "<emphasis>";
3060                                 emph_flag= true;
3061                         }else {
3062                                 file += "</emphasis>";
3063                                 emph_flag= false;
3064                         }
3065                 }
3066       
3067                 c = par->GetChar(i);
3068
3069                 if (c == LyXParagraph::META_INSET) {
3070                         inset = par->GetInset(i);
3071                         string tmp_out;
3072                         inset->DocBook(tmp_out);
3073                         //
3074                         // This code needs some explanation:
3075                         // Two insets are treated specially
3076                         //   label if it is the first element in a command paragraph
3077                         //         desc_on == 3
3078                         //   graphics inside tables or figure floats can't go on
3079                         //   title (the equivalente in latex for this case is caption
3080                         //   and title should come first
3081                         //         desc_on == 4
3082                         //
3083                         if(desc_on!= 3 || i!= 0) {
3084                                 if(!tmp_out.empty() && tmp_out[0] == '@') {
3085                                         if(desc_on == 4)
3086                                                 extra += frontStrip(tmp_out, '@');
3087                                         else
3088                                                 file += frontStrip(tmp_out, '@');
3089                                 }
3090                                 else
3091                                         file += tmp_out;
3092                         }
3093                 } else if (font2.latex() == LyXFont::ON) {
3094                         // "TeX"-Mode on ==> SGML-Mode on.
3095                         if (c!= '\0')
3096                                 file += c;
3097                         char_line_count++;
3098                 }
3099                 else {
3100                         string sgml_string;
3101                         if (par->linuxDocConvertChar(c, sgml_string)
3102                             && !style.free_spacing) { // in freespacing
3103                                                      // mode, spaces are
3104                                                      // non-breaking characters
3105                                 // char is ' '
3106                                 if (desc_on == 1) {
3107                                         char_line_count++;
3108                                         file += '\n';
3109                                         file += "</term><listitem><para>";
3110                                         desc_on = 2;
3111                                 }
3112                                 else  {
3113                                         file += c;
3114                                 }
3115                         }
3116                         else {
3117                                 file += sgml_string;
3118                         }
3119                 }
3120                 font1 = font2;
3121         }
3122
3123         /* needed if there is an optional argument but no contents */
3124         if (main_body > 0 && main_body == par->size()) {
3125                 font1 = style.font;
3126         }
3127         if (emph_flag) {
3128                 file += "</emphasis>";
3129         }
3130         
3131         /* resets description flag correctly */
3132         switch(desc_on){
3133         case 1:
3134                 /* <term> not closed... */
3135                 file += "</term>";
3136                 break;
3137         }
3138         file += '\n';
3139 }
3140
3141
3142 // candidate for move to BufferView
3143 bool Buffer::removeAutoInsets()
3144 {
3145         LyXParagraph * par = paragraph;
3146
3147         LyXCursor cursor = users->text->cursor;
3148         LyXCursor tmpcursor = cursor;
3149         cursor.par = tmpcursor.par->ParFromPos(tmpcursor.pos);
3150         cursor.pos = tmpcursor.par->PositionInParFromPos(tmpcursor.pos);
3151
3152         bool a = false;
3153         while (par) {
3154                 if (par->AutoDeleteInsets()){
3155                         a = true;
3156                         if (par->footnoteflag != LyXParagraph::CLOSED_FOOTNOTE){
3157                                 /* this is possible now, since SetCursor takes
3158                                    care about footnotes */
3159                                 users->text->SetCursorIntern(par, 0);
3160                                 users->text->RedoParagraphs(users->text->cursor, users->text->cursor.par->Next());
3161                                 users->text->FullRebreak();
3162                         }
3163                 }
3164                 par = par->next;
3165         }
3166         /* avoid forbidden cursor positions caused by error removing */ 
3167         if (cursor.pos > cursor.par->Last())
3168                 cursor.pos = cursor.par->Last();
3169         users->text->SetCursorIntern(cursor.par, cursor.pos);
3170
3171         return a;
3172 }
3173
3174
3175 int Buffer::runLaTeX()
3176 {
3177         if (!users->text) return 0;
3178
3179         ProhibitInput();
3180
3181         // get LaTeX-Filename
3182         string name = getLatexName();
3183
3184         string path = OnlyPath(filename);
3185
3186         string org_path = path;
3187         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3188                 path = tmppath;  
3189         }
3190
3191         Path p(path); // path to LaTeX file
3192         users->owner()->getMiniBuffer()->Set(_("Running LaTeX..."));   
3193
3194         // Remove all error insets
3195         bool a = removeAutoInsets();
3196
3197         // Always generate the LaTeX file
3198         makeLaTeXFile(name, org_path, false);
3199         markDviDirty();
3200
3201         // do the LaTex run(s)
3202         TeXErrors terr;
3203         LaTeX latex(lyxrc->latex_command, name, filepath);
3204         int res = latex.run(terr,
3205                             users->owner()->getMiniBuffer()); // running latex
3206
3207         // check return value from latex.run().
3208         if ((res & LaTeX::NO_LOGFILE)) {
3209                 WriteAlert(_("LaTeX did not work!"),
3210                            _("Missing log file:"), name);
3211         } else if ((res & LaTeX::ERRORS)) {
3212                 users->owner()->getMiniBuffer()->Set(_("Done"));
3213                 // Insert all errors as errors boxes
3214                 insertErrors(terr);
3215                 
3216                 // Dvi should also be kept dirty if the latex run
3217                 // ends up with errors. However it should be possible
3218                 // to view a dirty dvi too.
3219         } else {
3220                 //no errors or any other things to think about so:
3221                 users->owner()->getMiniBuffer()->Set(_("Done"));
3222                 markDviClean();
3223         }
3224
3225         // if we removed error insets before we ran LaTeX or if we inserted
3226         // error insets after we ran LaTeX this must be run:
3227         if (a || (res & LaTeX::ERRORS)){
3228                 users->redraw();
3229                 users->fitCursor();
3230                 users->updateScrollbar();
3231         }
3232         AllowInput();
3233  
3234         return latex.getNumErrors();
3235 }
3236
3237
3238 int Buffer::runLiterate()
3239 {
3240         if (!users->text) return 0;
3241
3242         ProhibitInput();
3243
3244         // get LaTeX-Filename
3245         string name = getLatexName();
3246         // get Literate-Filename
3247         string lit_name = ChangeExtension (getLatexName(), 
3248                                            lyxrc->literate_extension, true);
3249
3250         string path = OnlyPath(filename);
3251
3252         string org_path = path;
3253         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3254                 path = tmppath;  
3255         }
3256
3257         Path p(path); // path to Literate file
3258         users->owner()->getMiniBuffer()->Set(_("Running Literate..."));   
3259
3260         // Remove all error insets
3261         bool a = removeAutoInsets();
3262
3263         // generate the Literate file if necessary
3264         if (!isDviClean() || a) {
3265                 makeLaTeXFile(lit_name, org_path, false);
3266                 markDviDirty();
3267         }
3268
3269         Literate literate(lyxrc->latex_command, name, filepath, 
3270                           lit_name,
3271                           lyxrc->literate_command, lyxrc->literate_error_filter,
3272                           lyxrc->build_command, lyxrc->build_error_filter);
3273         TeXErrors terr;
3274         int res = literate.weave(terr, users->owner()->getMiniBuffer());
3275
3276         // check return value from literate.weave().
3277         if ((res & Literate::NO_LOGFILE)) {
3278                 WriteAlert(_("Literate command did not work!"),
3279                            _("Missing log file:"), name);
3280         } else if ((res & Literate::ERRORS)) {
3281                 users->owner()->getMiniBuffer()->Set(_("Done"));
3282                 // Insert all errors as errors boxes
3283                 insertErrors(terr);
3284                 
3285                 // Dvi should also be kept dirty if the latex run
3286                 // ends up with errors. However it should be possible
3287                 // to view a dirty dvi too.
3288         } else {
3289                 //no errors or any other things to think about so:
3290                 users->owner()->getMiniBuffer()->Set(_("Done"));
3291                 markDviClean();
3292         }
3293
3294         // if we removed error insets before we ran LaTeX or if we inserted
3295         // error insets after we ran LaTeX this must be run:
3296         if (a || (res & Literate::ERRORS)){
3297                 users->redraw();
3298                 users->fitCursor();
3299                 users->updateScrollbar();
3300         }
3301         AllowInput();
3302  
3303         return literate.getNumErrors();
3304 }
3305
3306
3307 int Buffer::buildProgram()
3308 {
3309         if (!users->text) return 0;
3310  
3311         ProhibitInput();
3312  
3313         // get LaTeX-Filename
3314         string name = getLatexName();
3315         // get Literate-Filename
3316         string lit_name = ChangeExtension(getLatexName(), 
3317                                           lyxrc->literate_extension, true);
3318  
3319         string path = OnlyPath(filename);
3320  
3321         string org_path = path;
3322         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3323                 path = tmppath;  
3324         }
3325  
3326         Path p(path); // path to Literate file
3327         users->owner()->getMiniBuffer()->Set(_("Building Program..."));   
3328  
3329         // Remove all error insets
3330         bool a = removeAutoInsets();
3331  
3332         // generate the LaTeX file if necessary
3333         if (!isNwClean() || a) {
3334                 makeLaTeXFile(lit_name, org_path, false);
3335                 markNwDirty();
3336         }
3337  
3338         Literate literate(lyxrc->latex_command, name, filepath, 
3339                           lit_name,
3340                           lyxrc->literate_command, lyxrc->literate_error_filter,
3341                           lyxrc->build_command, lyxrc->build_error_filter);
3342         TeXErrors terr;
3343         int res = literate.build(terr, users->owner()->getMiniBuffer());
3344  
3345         // check return value from literate.build().
3346         if ((res & Literate::NO_LOGFILE)) {
3347                 WriteAlert(_("Build did not work!"),
3348                            _("Missing log file:"), name);
3349         } else if ((res & Literate::ERRORS)) {
3350                 users->owner()->getMiniBuffer()->Set(_("Done"));
3351                 // Insert all errors as errors boxes
3352                 insertErrors(terr);
3353                 
3354                 // Literate files should also be kept dirty if the literate 
3355                 // command run ends up with errors.
3356         } else {
3357                 //no errors or any other things to think about so:
3358                 users->owner()->getMiniBuffer()->Set(_("Done"));
3359                 markNwClean();
3360         }
3361  
3362         // if we removed error insets before we ran Literate/Build or if we inserted
3363         // error insets after we ran Literate/Build this must be run:
3364         if (a || (res & Literate::ERRORS)){
3365                 users->redraw();
3366                 users->fitCursor();
3367                 users->updateScrollbar();
3368         }
3369         AllowInput();
3370
3371         return literate.getNumErrors();
3372 }
3373
3374
3375 // This should be enabled when the Chktex class is implemented. (Asger)
3376 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3377 // Other flags: -wall -v0 -x
3378 int Buffer::runChktex()
3379 {
3380         if (!users->text) return 0;
3381
3382         ProhibitInput();
3383
3384         // get LaTeX-Filename
3385         string name = getLatexName();
3386         string path = OnlyPath(filename);
3387
3388         string org_path = path;
3389         if (lyxrc->use_tempdir || (IsDirWriteable(path) < 1)) {
3390                 path = tmppath;  
3391         }
3392
3393         Path p(path); // path to LaTeX file
3394         users->owner()->getMiniBuffer()->Set(_("Running chktex..."));
3395
3396         // Remove all error insets
3397         bool a = removeAutoInsets();
3398
3399         // Generate the LaTeX file if neccessary
3400         if (!isDviClean() || a) {
3401                 makeLaTeXFile(name, org_path, false);
3402                 markDviDirty();
3403         }
3404
3405         TeXErrors terr;
3406         Chktex chktex(lyxrc->chktex_command, name, filepath);
3407         int res = chktex.run(terr); // run chktex
3408
3409         if (res == -1) {
3410                 WriteAlert(_("chktex did not work!"),
3411                            _("Could not run with file:"), name);
3412         } else if (res > 0) {
3413                 // Insert all errors as errors boxes
3414                 insertErrors(terr);
3415         }
3416
3417         // if we removed error insets before we ran chktex or if we inserted
3418         // error insets after we ran chktex, this must be run:
3419         if (a || res){
3420                 users->redraw();
3421                 users->fitCursor();
3422                 users->updateScrollbar();
3423         }
3424         AllowInput();
3425
3426         return res;
3427 }
3428
3429
3430 extern void AllFloats(char, char);
3431
3432
3433 // candidate for move to BufferView
3434 void Buffer::insertErrors(TeXErrors & terr)
3435 {
3436         // Save the cursor position
3437         LyXCursor cursor = users->text->cursor;
3438
3439         // This is drastic, but it's the only fix, I could find. (Asger)
3440         AllFloats(1, 0);
3441         AllFloats(1, 1);
3442
3443         for (TeXErrors::Errors::const_iterator cit = terr.begin();
3444              cit != terr.end();
3445              ++cit) {
3446                 string desctext((*cit).error_desc);
3447                 string errortext((*cit).error_text);
3448                 string msgtxt = desctext + '\n' + errortext;
3449                 int errorrow = (*cit).error_in_line;
3450
3451                 // Insert error string for row number
3452                 int tmpid = -1; 
3453                 int tmppos = -1;
3454
3455                 texrow.getIdFromRow(errorrow, tmpid, tmppos);
3456
3457                 LyXParagraph * texrowpar = 0;
3458
3459                 if (tmpid == -1) {
3460                         texrowpar = users->text->FirstParagraph();
3461                         tmppos = 0;
3462                 } else {
3463                         texrowpar = users->text->GetParFromID(tmpid);
3464                 }
3465
3466                 if (texrowpar == 0)
3467                         continue;
3468
3469                 InsetError * new_inset = new InsetError(msgtxt);
3470                 users->text->SetCursorIntern(texrowpar, tmppos);
3471                 users->text->InsertInset(new_inset);
3472                 users->text->FullRebreak();
3473         }
3474         // Restore the cursor position
3475         users->text->SetCursorIntern(cursor.par, cursor.pos);
3476 }
3477
3478
3479 // candidate for move to BufferView
3480 void Buffer::setCursorFromRow (int row)
3481 {
3482         int tmpid = -1; 
3483         int tmppos = -1;
3484
3485         texrow.getIdFromRow(row, tmpid, tmppos);
3486
3487         LyXParagraph * texrowpar;
3488
3489         if (tmpid == -1) {
3490                 texrowpar = users->text->FirstParagraph();
3491                 tmppos = 0;
3492         } else {
3493                 texrowpar = users->text->GetParFromID(tmpid);
3494         }
3495         users->text->SetCursor(texrowpar, tmppos);
3496 }
3497
3498
3499 void Buffer::RoffAsciiTable(ostream & os, LyXParagraph * par)
3500 {
3501         LyXFont font1 =  LyXFont(LyXFont::ALL_INHERIT);
3502         LyXFont font2;
3503         Inset * inset;
3504         LyXParagraph::size_type i;
3505         int j, cell = 0;
3506         char c;
3507         
3508         string fname1 = TmpFileName(string(), "RAT1");
3509         string fname2 = TmpFileName(string(), "RAT2");
3510
3511         ofstream ofs(fname1.c_str());
3512         if (!ofs) {
3513                 WriteAlert(_("LYX_ERROR:"),
3514                            _("Cannot open temporary file:"), fname1);
3515                 return;
3516         }
3517         par->table->RoffEndOfCell(ofs, -1);
3518         for (i = 0; i < par->size(); ++i) {
3519                 c = par->GetChar(i);
3520                 if (par->table->IsContRow(cell)) {
3521                         if (c == LyXParagraph::META_NEWLINE)
3522                                 cell++;
3523                         continue;
3524                 }
3525                 font2 = par->GetFontSettings(i);
3526                 if (font1.latex() != font2.latex()) {
3527                         if (font2.latex() != LyXFont::OFF)
3528                                 continue;
3529                 }
3530                 switch (c) {
3531                 case LyXParagraph::META_INSET:
3532                         if ((inset = par->GetInset(i))) {
3533                                 fstream fs(fname2.c_str(), ios::in|ios::out);
3534                                 if (!fs) {
3535                                         WriteAlert(_("LYX_ERROR:"),
3536                                                    _("Cannot open temporary file:"), fname2);
3537                                         ofs.close();
3538                                         remove(fname1.c_str());
3539                                         return;
3540                                 }
3541                                 inset->Latex(fs, -1);
3542                                 fs.seekp(0);
3543                                 fs.get(c);
3544                                 while(!fs) {
3545                                         if (c == '\\')
3546                                                 ofs << "\\\\";
3547                                         else
3548                                                 ofs << c;
3549                                         fs >> c;
3550                                 }
3551                                 fs.close();
3552                         }
3553                         break;
3554                 case LyXParagraph::META_NEWLINE:
3555                         if (par->table->CellHasContRow(cell)>= 0)
3556                                 par->RoffContTableRows(ofs, i+1, cell);
3557                         par->table->RoffEndOfCell(ofs, cell);
3558                         cell++;
3559                         break;
3560                 case LyXParagraph::META_HFILL: 
3561                         break;
3562                 case LyXParagraph::META_PROTECTED_SEPARATOR:
3563                         break;
3564                 case '\\': 
3565                         ofs << "\\\\";
3566                         break;
3567                 default:
3568                         if (c != '\0')
3569                                 ofs << c;
3570                         else if (c == '\0')
3571                                 lyxerr.debug()
3572                                         << "RoffAsciiTable:"
3573                                         " NULL char in structure." << endl;
3574                         break;
3575                 }
3576         }
3577         par->table->RoffEndOfCell(ofs, cell);
3578         ofs.close();
3579         string cmd = lyxrc->ascii_roff_command + " >" + fname2;
3580         cmd = subst(cmd, "$$FName", fname1);
3581         Systemcalls one(Systemcalls::System, cmd);
3582         if (!(lyxerr.debugging(Debug::ROFF))) {
3583                 remove(fname1.c_str());
3584         }
3585         ifstream ifs(fname2.c_str());
3586         if (!ifs) {
3587                 WriteFSAlert(_("Error! Can't open temporary file:"), fname2);
3588                 return;
3589         }
3590         // now output the produced file
3591         os << "\n\n";
3592         ifs.get(c);
3593         if (!ifs)
3594                 WriteAlert(_("Error!"),
3595                            _("Error executing *roff command on table"));
3596         // overread leading blank lines
3597         while(!ifs && (c == '\n'))
3598                 ifs.get(c);
3599         while(!ifs) {
3600                 for(j = 0; j < par->depth; ++j)
3601                         os << "  ";
3602                 while(!ifs && (c != '\n')) {
3603                         os << c;
3604                         ifs.get(c);
3605                 }
3606                 os << '\n';
3607                 // overread trailing blank lines
3608                 while(!ifs && (c == '\n'))
3609                         ifs.get(c);
3610         }
3611         ifs.close();
3612         remove(fname2.c_str());
3613 }
3614
3615         
3616 /// changed Heinrich Bauer, 23/03/98
3617 bool Buffer::isDviClean()
3618 {
3619   if (lyxrc->use_tempdir)
3620     return dvi_clean_tmpd;
3621   else
3622     return dvi_clean_orgd;
3623 }
3624
3625  
3626 /// changed Heinrich Bauer, 23/03/98
3627 void Buffer::markDviClean()
3628 {
3629   if (lyxrc->use_tempdir)
3630     dvi_clean_tmpd = true;
3631   else
3632     dvi_clean_orgd = true;
3633 }
3634
3635
3636 /// changed Heinrich Bauer, 23/03/98
3637 void Buffer::markDviDirty()
3638 {
3639   if (lyxrc->use_tempdir)
3640     dvi_clean_tmpd = false;
3641   else
3642     dvi_clean_orgd = false;
3643 }
3644
3645
3646 void Buffer::validate(LaTeXFeatures & features)
3647 {
3648         LyXParagraph * par = paragraph;
3649         LyXTextClass const & tclass = 
3650                 textclasslist.TextClass(params.textclass);
3651     
3652         // AMS Style is at document level
3653     
3654         features.amsstyle = (params.use_amsmath ||
3655                              tclass.provides(LyXTextClass::amsmath));
3656     
3657         while (par) {
3658                 // We don't use "lyxerr.debug" because of speed. (Asger)
3659                 if (lyxerr.debugging(Debug::LATEX))
3660                         lyxerr << "Paragraph: " <<  par << endl;
3661
3662                 // Now just follow the list of paragraphs and run
3663                 // validate on each of them.
3664                 par->validate(features);
3665
3666                 // and then the next paragraph
3667                 par = par->next;
3668         }
3669
3670         // the bullet shapes are buffer level not paragraph level
3671         // so they are tested here
3672         for (int i = 0; i < 4; ++i) {
3673                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3674                         int font = params.user_defined_bullets[i].getFont();
3675                         if (font == 0) {
3676                                 int c = params
3677                                         .user_defined_bullets[i]
3678                                         .getCharacter();
3679                                 if (c == 16
3680                                    || c == 17
3681                                    || c == 25
3682                                    || c == 26
3683                                    || c == 31) {
3684                                         features.latexsym = true;
3685                                 }
3686                         }
3687                         if (font == 1) {
3688                                 features.amssymb = true;
3689                         }
3690                         else if ((font >= 2 && font <= 5)) {
3691                                 features.pifont = true;
3692                         }
3693                 }
3694         }
3695         
3696         if (lyxerr.debugging(Debug::LATEX)) {
3697                 features.showStruct(params);
3698         }
3699 }
3700
3701
3702 void Buffer::setPaperStuff()
3703 {
3704         params.papersize = BufferParams::PAPER_DEFAULT;
3705         char c1 = params.paperpackage;
3706         if (c1 == BufferParams::PACKAGE_NONE) {
3707                 char c2 = params.papersize2;
3708                 if (c2 == BufferParams::VM_PAPER_USLETTER)
3709                         params.papersize = BufferParams::PAPER_USLETTER;
3710                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3711                         params.papersize = BufferParams::PAPER_LEGALPAPER;
3712                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3713                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3714                 else if (c2 == BufferParams::VM_PAPER_A3)
3715                         params.papersize = BufferParams::PAPER_A3PAPER;
3716                 else if (c2 == BufferParams::VM_PAPER_A4)
3717                         params.papersize = BufferParams::PAPER_A4PAPER;
3718                 else if (c2 == BufferParams::VM_PAPER_A5)
3719                         params.papersize = BufferParams::PAPER_A5PAPER;
3720                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3721                          (c2 == BufferParams::VM_PAPER_B5))
3722                         params.papersize = BufferParams::PAPER_B5PAPER;
3723         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3724                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3725                 params.papersize = BufferParams::PAPER_A4PAPER;
3726 }
3727
3728
3729 #if 0
3730 void Buffer::setOldPaperStuff()
3731 {
3732         char c = params.papersize = params.papersize2;
3733         params.papersize2 = BufferParams::VM_PAPER_DEFAULT;
3734         params.paperpackage = BufferParams::PACKAGE_NONE;
3735         if (c == OLD_PAPER_A4PAPER)
3736                 params.papersize2 = BufferParams::VM_PAPER_A4;
3737         else if (c == OLD_PAPER_A4)
3738                 params.paperpackage = BufferParams::PACKAGE_A4;
3739         else if (c == OLD_PAPER_A4WIDE)
3740                 params.paperpackage = BufferParams::PACKAGE_A4WIDE;
3741         else if (c == OLD_PAPER_WIDEMARGINSA4)
3742                 params.paperpackage = BufferParams::PACKAGE_WIDEMARGINSA4;
3743         else if (c == OLD_PAPER_USLETTER)
3744                 params.papersize2 = BufferParams::VM_PAPER_USLETTER;
3745         else if (c == OLD_PAPER_A5PAPER)
3746                 params.papersize2 = BufferParams::VM_PAPER_A5;
3747         else if (c == OLD_PAPER_B5PAPER)
3748                 params.papersize2 = BufferParams::VM_PAPER_B5;
3749         else if (c == OLD_PAPER_EXECUTIVEPAPER)
3750                 params.papersize2 = BufferParams::VM_PAPER_USEXECUTIVE;
3751         else if (c == OLD_PAPER_LEGALPAPER)
3752                 params.papersize2 = BufferParams::VM_PAPER_USLEGAL;
3753         setPaperStuff();
3754 }
3755 #endif
3756
3757
3758 // candidate for move to BufferView
3759 void Buffer::insertInset(Inset * inset, string const & lout,
3760                          bool no_table)
3761 {
3762         // check for table/list in tables
3763         if (no_table && users->text->cursor.par->table){
3764                 WriteAlert(_("Impossible Operation!"),
3765                            _("Cannot insert table/list in table."),
3766                            _("Sorry."));
3767                 return;
3768         }
3769         // not quite sure if we want this...
3770         users->text->SetCursorParUndo();
3771         users->text->FreezeUndo();
3772         
3773         BeforeChange();
3774         if (!lout.empty()) {
3775                 users->update(-2);
3776                 users->text->BreakParagraph();
3777                 users->update(-1);
3778                 
3779                 if (users->text->cursor.par->Last()) {
3780                         users->text->CursorLeft();
3781                         
3782                         users->text->BreakParagraph();
3783                         users->update(-1);
3784                 }
3785
3786                 int lay = textclasslist.NumberOfLayout(params.textclass,
3787                                                        lout).second;
3788                 if (lay == -1) // layout not found
3789                         // use default layout "Standard" (0)
3790                         lay = 0;
3791                 
3792                 users->text->SetLayout(lay);
3793                 
3794                 users->text->SetParagraph(0, 0,
3795                                    0, 0,
3796                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3797                                    LYX_ALIGN_LAYOUT, 
3798                                    string(),
3799                                    0);
3800                 users->update(-1);
3801                 
3802                 users->text->current_font.setLatex(LyXFont::OFF);
3803         }
3804         
3805         users->text->InsertInset(inset);
3806         users->update(-1);
3807
3808         users->text->UnFreezeUndo();    
3809 }
3810
3811
3812 // Open and lock an updatable inset
3813 // candidate for move to BufferView
3814 void Buffer::open_new_inset(UpdatableInset * new_inset)
3815 {
3816         BeforeChange();
3817         users->text->FinishUndo();
3818         insertInset(new_inset);
3819         users->text->CursorLeft();
3820         users->update(1);
3821         new_inset->Edit(0, 0);
3822 }
3823
3824
3825 /* This function should be in Buffer because it's a buffer's property (ale) */
3826 string Buffer::getIncludeonlyList(char delim)
3827 {
3828         string lst;
3829         LyXParagraph * par = paragraph;
3830         LyXParagraph::size_type pos;
3831         Inset * inset;
3832         while (par){
3833                 pos = -1;
3834                 while ((inset = par->ReturnNextInsetPointer(pos))){
3835                         if (inset->LyxCode() == Inset::INCLUDE_CODE) {
3836                                 InsetInclude * insetinc = 
3837                                         static_cast<InsetInclude*>(inset);
3838                                 if (insetinc->isInclude() 
3839                                     && insetinc->isNoLoad()) {
3840                                         if (!lst.empty())
3841                                                 lst += delim;
3842                                         lst += ChangeExtension(insetinc->getContents(), string(), true);
3843                                 }
3844                         }
3845                         pos++;
3846                 } 
3847                 par = par->next;
3848         }
3849         lyxerr.debug() << "Includeonly(" << lst << ')' << endl;
3850         return lst;
3851 }
3852
3853
3854 /* This is also a buffer property (ale) */ 
3855 string Buffer::getReferenceList(char delim)
3856 {
3857         /// if this is a child document and the parent is already loaded
3858         /// Use the parent's list instead  [ale990407]
3859         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3860                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3861                 if (tmp)
3862                   return tmp->getReferenceList(delim);
3863         }
3864
3865         LyXParagraph * par = paragraph;
3866         LyXParagraph::size_type pos;
3867         Inset * inset;
3868         string lst;
3869         while (par){
3870                 pos = -1;
3871                 while ((inset = par->ReturnNextInsetPointer(pos))){     
3872                         for (int i = 0; i < inset->GetNumberOfLabels(); i++) {
3873                                 if (!lst.empty())
3874                                         lst += delim;
3875                                 lst += inset->getLabel(i);
3876                         }
3877                         pos++;
3878                 } 
3879                 par = par->next;
3880         }
3881         lyxerr.debug() << "References(" <<  lst << ")" << endl;
3882         return lst;
3883 }
3884
3885
3886 /* This is also a buffer property (ale) */ 
3887 string Buffer::getBibkeyList(char delim)
3888 {
3889         /// if this is a child document and the parent is already loaded
3890         /// Use the parent's list instead  [ale990412]
3891         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3892                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3893                 if (tmp)
3894                         return tmp->getBibkeyList(delim);
3895         }
3896
3897         string bibkeys;
3898         LyXParagraph * par = paragraph;
3899         while (par) {
3900                 if (par->bibkey) {
3901                         if (!bibkeys.empty())
3902                                 bibkeys += delim;
3903                         bibkeys += par->bibkey->getContents();
3904                 }
3905                 par = par->next;
3906         }
3907
3908         // Might be either using bibtex or a child has bibliography
3909         if (bibkeys.empty()) {
3910                 par = paragraph;
3911                 while (par) {
3912                         Inset * inset;
3913                         LyXParagraph::size_type pos = -1;
3914
3915                         // Search for Bibtex or Include inset
3916                         while ((inset = par->ReturnNextInsetPointer(pos))) {
3917                                 if (inset-> LyxCode() == Inset::BIBTEX_CODE) {
3918                                         if (!bibkeys.empty())
3919                                                 bibkeys += delim;
3920                                         bibkeys += static_cast<InsetBibtex*>(inset)->getKeys();
3921                                 } else if (inset-> LyxCode() == Inset::INCLUDE_CODE) {
3922                                         string bk = static_cast<InsetInclude*>(inset)->getKeys();
3923                                         if (!bk.empty()) {
3924                                                 if (!bibkeys.empty())
3925                                                         bibkeys += delim;
3926                                                 bibkeys += bk;
3927                                         }
3928                                 }
3929                                 pos++;
3930                         }
3931                         par = par->next;
3932                 }
3933         }
3934  
3935         lyxerr.debug() << "Bibkeys(" << bibkeys << ")" << endl;
3936         return bibkeys;
3937 }
3938
3939
3940 // candidate for move to BufferView
3941 /* This is also a buffer property (ale) */
3942 // Not so sure about that. a goto Label function can not be buffer local, just
3943 // think how this will work in a multiwindo/buffer environment, all the
3944 // cursors in all the views showing this buffer will move. (Lgb)
3945 // OK, then no cursor action should be allowed in buffer. (ale)
3946 bool Buffer::gotoLabel(string const & label)
3947
3948 {
3949         LyXParagraph * par = paragraph;
3950         LyXParagraph::size_type pos;
3951         Inset * inset;
3952         while (par) {
3953                 pos = -1;
3954                 while ((inset = par->ReturnNextInsetPointer(pos))){     
3955                         for (int i = 0; i < inset->GetNumberOfLabels(); i++) {
3956                                 if (label == inset->getLabel(i)) {
3957                                         BeforeChange();
3958                                         users->text->SetCursor(par, pos);
3959                                         users->text->sel_cursor = users->text->cursor;
3960                                         users->update(0);
3961                                         return true;
3962                                 }
3963                         }
3964                         pos++;
3965                 } 
3966                 par = par->next;
3967         }
3968         return false;
3969 }
3970
3971
3972 bool Buffer::isDepClean(string const & name) const
3973 {
3974         DEPCLEAN * item = dep_clean;
3975         while (item && item->master != name)
3976                 item = item->next;
3977         if (!item) return true;
3978         return item->clean;
3979 }
3980
3981
3982 void Buffer::markDepClean(string const & name)
3983 {
3984         if (!dep_clean) {
3985                 dep_clean = new DEPCLEAN;
3986                 dep_clean->clean = true;
3987                 dep_clean->master = name;
3988                 dep_clean->next = 0;
3989         } else {
3990                 DEPCLEAN* item = dep_clean;
3991                 while (item && item->master != name)
3992                         item = item->next;
3993                 if (item) {
3994                         item->clean = true;
3995                 } else {
3996                         item = new DEPCLEAN;
3997                         item->clean = true;
3998                         item->master = name;
3999                         item->next = 0;;
4000                 }
4001         }
4002 }
4003
4004 void Buffer::Dispatch(const string & command)
4005 {
4006         // Split command string into command and argument
4007         string cmd, line = frontStrip(command);
4008         string arg = strip(frontStrip(split(line, cmd, ' ')));
4009
4010         Dispatch(lyxaction.LookupFunc(cmd.c_str()), arg.c_str());
4011 }
4012
4013 void Buffer::Dispatch(int action, const string & argument)
4014 {
4015         switch (action) {
4016                 case LFUN_EXPORT: 
4017                         MenuExport(this, argument);
4018                         break;
4019                         break;
4020
4021                 default:
4022                         lyxerr << "A truly unknown func!" << endl;
4023                 break;
4024
4025         } // end of switch
4026
4027 }