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