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