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