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