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