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