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