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