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