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