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