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