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