]> git.lyx.org Git - lyx.git/blob - src/buffer.C
5be67668d69eae1ef629c3c34f9bdc718e28d6ba
[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                 // Does this fix it? YES!
1045                 checkminipage = true;
1046                 
1047 #ifdef NO_LATEX
1048                 insertErtContents(par, pos, font, false);
1049                 ert_stack.push(ert_comp);
1050                 ert_comp = ErtComp();
1051 #endif
1052                 readInset(lex, par, pos, font);
1053 #ifdef NO_LATEX
1054                 ert_comp = ert_stack.top();
1055                 ert_stack.pop();
1056 #endif
1057         } else if (token == "\\SpecialChar") {
1058                 LyXLayout const & layout =
1059                         textclasslist.Style(params.textclass, 
1060                                             par->getLayout());
1061
1062                 // Insets don't make sense in a free-spacing context! ---Kayvan
1063                 if (layout.free_spacing) {
1064                         if (lex.IsOK()) {
1065                                 lex.next();
1066                                 string next_token = lex.GetString();
1067                                 if (next_token == "\\-") {
1068                                         par->insertChar(pos, '-', font);
1069                                 } else if (next_token == "\\protected_separator"
1070                                         || next_token == "~") {
1071                                         par->insertChar(pos, ' ', font);
1072                                 } else {
1073                                         lex.printError("Token `$$Token' "
1074                                                        "is in free space "
1075                                                        "paragraph layout!");
1076                                         --pos;
1077                                 }
1078                         }
1079                 } else {
1080                         Inset * inset = new InsetSpecialChar;
1081                         inset->read(this, lex);
1082                         par->insertInset(pos, inset, font);
1083                 }
1084                 ++pos;
1085         } else if (token == "\\newline") {
1086 #ifdef NO_LATEX
1087
1088                 if (!ert_comp.in_tabular && ert_comp.active) {
1089                         ert_comp.contents += char(Paragraph::META_NEWLINE);
1090                 } else {
1091                         // Since we cannot know it this is only a regular
1092                         // newline or a tabular cell delimter we have to
1093                         // handle the ERT here.
1094                         insertErtContents(par, pos, font, false);
1095
1096                         par->insertChar(pos, Paragraph::META_NEWLINE, font);
1097                         ++pos;
1098                 }
1099 #else
1100                 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1101                 ++pos;
1102 #endif
1103         } else if (token == "\\LyXTable") {
1104 #ifdef NO_LATEX
1105                 ert_comp.in_tabular = true;
1106 #endif
1107                 Inset * inset = new InsetTabular(*this);
1108                 inset->read(this, lex);
1109                 par->insertInset(pos, inset, font);
1110                 ++pos;
1111                 // because of OLD_TABULAR_READ where tabulars have been
1112                 // one paragraph.
1113                 checkminipage = true;
1114         } else if (token == "\\hfill") {
1115                 par->insertChar(pos, Paragraph::META_HFILL, font);
1116                 ++pos;
1117         } else if (token == "\\protected_separator") { // obsolete
1118                 // This is a backward compability thingie. (Lgb)
1119                 // Remove it later some time...introduced with fileformat
1120                 // 2.16. (Lgb)
1121                 LyXLayout const & layout =
1122                         textclasslist.Style(params.textclass, 
1123                                             par->getLayout());
1124
1125                 if (layout.free_spacing) {
1126                         par->insertChar(pos, ' ', font);
1127                 } else {
1128                         Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1129                         par->insertInset(pos, inset, font);
1130                 }
1131                 ++pos;
1132         } else if (token == "\\bibitem") {  // ale970302
1133                 if (!par->bibkey) {
1134                         InsetCommandParams p("bibitem", "dummy");
1135                         par->bibkey = new InsetBibKey(p);
1136                 }
1137                 par->bibkey->read(this, lex);                   
1138         } else if (token == "\\backslash") {
1139 #ifdef NO_LATEX
1140                 if (ert_comp.active) {
1141                         ert_comp.contents += "\\";
1142                 } else {
1143 #endif
1144                 par->insertChar(pos, '\\', font);
1145                 ++pos;
1146 #ifdef NO_LATEX
1147                 }
1148 #endif
1149         } else if (token == "\\the_end") {
1150 #ifdef NO_LATEX
1151                 // If we still have some ert active here we have to insert
1152                 // it so we don't loose it. (Lgb)
1153                 insertErtContents(par, pos, font);
1154 #endif
1155                 the_end_read = true;
1156                 minipar = parBeforeMinipage = 0;
1157         } else {
1158 #ifdef NO_LATEX
1159                 if (ert_comp.active) {
1160                         ert_comp.contents += token;
1161                 } else {
1162 #endif
1163                 // This should be insurance for the future: (Asger)
1164                 lex.printError("Unknown token `$$Token'. "
1165                                "Inserting as text.");
1166                 string::const_iterator cit = token.begin();
1167                 string::const_iterator end = token.end();
1168                 for (; cit != end; ++cit) {
1169                         par->insertChar(pos, (*cit), font);
1170                         ++pos;
1171                 }
1172 #ifdef NO_LATEX
1173                 }
1174 #endif
1175         }
1176 #ifndef NO_PEXTRA_REALLY
1177         // now check if we have a minipage paragraph as at this
1178         // point we already read all the necessary data!
1179         // this cannot be done in layout because there we did
1180         // not read yet the paragraph PEXTRA-params (Jug)
1181         //
1182         // BEGIN pextra_minipage compability
1183         // This should be removed in 1.3.x (Lgb)
1184         
1185         // This compability code is not perfect. In a couple
1186         // of rand cases it fails. When the minipage par is
1187         // the first par in the document, and when there are
1188         // none or only one regular paragraphs after the
1189         // minipage. Currently I am not investing any effort
1190         // in fixing those cases.
1191
1192         //lyxerr << "Call depth: " << call_depth << endl;
1193         if (checkminipage && (call_depth == 1)) {
1194         checkminipage = false;
1195         if (minipar && (minipar != par) &&
1196             (par->params().pextraType()==Paragraph::PEXTRA_MINIPAGE))
1197         {
1198                 lyxerr << "minipages in a row" << endl;
1199                 if (par->params().pextraStartMinipage()) {
1200                         lyxerr << "start new minipage" << endl;
1201                         // minipages in a row
1202                         par->previous()->next(0);
1203                         par->previous(0);
1204                                 
1205                         Paragraph * tmp = minipar;
1206                         while (tmp) {
1207                                 tmp->params().pextraType(0);
1208                                 tmp->params().pextraWidth(string());
1209                                 tmp->params().pextraWidthp(string());
1210                                 tmp->params().pextraAlignment(0);
1211                                 tmp->params().pextraHfill(false);
1212                                 tmp->params().pextraStartMinipage(false);
1213                                 tmp = tmp->next();
1214                         }
1215                         // create a new paragraph to insert the
1216                         // minipages in the following case
1217                         if (par->params().pextraStartMinipage() &&
1218                             !par->params().pextraHfill())
1219                         {
1220                                 Paragraph * p = new Paragraph;
1221                                 p->layout = 0;
1222                                 p->previous(parBeforeMinipage);
1223                                 parBeforeMinipage->next(p);
1224                                 p->next(0);
1225                                 p->params().depth(parBeforeMinipage->params().depth());
1226                                 parBeforeMinipage = p;
1227                         }
1228                         InsetMinipage * mini = new InsetMinipage;
1229                         mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1230                         mini->width(par->params().pextraWidth());
1231                         if (!par->params().pextraWidthp().empty()) {
1232                             lyxerr << "WP:" << mini->width() << endl;
1233                             mini->width(tostr(par->params().pextraWidthp())+"%");
1234                         }
1235                         mini->inset.paragraph(par);
1236                         // Insert the minipage last in the
1237                         // previous paragraph.
1238                         if (par->params().pextraHfill()) {
1239                                 parBeforeMinipage->insertChar
1240                                         (parBeforeMinipage->size(), Paragraph::META_HFILL);
1241                         }
1242                         parBeforeMinipage->insertInset
1243                                 (parBeforeMinipage->size(), mini);
1244                                 
1245                         minipar = par;
1246                 } else {
1247                         lyxerr << "new minipage par" << endl;
1248                         //nothing to do just continue reading
1249                 }
1250                         
1251         } else if (minipar && (minipar != par)) {
1252                 lyxerr << "last minipage par read" << endl;
1253                 // The last paragraph read was not part of a
1254                 // minipage but the par linked list is...
1255                 // So we need to remove the last par from the
1256                 // rest
1257                 if (par->previous())
1258                         par->previous()->next(0);
1259                 par->previous(parBeforeMinipage);
1260                 parBeforeMinipage->next(par);
1261                 Paragraph * tmp = minipar;
1262                 while (tmp) {
1263                         tmp->params().pextraType(0);
1264                         tmp->params().pextraWidth(string());
1265                         tmp->params().pextraWidthp(string());
1266                         tmp->params().pextraAlignment(0);
1267                         tmp->params().pextraHfill(false);
1268                         tmp->params().pextraStartMinipage(false);
1269                         tmp = tmp->next();
1270                 }
1271                 depth = parBeforeMinipage->params().depth();
1272                 minipar = parBeforeMinipage = 0;
1273         } else if (!minipar &&
1274                    (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1275         {
1276                 // par is the first paragraph in a minipage
1277                 lyxerr << "begin minipage" << endl;
1278                 // To minimize problems for
1279                 // the users we will insert
1280                 // the first minipage in
1281                 // a sequence of minipages
1282                 // in its own paragraph.
1283                 Paragraph * p = new Paragraph;
1284                 p->layout = 0;
1285                 p->previous(par->previous());
1286                 p->next(0);
1287                 p->params().depth(depth);
1288                 par->params().depth(0);
1289                 depth = 0;
1290                 if (par->previous())
1291                         par->previous()->next(p);
1292                 par->previous(0);
1293                 parBeforeMinipage = p;
1294                 minipar = par;
1295                 if (!first_par || (first_par == par))
1296                         first_par = p;
1297
1298                 InsetMinipage * mini = new InsetMinipage;
1299                 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1300                 mini->width(minipar->params().pextraWidth());
1301                 if (!par->params().pextraWidthp().empty()) {
1302                     lyxerr << "WP:" << mini->width() << endl;
1303                     mini->width(tostr(par->params().pextraWidthp())+"%");
1304                 }
1305                 mini->inset.paragraph(minipar);
1306                         
1307                 // Insert the minipage last in the
1308                 // previous paragraph.
1309                 if (minipar->params().pextraHfill()) {
1310                         parBeforeMinipage->insertChar
1311                                 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1312                 }
1313                 parBeforeMinipage->insertInset
1314                         (parBeforeMinipage->size(), mini);
1315         }
1316         }
1317         // End of pextra_minipage compability
1318 #endif
1319         --call_depth;
1320         return the_end_read;
1321 }
1322
1323 // needed to insert the selection
1324 void Buffer::insertStringAsLines(Paragraph *& par, Paragraph::size_type & pos,
1325                                  LyXFont const & font, 
1326                                  string const & str) const
1327 {
1328         LyXLayout const & layout = textclasslist.Style(params.textclass, 
1329                                                      par->getLayout());
1330         // insert the string, don't insert doublespace
1331         bool space_inserted = true;
1332         for(string::const_iterator cit = str.begin(); 
1333             cit != str.end(); ++cit) {
1334                 if (*cit == '\n') {
1335                         if (par->size() || layout.keepempty) { 
1336                                 par->breakParagraph(params, pos, 
1337                                                     layout.isEnvironment());
1338                                 par = par->next();
1339                                 pos = 0;
1340                                 space_inserted = true;
1341                         } else {
1342                                 continue;
1343                         }
1344                         // do not insert consecutive spaces if !free_spacing
1345                 } else if ((*cit == ' ' || *cit == '\t')
1346                            && space_inserted && !layout.free_spacing) {
1347                         continue;
1348                 } else if (*cit == '\t') {
1349                         if (!layout.free_spacing) {
1350                                 // tabs are like spaces here
1351                                 par->insertChar(pos, ' ', font);
1352                                 ++pos;
1353                                 space_inserted = true;
1354                         } else {
1355                                 const Paragraph::value_type nb = 8 - pos % 8;
1356                                 for (Paragraph::size_type a = 0; 
1357                                      a < nb ; ++a) {
1358                                         par->insertChar(pos, ' ', font);
1359                                         ++pos;
1360                                 }
1361                                 space_inserted = true;
1362                         }
1363                 } else if (!IsPrintable(*cit)) {
1364                         // Ignore unprintables
1365                         continue;
1366                 } else {
1367                         // just insert the character
1368                         par->insertChar(pos, *cit, font);
1369                         ++pos;
1370                         space_inserted = (*cit == ' ');
1371                 }
1372
1373         }       
1374 }
1375
1376
1377 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1378                        int & pos, LyXFont & font)
1379 {
1380         // consistency check
1381         if (lex.GetString() != "\\begin_inset") {
1382                 lyxerr << "Buffer::readInset: Consistency check failed."
1383                        << endl;
1384         }
1385         
1386         Inset * inset = 0;
1387
1388         lex.next();
1389         string const tmptok = lex.GetString();
1390         last_inset_read = tmptok;
1391
1392         // test the different insets
1393         if (tmptok == "LatexCommand") {
1394                 InsetCommandParams inscmd;
1395                 inscmd.read(lex);
1396
1397                 string const cmdName = inscmd.getCmdName();
1398                 
1399                 // This strange command allows LyX to recognize "natbib" style
1400                 // citations: citet, citep, Citet etc.
1401                 if (compare_no_case(cmdName, "cite", 4) == 0) {
1402                         inset = new InsetCitation(inscmd);
1403                 } else if (cmdName == "bibitem") {
1404                         lex.printError("Wrong place for bibitem");
1405                         inset = new InsetBibKey(inscmd);
1406                 } else if (cmdName == "BibTeX") {
1407                         inset = new InsetBibtex(inscmd);
1408                 } else if (cmdName == "index") {
1409                         inset = new InsetIndex(inscmd);
1410                 } else if (cmdName == "include") {
1411                         inset = new InsetInclude(inscmd, *this);
1412                 } else if (cmdName == "label") {
1413                         inset = new InsetLabel(inscmd);
1414                 } else if (cmdName == "url"
1415                            || cmdName == "htmlurl") {
1416                         inset = new InsetUrl(inscmd);
1417                 } else if (cmdName == "ref"
1418                            || cmdName == "pageref"
1419                            || cmdName == "vref"
1420                            || cmdName == "vpageref"
1421                            || cmdName == "prettyref") {
1422                         if (!inscmd.getOptions().empty()
1423                             || !inscmd.getContents().empty()) {
1424                                 inset = new InsetRef(inscmd, *this);
1425                         }
1426                 } else if (cmdName == "tableofcontents") {
1427                         inset = new InsetTOC(inscmd);
1428                 } else if (cmdName == "listofalgorithms") {
1429                         inset = new InsetFloatList("algorithm");
1430                 } else if (cmdName == "listoffigures") {
1431                         inset = new InsetFloatList("figure");
1432                 } else if (cmdName == "listoftables") {
1433                         inset = new InsetFloatList("table");
1434                 } else if (cmdName == "printindex") {
1435                         inset = new InsetPrintIndex(inscmd);
1436                 } else if (cmdName == "lyxparent") {
1437                         inset = new InsetParent(inscmd, *this);
1438                 }
1439         } else {
1440                 bool alreadyread = false;
1441                 if (tmptok == "Quotes") {
1442                         inset = new InsetQuotes;
1443                 } else if (tmptok == "External") {
1444                         inset = new InsetExternal;
1445                 } else if (tmptok == "FormulaMacro") {
1446                         inset = new InsetFormulaMacro;
1447                 } else if (tmptok == "Formula") {
1448                         inset = new InsetFormula;
1449                 } else if (tmptok == "Figure") {
1450                         inset = new InsetFig(100, 100, *this);
1451                 } else if (tmptok == "Info") {// backwards compatibility
1452                         inset = new InsetNote(this,
1453                                               lex.getLongString("\\end_inset"),
1454                                               true);
1455                         alreadyread = true;
1456                 } else if (tmptok == "Note") {
1457                         inset = new InsetNote;
1458                 } else if (tmptok == "Include") {
1459                         InsetCommandParams p( "Include" );
1460                         inset = new InsetInclude(p, *this);
1461                 } else if (tmptok == "ERT") {
1462                         inset = new InsetERT;
1463                 } else if (tmptok == "Tabular") {
1464                         inset = new InsetTabular(*this);
1465                 } else if (tmptok == "Text") {
1466                         inset = new InsetText;
1467                 } else if (tmptok == "Foot") {
1468                         inset = new InsetFoot;
1469                 } else if (tmptok == "Marginal") {
1470                         inset = new InsetMarginal;
1471                 } else if (tmptok == "Minipage") {
1472                         inset = new InsetMinipage;
1473                 } else if (tmptok == "Float") {
1474                         lex.next();
1475                         string tmptok = lex.GetString();
1476                         inset = new InsetFloat(tmptok);
1477 #if 0
1478                 } else if (tmptok == "List") {
1479                         inset = new InsetList;
1480                 } else if (tmptok == "Theorem") {
1481                         inset = new InsetList;
1482 #endif
1483                 } else if (tmptok == "Caption") {
1484                         inset = new InsetCaption;
1485                 } else if (tmptok == "GRAPHICS") {
1486                         inset = new InsetGraphics;
1487                 } else if (tmptok == "FloatList") {
1488                         inset = new InsetFloatList;
1489                 }
1490                 
1491                 if (inset && !alreadyread) inset->read(this, lex);
1492         }
1493         
1494         if (inset) {
1495                 par->insertInset(pos, inset, font);
1496                 ++pos;
1497         }
1498 }
1499
1500
1501 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1502 {
1503         if (lex.IsOK()) {
1504                 lex.next();
1505                 string const token(lex.GetString());
1506                 if (token == "\\lyxformat") { // the first token _must_ be...
1507                         lex.EatLine();
1508                         string tmp_format = lex.GetString();
1509                         //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1510                         // if present remove ".," from string.
1511                         string::size_type dot = tmp_format.find_first_of(".,");
1512                         //lyxerr << "           dot found at " << dot << endl;
1513                         if (dot != string::npos)
1514                                 tmp_format.erase(dot, 1);
1515                         file_format = strToInt(tmp_format);
1516                         if (file_format == LYX_FORMAT) {
1517                                 // current format
1518                         } else if (file_format > LYX_FORMAT) {
1519                                 // future format
1520                                 WriteAlert(_("Warning!"),
1521                                            _("LyX file format is newer that what"),
1522                                            _("is supported in this LyX version. Expect some problems."));
1523                                 
1524                         } else if (file_format < LYX_FORMAT) {
1525                                 // old formats
1526                                 if (file_format < 200) {
1527                                         WriteAlert(_("ERROR!"),
1528                                                    _("Old LyX file format found. "
1529                                                      "Use LyX 0.10.x to read this!"));
1530                                         return false;
1531                                 }
1532                         }
1533                         bool the_end = readLyXformat2(lex, par);
1534                         setPaperStuff();
1535                         // the_end was added in 213
1536                         if (file_format < 213)
1537                                 the_end = true;
1538
1539                         if (!the_end)
1540                                 WriteAlert(_("Warning!"),
1541                                            _("Reading of document is not complete"),
1542                                            _("Maybe the document is truncated"));
1543                         return true;
1544                 } else { // "\\lyxformat" not found
1545                         WriteAlert(_("ERROR!"), _("Not a LyX file!"));
1546                 }
1547         } else
1548                 WriteAlert(_("ERROR!"), _("Unable to read file!"));
1549         return false;
1550 }
1551                     
1552
1553 // Should probably be moved to somewhere else: BufferView? LyXView?
1554 bool Buffer::save() const
1555 {
1556         // We don't need autosaves in the immediate future. (Asger)
1557         resetAutosaveTimers();
1558
1559         // make a backup
1560         string s;
1561         if (lyxrc.make_backup) {
1562                 s = fileName() + '~';
1563                 if (!lyxrc.backupdir_path.empty())
1564                         s = AddName(lyxrc.backupdir_path,
1565                                     subst(os::slashify_path(s),'/','!'));
1566
1567                 // Rename is the wrong way of making a backup,
1568                 // this is the correct way.
1569                 /* truss cp fil fil2:
1570                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1571                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1572                    open("LyXVC.lyx", O_RDONLY)                     = 3
1573                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1574                    fstat(4, 0xEFFFF508)                            = 0
1575                    fstat(3, 0xEFFFF508)                            = 0
1576                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1577                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1578                    read(3, 0xEFFFD4A0, 8192)                       = 0
1579                    close(4)                                        = 0
1580                    close(3)                                        = 0
1581                    chmod("LyXVC3.lyx", 0100644)                    = 0
1582                    lseek(0, 0, SEEK_CUR)                           = 46440
1583                    _exit(0)
1584                 */
1585
1586                 // Should probably have some more error checking here.
1587                 // Should be cleaned up in 0.13, at least a bit.
1588                 // Doing it this way, also makes the inodes stay the same.
1589                 // This is still not a very good solution, in particular we
1590                 // might loose the owner of the backup.
1591                 FileInfo finfo(fileName());
1592                 if (finfo.exist()) {
1593                         mode_t fmode = finfo.getMode();
1594                         struct utimbuf times = {
1595                                 finfo.getAccessTime(),
1596                                 finfo.getModificationTime() };
1597
1598                         ifstream ifs(fileName().c_str());
1599                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1600                         if (ifs && ofs) {
1601                                 ofs << ifs.rdbuf();
1602                                 ifs.close();
1603                                 ofs.close();
1604                                 ::chmod(s.c_str(), fmode);
1605                                 
1606                                 if (::utime(s.c_str(), &times)) {
1607                                         lyxerr << "utime error." << endl;
1608                                 }
1609                         } else {
1610                                 lyxerr << "LyX was not able to make "
1611                                         "backup copy. Beware." << endl;
1612                         }
1613                 }
1614         }
1615         
1616         if (writeFile(fileName(), false)) {
1617                 markLyxClean();
1618                 removeAutosaveFile(fileName());
1619         } else {
1620                 // Saving failed, so backup is not backup
1621                 if (lyxrc.make_backup) {
1622                         lyx::rename(s, fileName());
1623                 }
1624                 return false;
1625         }
1626         return true;
1627 }
1628
1629
1630 // Returns false if unsuccesful
1631 bool Buffer::writeFile(string const & fname, bool flag) const
1632 {
1633         // if flag is false writeFile will not create any GUI
1634         // warnings, only cerr.
1635         // Needed for autosave in background or panic save (Matthias 120496)
1636
1637         if (read_only && (fname == filename)) {
1638                 // Here we should come with a question if we should
1639                 // perform the write anyway.
1640                 if (flag)
1641                         lyxerr << _("Error! Document is read-only: ")
1642                                << fname << endl;
1643                 else
1644                         WriteAlert(_("Error! Document is read-only: "),
1645                                    fname);
1646                 return false;
1647         }
1648
1649         FileInfo finfo(fname);
1650         if (finfo.exist() && !finfo.writable()) {
1651                 // Here we should come with a question if we should
1652                 // try to do the save anyway. (i.e. do a chmod first)
1653                 if (flag)
1654                         lyxerr << _("Error! Cannot write file: ")
1655                                << fname << endl;
1656                 else
1657                         WriteFSAlert(_("Error! Cannot write file: "),
1658                                      fname);
1659                 return false;
1660         }
1661
1662         ofstream ofs(fname.c_str());
1663         if (!ofs) {
1664                 if (flag)
1665                         lyxerr << _("Error! Cannot open file: ")
1666                                << fname << endl;
1667                 else
1668                         WriteFSAlert(_("Error! Cannot open file: "),
1669                                      fname);
1670                 return false;
1671         }
1672
1673 #ifdef HAVE_LOCALE
1674         // Use the standard "C" locale for file output.
1675         ofs.imbue(std::locale::classic());
1676 #endif
1677
1678         // The top of the file should not be written by params.
1679
1680         // write out a comment in the top of the file
1681         ofs << '#' << LYX_DOCVERSION 
1682             << " created this file. For more info see http://www.lyx.org/\n"
1683             << "\\lyxformat " << LYX_FORMAT << "\n";
1684
1685         // now write out the buffer paramters.
1686         params.writeFile(ofs);
1687
1688         Paragraph::depth_type depth = 0;
1689
1690         // this will write out all the paragraphs
1691         // using recursive descent.
1692         paragraph->writeFile(this, ofs, params, depth);
1693
1694         // Write marker that shows file is complete
1695         ofs << "\n\\the_end" << endl;
1696
1697         ofs.close();
1698
1699         // how to check if close went ok?
1700         // Following is an attempt... (BE 20001011)
1701         
1702         // good() returns false if any error occured, including some
1703         //        formatting error.
1704         // bad()  returns true if something bad happened in the buffer,
1705         //        which should include file system full errors.
1706
1707         bool status = true;
1708         if (!ofs.good()) {
1709                 status = false;
1710 #if 0
1711                 if (ofs.bad()) {
1712                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1713                 } else {
1714                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1715                                << endl;
1716                 }
1717 #endif
1718         }
1719         
1720         return status;
1721 }
1722
1723
1724 string const Buffer::asciiParagraph(Paragraph const * par,
1725                                     unsigned int linelen) const
1726 {
1727         ostringstream buffer;
1728         Paragraph::depth_type depth = 0;
1729         int ltype = 0;
1730         Paragraph::depth_type ltype_depth = 0;
1731         unsigned int currlinelen = 0;
1732         bool ref_printed = false;
1733
1734         int noparbreak = 0;
1735         int islatex = 0;
1736         if (!par->previous()) {
1737                 // begins or ends a deeper area ?
1738                 if (depth != par->params().depth()) {
1739                         if (par->params().depth() > depth) {
1740                                 while (par->params().depth() > depth) {
1741                                         ++depth;
1742                                 }
1743                         } else {
1744                                 while (par->params().depth() < depth) {
1745                                         --depth;
1746                                 }
1747                         }
1748                 }
1749                 
1750                 // First write the layout
1751                 string const tmp = textclasslist.NameOfLayout(params.textclass, par->layout);
1752                 if (tmp == "Itemize") {
1753                         ltype = 1;
1754                         ltype_depth = depth + 1;
1755                 } else if (tmp == "Enumerate") {
1756                         ltype = 2;
1757                         ltype_depth = depth + 1;
1758                 } else if (contains(tmp, "ection")) {
1759                         ltype = 3;
1760                         ltype_depth = depth + 1;
1761                 } else if (contains(tmp, "aragraph")) {
1762                         ltype = 4;
1763                         ltype_depth = depth + 1;
1764                 } else if (tmp == "Description") {
1765                         ltype = 5;
1766                         ltype_depth = depth + 1;
1767                 } else if (tmp == "Abstract") {
1768                         ltype = 6;
1769                         ltype_depth = 0;
1770                 } else if (tmp == "Bibliography") {
1771                         ltype = 7;
1772                         ltype_depth = 0;
1773                 } else {
1774                         ltype = 0;
1775                         ltype_depth = 0;
1776                 }
1777                 
1778                 /* maybe some vertical spaces */ 
1779                 
1780                 /* the labelwidthstring used in lists */ 
1781                 
1782                 /* some lines? */ 
1783                 
1784                 /* some pagebreaks? */ 
1785                 
1786                 /* noindent ? */ 
1787                 
1788                 /* what about the alignment */ 
1789         } else {
1790                 lyxerr << "Should this ever happen?" << endl;
1791         }
1792
1793 #ifndef NO_LATEX
1794         LyXFont const font1 = LyXFont(LyXFont::ALL_INHERIT, params.language);
1795 #endif
1796         for (Paragraph::size_type i = 0; i < par->size(); ++i) {
1797                 if (!i && !noparbreak) {
1798                         if (linelen > 0)
1799                                 buffer << "\n\n";
1800                         for (Paragraph::depth_type j = 0; j < depth; ++j)
1801                                 buffer << "  ";
1802                         currlinelen = depth * 2;
1803                         switch (ltype) {
1804                         case 0: // Standard
1805                         case 4: // (Sub)Paragraph
1806                         case 5: // Description
1807                                 break;
1808                         case 6: // Abstract
1809                                 if (linelen > 0)
1810                                         buffer << "Abstract\n\n";
1811                                 else
1812                                         buffer << "Abstract: ";
1813                                 break;
1814                         case 7: // Bibliography
1815                                 if (!ref_printed) {
1816                                         if (linelen > 0)
1817                                                 buffer << "References\n\n";
1818                                         else
1819                                                 buffer << "References: ";
1820                                         ref_printed = true;
1821                                 }
1822                                 break;
1823                         default:
1824                                 buffer << par->params().labelString() << " ";
1825                                 break;
1826                         }
1827                         if (ltype_depth > depth) {
1828                                 for (Paragraph::depth_type j = ltype_depth - 1; 
1829                                      j > depth; --j)
1830                                         buffer << "  ";
1831                                 currlinelen += (ltype_depth-depth)*2;
1832                         }
1833                 }
1834 #ifndef NO_LATEX
1835                 LyXFont const font2 = par->getFontSettings(params, i);
1836                 if (font1.latex() != font2.latex()) {
1837                         if (font2.latex() == LyXFont::OFF)
1838                                 islatex = 0;
1839                         else
1840                                 islatex = 1;
1841                 } else {
1842                         islatex = 0;
1843                 }
1844 #endif
1845                 
1846                 char c = par->getUChar(params, i);
1847                 if (islatex)
1848                         continue;
1849                 switch (c) {
1850                 case Paragraph::META_INSET:
1851                 {
1852                         Inset const * inset = par->getInset(i);
1853                         if (inset) {
1854                                 if (!inset->ascii(this, buffer)) {
1855                                         string dummy;
1856                                         string const s =
1857                                                 rsplit(buffer.str().c_str(),
1858                                                        dummy, '\n');
1859                                         currlinelen += s.length();
1860                                 } else {
1861                                         // to be sure it breaks paragraph
1862                                         currlinelen += linelen;
1863                                 }
1864                         }
1865                 }
1866                 break;
1867                 
1868                 case Paragraph::META_NEWLINE:
1869                         if (linelen > 0) {
1870                                 buffer << "\n";
1871                                 for (Paragraph::depth_type j = 0; 
1872                                      j < depth; ++j)
1873                                         buffer << "  ";
1874                         }
1875                         currlinelen = depth * 2;
1876                         if (ltype_depth > depth) {
1877                                 for (Paragraph::depth_type j = ltype_depth;
1878                                      j > depth; --j)
1879                                         buffer << "  ";
1880                                 currlinelen += (ltype_depth - depth) * 2;
1881                         }
1882                         break;
1883                         
1884                 case Paragraph::META_HFILL: 
1885                         buffer << "\t";
1886                         break;
1887                         
1888                 case '\\':
1889                         buffer << "\\";
1890                         break;
1891                         
1892                 default:
1893                         if ((linelen > 0) && (currlinelen > (linelen - 10)) &&
1894                             (c == ' ') && ((i + 2) < par->size()))
1895                         {
1896                                 buffer << "\n";
1897                                 for (Paragraph::depth_type j = 0; 
1898                                      j < depth; ++j)
1899                                         buffer << "  ";
1900                                 currlinelen = depth * 2;
1901                                 if (ltype_depth > depth) {
1902                                         for (Paragraph::depth_type j = ltype_depth;
1903                                             j > depth; --j)
1904                                                 buffer << "  ";
1905                                         currlinelen += (ltype_depth-depth)*2;
1906                                 }
1907                         } else if (c != '\0')
1908                                 buffer << c;
1909                         else if (c == '\0')
1910                                 lyxerr[Debug::INFO] << "writeAsciiFile: NULL char in structure." << endl;
1911                         ++currlinelen;
1912                         break;
1913                 }
1914         }
1915         return buffer.str().c_str();
1916 }
1917
1918
1919 void Buffer::writeFileAscii(string const & fname, int linelen) 
1920 {
1921         ofstream ofs(fname.c_str());
1922         if (!ofs) {
1923                 WriteFSAlert(_("Error: Cannot write file:"), fname);
1924                 return;
1925         }
1926         writeFileAscii(ofs, linelen);
1927 }
1928
1929
1930 void Buffer::writeFileAscii(ostream & ofs, int linelen) 
1931 {
1932         Paragraph * par = paragraph;
1933         while (par) {
1934                 ofs << asciiParagraph(par, linelen);
1935                 par = par->next();
1936         }
1937         ofs << "\n";
1938 }
1939
1940 bool use_babel;
1941
1942 void Buffer::makeLaTeXFile(string const & fname, 
1943                            string const & original_path,
1944                            bool nice, bool only_body)
1945 {
1946         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1947         
1948         niceFile = nice; // this will be used by Insetincludes.
1949
1950         tex_code_break_column = lyxrc.ascii_linelen;
1951
1952         LyXTextClass const & tclass =
1953                 textclasslist.TextClass(params.textclass);
1954
1955         ofstream ofs(fname.c_str());
1956         if (!ofs) {
1957                 WriteFSAlert(_("Error: Cannot open file: "), fname);
1958                 return;
1959         }
1960         
1961         // validate the buffer.
1962         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1963         LaTeXFeatures features(params, tclass.numLayouts());
1964         validate(features);
1965         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1966         
1967         texrow.reset();
1968         // The starting paragraph of the coming rows is the 
1969         // first paragraph of the document. (Asger)
1970         texrow.start(paragraph, 0);
1971
1972         if (!only_body && nice) {
1973                 ofs << "%% " LYX_DOCVERSION " created this file.  "
1974                         "For more info, see http://www.lyx.org/.\n"
1975                         "%% Do not edit unless you really know what "
1976                         "you are doing.\n";
1977                 texrow.newline();
1978                 texrow.newline();
1979         }
1980         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1981         // There are a few differences between nice LaTeX and usual files:
1982         // usual is \batchmode and has a 
1983         // special input@path to allow the including of figures
1984         // with either \input or \includegraphics (what figinsets do).
1985         // batchmode is not set if there is a tex_code_break_column.
1986         // In this case somebody is interested in the generated LaTeX,
1987         // so this is OK. input@path is set when the actual parameter
1988         // original_path is set. This is done for usual tex-file, but not
1989         // for nice-latex-file. (Matthias 250696)
1990         if (!only_body) {
1991                 if (!nice){
1992                         // code for usual, NOT nice-latex-file
1993                         ofs << "\\batchmode\n"; // changed
1994                         // from \nonstopmode
1995                         texrow.newline();
1996                 }
1997                 if (!original_path.empty()) {
1998                         ofs << "\\makeatletter\n"
1999                             << "\\def\\input@path{{"
2000                             << os::external_path(original_path) << "/}}\n"
2001                             << "\\makeatother\n";
2002                         texrow.newline();
2003                         texrow.newline();
2004                         texrow.newline();
2005                 }
2006                 
2007                 ofs << "\\documentclass";
2008                 
2009                 ostringstream options; // the document class options.
2010                 
2011                 if (tokenPos(tclass.opt_fontsize(),
2012                              '|', params.fontsize) >= 0) {
2013                         // only write if existing in list (and not default)
2014                         options << params.fontsize << "pt,";
2015                 }
2016                 
2017                 
2018                 if (!params.use_geometry &&
2019                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2020                         switch (params.papersize) {
2021                         case BufferParams::PAPER_A4PAPER:
2022                                 options << "a4paper,";
2023                                 break;
2024                         case BufferParams::PAPER_USLETTER:
2025                                 options << "letterpaper,";
2026                                 break;
2027                         case BufferParams::PAPER_A5PAPER:
2028                                 options << "a5paper,";
2029                                 break;
2030                         case BufferParams::PAPER_B5PAPER:
2031                                 options << "b5paper,";
2032                                 break;
2033                         case BufferParams::PAPER_EXECUTIVEPAPER:
2034                                 options << "executivepaper,";
2035                                 break;
2036                         case BufferParams::PAPER_LEGALPAPER:
2037                                 options << "legalpaper,";
2038                                 break;
2039                         }
2040                 }
2041
2042                 // if needed
2043                 if (params.sides != tclass.sides()) {
2044                         switch (params.sides) {
2045                         case LyXTextClass::OneSide:
2046                                 options << "oneside,";
2047                                 break;
2048                         case LyXTextClass::TwoSides:
2049                                 options << "twoside,";
2050                                 break;
2051                         }
2052                 }
2053
2054                 // if needed
2055                 if (params.columns != tclass.columns()) {
2056                         if (params.columns == 2)
2057                                 options << "twocolumn,";
2058                         else
2059                                 options << "onecolumn,";
2060                 }
2061
2062                 if (!params.use_geometry 
2063                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2064                         options << "landscape,";
2065                 
2066                 // language should be a parameter to \documentclass
2067                 use_babel = false;
2068                 ostringstream language_options;
2069                 if (params.language->babel() == "hebrew"
2070                     && default_language->babel() != "hebrew")
2071                          // This seems necessary
2072                         features.UsedLanguages.insert(default_language);
2073
2074                 if (lyxrc.language_use_babel ||
2075                     params.language->lang() != lyxrc.default_language ||
2076                     !features.UsedLanguages.empty()) {
2077                         use_babel = true;
2078                         for (LaTeXFeatures::LanguageList::const_iterator cit =
2079                                      features.UsedLanguages.begin();
2080                              cit != features.UsedLanguages.end(); ++cit)
2081                                 language_options << (*cit)->babel() << ',';
2082                         language_options << params.language->babel();
2083                         if (lyxrc.language_global_options)
2084                                 options << language_options.str() << ',';
2085                 }
2086
2087                 // the user-defined options
2088                 if (!params.options.empty()) {
2089                         options << params.options << ',';
2090                 }
2091
2092                 string strOptions(options.str().c_str());
2093                 if (!strOptions.empty()){
2094                         strOptions = strip(strOptions, ',');
2095                         ofs << '[' << strOptions << ']';
2096                 }
2097                 
2098                 ofs << '{'
2099                     << textclasslist.LatexnameOfClass(params.textclass)
2100                     << "}\n";
2101                 texrow.newline();
2102                 // end of \documentclass defs
2103                 
2104                 // font selection must be done before loading fontenc.sty
2105                 // The ae package is not needed when using OT1 font encoding.
2106                 if (params.fonts != "default" &&
2107                     (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2108                         ofs << "\\usepackage{" << params.fonts << "}\n";
2109                         texrow.newline();
2110                         if (params.fonts == "ae") {
2111                                 ofs << "\\usepackage{aecompl}\n";
2112                                 texrow.newline();
2113                         }
2114                 }
2115                 // this one is not per buffer
2116                 if (lyxrc.fontenc != "default") {
2117                         ofs << "\\usepackage[" << lyxrc.fontenc
2118                             << "]{fontenc}\n";
2119                         texrow.newline();
2120                 }
2121
2122                 if (params.inputenc == "auto") {
2123                         string const doc_encoding =
2124                                 params.language->encoding()->LatexName();
2125
2126                         // Create a list with all the input encodings used 
2127                         // in the document
2128                         set<string> encodings;
2129                         for (LaTeXFeatures::LanguageList::const_iterator it =
2130                                      features.UsedLanguages.begin();
2131                              it != features.UsedLanguages.end(); ++it)
2132                                 if ((*it)->encoding()->LatexName() != doc_encoding)
2133                                         encodings.insert((*it)->encoding()->LatexName());
2134
2135                         ofs << "\\usepackage[";
2136                         std::copy(encodings.begin(), encodings.end(),
2137                                   std::ostream_iterator<string>(ofs, ","));
2138                         ofs << doc_encoding << "]{inputenc}\n";
2139                         texrow.newline();
2140                 } else if (params.inputenc != "default") {
2141                         ofs << "\\usepackage[" << params.inputenc
2142                             << "]{inputenc}\n";
2143                         texrow.newline();
2144                 }
2145
2146                 // At the very beginning the text parameters.
2147                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2148                         switch (params.paperpackage) {
2149                         case BufferParams::PACKAGE_A4:
2150                                 ofs << "\\usepackage{a4}\n";
2151                                 texrow.newline();
2152                                 break;
2153                         case BufferParams::PACKAGE_A4WIDE:
2154                                 ofs << "\\usepackage{a4wide}\n";
2155                                 texrow.newline();
2156                                 break;
2157                         case BufferParams::PACKAGE_WIDEMARGINSA4:
2158                                 ofs << "\\usepackage[widemargins]{a4}\n";
2159                                 texrow.newline();
2160                                 break;
2161                         }
2162                 }
2163                 if (params.use_geometry) {
2164                         ofs << "\\usepackage{geometry}\n";
2165                         texrow.newline();
2166                         ofs << "\\geometry{verbose";
2167                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2168                                 ofs << ",landscape";
2169                         switch (params.papersize2) {
2170                         case BufferParams::VM_PAPER_CUSTOM:
2171                                 if (!params.paperwidth.empty())
2172                                         ofs << ",paperwidth="
2173                                             << params.paperwidth;
2174                                 if (!params.paperheight.empty())
2175                                         ofs << ",paperheight="
2176                                             << params.paperheight;
2177                                 break;
2178                         case BufferParams::VM_PAPER_USLETTER:
2179                                 ofs << ",letterpaper";
2180                                 break;
2181                         case BufferParams::VM_PAPER_USLEGAL:
2182                                 ofs << ",legalpaper";
2183                                 break;
2184                         case BufferParams::VM_PAPER_USEXECUTIVE:
2185                                 ofs << ",executivepaper";
2186                                 break;
2187                         case BufferParams::VM_PAPER_A3:
2188                                 ofs << ",a3paper";
2189                                 break;
2190                         case BufferParams::VM_PAPER_A4:
2191                                 ofs << ",a4paper";
2192                                 break;
2193                         case BufferParams::VM_PAPER_A5:
2194                                 ofs << ",a5paper";
2195                                 break;
2196                         case BufferParams::VM_PAPER_B3:
2197                                 ofs << ",b3paper";
2198                                 break;
2199                         case BufferParams::VM_PAPER_B4:
2200                                 ofs << ",b4paper";
2201                                 break;
2202                         case BufferParams::VM_PAPER_B5:
2203                                 ofs << ",b5paper";
2204                                 break;
2205                         default:
2206                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2207                                 switch (lyxrc.default_papersize) {
2208                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2209                                 case BufferParams::PAPER_USLETTER:
2210                                         ofs << ",letterpaper";
2211                                         break;
2212                                 case BufferParams::PAPER_LEGALPAPER:
2213                                         ofs << ",legalpaper";
2214                                         break;
2215                                 case BufferParams::PAPER_EXECUTIVEPAPER:
2216                                         ofs << ",executivepaper";
2217                                         break;
2218                                 case BufferParams::PAPER_A3PAPER:
2219                                         ofs << ",a3paper";
2220                                         break;
2221                                 case BufferParams::PAPER_A4PAPER:
2222                                         ofs << ",a4paper";
2223                                         break;
2224                                 case BufferParams::PAPER_A5PAPER:
2225                                         ofs << ",a5paper";
2226                                         break;
2227                                 case BufferParams::PAPER_B5PAPER:
2228                                         ofs << ",b5paper";
2229                                         break;
2230                                 }
2231                         }
2232                         if (!params.topmargin.empty())
2233                                 ofs << ",tmargin=" << params.topmargin;
2234                         if (!params.bottommargin.empty())
2235                                 ofs << ",bmargin=" << params.bottommargin;
2236                         if (!params.leftmargin.empty())
2237                                 ofs << ",lmargin=" << params.leftmargin;
2238                         if (!params.rightmargin.empty())
2239                                 ofs << ",rmargin=" << params.rightmargin;
2240                         if (!params.headheight.empty())
2241                                 ofs << ",headheight=" << params.headheight;
2242                         if (!params.headsep.empty())
2243                                 ofs << ",headsep=" << params.headsep;
2244                         if (!params.footskip.empty())
2245                                 ofs << ",footskip=" << params.footskip;
2246                         ofs << "}\n";
2247                         texrow.newline();
2248                 }
2249                 if (features.amsstyle
2250                     && !tclass.provides(LyXTextClass::amsmath)) {
2251                         ofs << "\\usepackage{amsmath}\n";
2252                         texrow.newline();
2253                 }
2254
2255                 if (tokenPos(tclass.opt_pagestyle(),
2256                              '|', params.pagestyle) >= 0) {
2257                         if (params.pagestyle == "fancy") {
2258                                 ofs << "\\usepackage{fancyhdr}\n";
2259                                 texrow.newline();
2260                         }
2261                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2262                         texrow.newline();
2263                 }
2264
2265                 // We try to load babel late, in case it interferes
2266                 // with other packages.
2267                 if (use_babel) {
2268                         string tmp = lyxrc.language_package;
2269                         if (!lyxrc.language_global_options
2270                             && tmp == "\\usepackage{babel}")
2271                                 tmp = string("\\usepackage[") +
2272                                         language_options.str().c_str() +
2273                                         "]{babel}";
2274                         ofs << tmp << "\n";
2275                         texrow.newline();
2276                 }
2277
2278                 if (params.secnumdepth != tclass.secnumdepth()) {
2279                         ofs << "\\setcounter{secnumdepth}{"
2280                             << params.secnumdepth
2281                             << "}\n";
2282                         texrow.newline();
2283                 }
2284                 if (params.tocdepth != tclass.tocdepth()) {
2285                         ofs << "\\setcounter{tocdepth}{"
2286                             << params.tocdepth
2287                             << "}\n";
2288                         texrow.newline();
2289                 }
2290                 
2291                 if (params.paragraph_separation) {
2292                         switch (params.defskip.kind()) {
2293                         case VSpace::SMALLSKIP: 
2294                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2295                                 break;
2296                         case VSpace::MEDSKIP:
2297                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2298                                 break;
2299                         case VSpace::BIGSKIP:
2300                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2301                                 break;
2302                         case VSpace::LENGTH:
2303                                 ofs << "\\setlength\\parskip{"
2304                                     << params.defskip.length().asLatexString()
2305                                     << "}\n";
2306                                 break;
2307                         default: // should never happen // Then delete it.
2308                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2309                                 break;
2310                         }
2311                         texrow.newline();
2312                         
2313                         ofs << "\\setlength\\parindent{0pt}\n";
2314                         texrow.newline();
2315                 }
2316
2317                 // Now insert the LyX specific LaTeX commands...
2318
2319                 // The optional packages;
2320                 string preamble(features.getPackages());
2321
2322                 // this might be useful...
2323                 preamble += "\n\\makeatletter\n";
2324
2325                 // Some macros LyX will need
2326                 string tmppreamble(features.getMacros());
2327
2328                 if (!tmppreamble.empty()) {
2329                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2330                                 "LyX specific LaTeX commands.\n"
2331                                 + tmppreamble + '\n';
2332                 }
2333
2334                 // the text class specific preamble 
2335                 tmppreamble = features.getTClassPreamble();
2336                 if (!tmppreamble.empty()) {
2337                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2338                                 "Textclass specific LaTeX commands.\n"
2339                                 + tmppreamble + '\n';
2340                 }
2341
2342                 /* the user-defined preamble */
2343                 if (!params.preamble.empty()) {
2344                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2345                                 "User specified LaTeX commands.\n"
2346                                 + params.preamble + '\n';
2347                 }
2348
2349                 preamble += "\\makeatother\n";
2350
2351                 // Itemize bullet settings need to be last in case the user
2352                 // defines their own bullets that use a package included
2353                 // in the user-defined preamble -- ARRae
2354                 // Actually it has to be done much later than that
2355                 // since some packages like frenchb make modifications
2356                 // at \begin{document} time -- JMarc 
2357                 string bullets_def;
2358                 for (int i = 0; i < 4; ++i) {
2359                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2360                                 if (bullets_def.empty())
2361                                         bullets_def="\\AtBeginDocument{\n";
2362                                 bullets_def += "  \\renewcommand{\\labelitemi";
2363                                 switch (i) {
2364                                 // `i' is one less than the item to modify
2365                                 case 0:
2366                                         break;
2367                                 case 1:
2368                                         bullets_def += 'i';
2369                                         break;
2370                                 case 2:
2371                                         bullets_def += "ii";
2372                                         break;
2373                                 case 3:
2374                                         bullets_def += 'v';
2375                                         break;
2376                                 }
2377                                 bullets_def += "}{" + 
2378                                   params.user_defined_bullets[i].getText() 
2379                                   + "}\n";
2380                         }
2381                 }
2382
2383                 if (!bullets_def.empty())
2384                   preamble += bullets_def + "}\n\n";
2385
2386                 for (int j = countChar(preamble, '\n'); j-- ;) {
2387                         texrow.newline();
2388                 }
2389
2390                 ofs << preamble;
2391
2392                 // make the body.
2393                 ofs << "\\begin{document}\n";
2394                 texrow.newline();
2395         } // only_body
2396         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2397
2398         if (!lyxrc.language_auto_begin) {
2399                 ofs << subst(lyxrc.language_command_begin, "$$lang",
2400                              params.language->babel())
2401                     << endl;
2402                 texrow.newline();
2403         }
2404         
2405         latexParagraphs(ofs, paragraph, 0, texrow);
2406
2407         // add this just in case after all the paragraphs
2408         ofs << endl;
2409         texrow.newline();
2410
2411         if (!lyxrc.language_auto_end) {
2412                 ofs << subst(lyxrc.language_command_end, "$$lang",
2413                              params.language->babel())
2414                     << endl;
2415                 texrow.newline();
2416         }
2417
2418         if (!only_body) {
2419                 ofs << "\\end{document}\n";
2420                 texrow.newline();
2421         
2422                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2423         } else {
2424                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2425                                      << endl;
2426         }
2427
2428         // Just to be sure. (Asger)
2429         texrow.newline();
2430
2431         // tex_code_break_column's value is used to decide
2432         // if we are in batchmode or not (within mathed_write()
2433         // in math_write.C) so we must set it to a non-zero
2434         // value when we leave otherwise we save incorrect .lyx files.
2435         tex_code_break_column = lyxrc.ascii_linelen;
2436
2437         ofs.close();
2438         if (ofs.fail()) {
2439                 lyxerr << "File was not closed properly." << endl;
2440         }
2441         
2442         lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2443 }
2444
2445
2446 //
2447 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2448 //
2449 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2450                              Paragraph * endpar, TexRow & texrow) const
2451 {
2452         bool was_title = false;
2453         bool already_title = false;
2454
2455         // if only_body
2456         while (par != endpar) {
2457                 LyXLayout const & layout =
2458                         textclasslist.Style(params.textclass,
2459                                             par->layout);
2460             
2461                 if (layout.intitle) {
2462                         if (already_title) {
2463                                 lyxerr <<"Error in latexParagraphs: You"
2464                                         " should not mix title layouts"
2465                                         " with normal ones." << endl;
2466                         } else
2467                                 was_title = true;
2468                 } else if (was_title && !already_title) {
2469                         ofs << "\\maketitle\n";
2470                         texrow.newline();
2471                         already_title = true;
2472                         was_title = false;                  
2473                 }
2474                 
2475                 if (layout.isEnvironment()) {
2476                         par = par->TeXEnvironment(this, params, ofs, texrow);
2477                 } else {
2478                         par = par->TeXOnePar(this, params, ofs, texrow, false);
2479                 }
2480         }
2481         // It might be that we only have a title in this document
2482         if (was_title && !already_title) {
2483                 ofs << "\\maketitle\n";
2484                 texrow.newline();
2485         }
2486 }
2487
2488
2489 bool Buffer::isLatex() const
2490 {
2491         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2492 }
2493
2494
2495 bool Buffer::isLinuxDoc() const
2496 {
2497         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2498 }
2499
2500
2501 bool Buffer::isLiterate() const
2502 {
2503         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2504 }
2505
2506
2507 bool Buffer::isDocBook() const
2508 {
2509         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2510 }
2511
2512
2513 bool Buffer::isSGML() const
2514 {
2515         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2516                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2517 }
2518
2519
2520 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2521                          string const & latexname) const
2522 {
2523         if (!latexname.empty() && latexname != "!-- --")
2524                 os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2525         //os << string(depth, ' ') << "<" << latexname << ">\n";
2526 }
2527
2528
2529 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2530                           string const & latexname) const
2531 {
2532         if (!latexname.empty() && latexname != "!-- --")
2533                 os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2534         //os << string(depth, ' ') << "</" << latexname << ">\n";
2535 }
2536
2537
2538 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2539 {
2540         ofstream ofs(fname.c_str());
2541
2542         if (!ofs) {
2543                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2544                 return;
2545         }
2546
2547         niceFile = nice; // this will be used by included files.
2548
2549         LyXTextClass const & tclass =
2550                 textclasslist.TextClass(params.textclass);
2551
2552         LaTeXFeatures features(params, tclass.numLayouts());
2553         validate(features);
2554
2555         texrow.reset();
2556
2557         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2558
2559         if (!body_only) {
2560                 string sgml_includedfiles=features.getIncludedFiles(fname);
2561
2562                 if (params.preamble.empty() && sgml_includedfiles.empty()) {
2563                         ofs << "<!doctype linuxdoc system>\n\n";
2564                 } else {
2565                         ofs << "<!doctype linuxdoc system [ "
2566                             << params.preamble << sgml_includedfiles << " \n]>\n\n";
2567                 }
2568
2569                 if (params.options.empty())
2570                         sgmlOpenTag(ofs, 0, top_element);
2571                 else {
2572                         string top = top_element;
2573                         top += " ";
2574                         top += params.options;
2575                         sgmlOpenTag(ofs, 0, top);
2576                 }
2577         }
2578
2579         ofs << "<!-- "  << LYX_DOCVERSION 
2580             << " created this file. For more info see http://www.lyx.org/"
2581             << " -->\n";
2582
2583         Paragraph::depth_type depth = 0; // paragraph depth
2584         Paragraph * par = paragraph;
2585         string item_name;
2586         vector<string> environment_stack(5);
2587
2588         while (par) {
2589                 LyXLayout const & style =
2590                         textclasslist.Style(params.textclass,
2591                                             par->layout);
2592
2593                 // treat <toc> as a special case for compatibility with old code
2594                 if (par->getChar(0) == Paragraph::META_INSET) {
2595                         Inset * inset = par->getInset(0);
2596                         Inset::Code lyx_code = inset->lyxCode();
2597                         if (lyx_code == Inset::TOC_CODE){
2598                                 string const temp = "toc";
2599                                 sgmlOpenTag(ofs, depth, temp);
2600
2601                                 par = par->next();
2602                                 continue;
2603                         }
2604                 }
2605
2606                 // environment tag closing
2607                 for (; depth > par->params().depth(); --depth) {
2608                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2609                         environment_stack[depth].erase();
2610                 }
2611
2612                 // write opening SGML tags
2613                 switch (style.latextype) {
2614                 case LATEX_PARAGRAPH:
2615                         if (depth == par->params().depth() 
2616                            && !environment_stack[depth].empty()) {
2617                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2618                                 environment_stack[depth].erase();
2619                                 if (depth) 
2620                                         --depth;
2621                                 else
2622                                         ofs << "</p>";
2623                         }
2624                         sgmlOpenTag(ofs, depth, style.latexname());
2625                         break;
2626
2627                 case LATEX_COMMAND:
2628                         if (depth!= 0)
2629                                 linuxDocError(par, 0,
2630                                               _("Error : Wrong depth for"
2631                                                 " LatexType Command.\n"));
2632
2633                         if (!environment_stack[depth].empty()){
2634                                 sgmlCloseTag(ofs, depth,
2635                                              environment_stack[depth]);
2636                                 ofs << "</p>";
2637                         }
2638
2639                         environment_stack[depth].erase();
2640                         sgmlOpenTag(ofs, depth, style.latexname());
2641                         break;
2642
2643                 case LATEX_ENVIRONMENT:
2644                 case LATEX_ITEM_ENVIRONMENT:
2645                         if (depth == par->params().depth() 
2646                             && environment_stack[depth] != style.latexname()) {
2647                                 sgmlCloseTag(ofs, depth,
2648                                              environment_stack[depth]);
2649                                 environment_stack[depth].erase();
2650                         }
2651                         if (depth < par->params().depth()) {
2652                                depth = par->params().depth();
2653                                environment_stack[depth].erase();
2654                         }
2655                         if (environment_stack[depth] != style.latexname()) {
2656                                 if (depth == 0) {
2657                                         sgmlOpenTag(ofs, depth, "p");
2658                                 }
2659                                 sgmlOpenTag(ofs, depth, style.latexname());
2660
2661                                 if (environment_stack.size() == depth + 1)
2662                                         environment_stack.push_back("!-- --");
2663                                 environment_stack[depth] = style.latexname();
2664                         }
2665
2666                         if (style.latexparam() == "CDATA")
2667                                 ofs << "<![CDATA[";
2668
2669                         if (style.latextype == LATEX_ENVIRONMENT) break;
2670
2671                         if (style.labeltype == LABEL_MANUAL)
2672                                 item_name = "tag";
2673                         else
2674                                 item_name = "item";
2675
2676                         sgmlOpenTag(ofs, depth + 1, item_name);
2677                         break;
2678                 default:
2679                         sgmlOpenTag(ofs, depth, style.latexname());
2680                         break;
2681                 }
2682
2683                 simpleLinuxDocOnePar(ofs, par, depth);
2684
2685                 par = par->next();
2686
2687                 ofs << "\n";
2688                 // write closing SGML tags
2689                 switch (style.latextype) {
2690                 case LATEX_COMMAND:
2691                         break;
2692                 case LATEX_ENVIRONMENT:
2693                 case LATEX_ITEM_ENVIRONMENT:
2694                         if (style.latexparam() == "CDATA")
2695                                 ofs << "]]>";
2696                         break;
2697                 default:
2698                         sgmlCloseTag(ofs, depth, style.latexname());
2699                         break;
2700                 }
2701         }
2702    
2703         // Close open tags
2704         for (int i=depth; i >= 0; --i)
2705                 sgmlCloseTag(ofs, depth, environment_stack[i]);
2706
2707         if (!body_only) {
2708                 ofs << "\n\n";
2709                 sgmlCloseTag(ofs, 0, top_element);
2710         }
2711
2712         ofs.close();
2713         // How to check for successful close
2714 }
2715
2716
2717 void Buffer::docBookHandleCaption(ostream & os, string & inner_tag,
2718                                   Paragraph::depth_type depth, int desc_on,
2719                                   Paragraph * & par)
2720 {
2721         Paragraph * tpar = par;
2722         while (tpar
2723                && (tpar->layout != textclasslist.NumberOfLayout(params.textclass,
2724                                                                 "Caption").second))
2725                 tpar = tpar->next();
2726
2727         if (tpar &&
2728             tpar->layout == textclasslist.NumberOfLayout(params.textclass,
2729                                                          "Caption").second) {
2730                 sgmlOpenTag(os, depth + 1, inner_tag);
2731                 string extra_par;
2732                 simpleDocBookOnePar(os, extra_par, tpar,
2733                                     desc_on, depth + 2);
2734                 sgmlCloseTag(os, depth+1, inner_tag);
2735                 if (!extra_par.empty())
2736                         os << extra_par;
2737         }
2738 }
2739
2740
2741 // checks, if newcol chars should be put into this line
2742 // writes newline, if necessary.
2743 namespace {
2744
2745 void linux_doc_line_break(ostream & os, string::size_type & colcount,
2746                           string::size_type newcol)
2747 {
2748         colcount += newcol;
2749         if (colcount > lyxrc.ascii_linelen) {
2750                 os << "\n";
2751                 colcount = newcol; // assume write after this call
2752         }
2753 }
2754
2755 enum PAR_TAG {
2756         NONE=0,
2757         TT = 1,
2758         SF = 2,
2759         BF = 4,
2760         IT = 8,
2761         SL = 16,
2762         EM = 32
2763 };
2764
2765
2766 string tag_name(PAR_TAG const & pt) {
2767         switch (pt) {
2768         case NONE: return "!-- --";
2769         case TT: return "tt";
2770         case SF: return "sf";
2771         case BF: return "bf";
2772         case IT: return "it";
2773         case SL: return "sl";
2774         case EM: return "em";
2775         }
2776         return "";
2777 }
2778
2779
2780 inline
2781 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2782 {
2783         p1 = static_cast<PAR_TAG>(p1 | p2);
2784 }
2785
2786
2787 inline
2788 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2789 {
2790         p1 = static_cast<PAR_TAG>( p1 & ~p2);
2791 }
2792
2793 } // namespace anon
2794
2795
2796
2797
2798 // Handle internal paragraph parsing -- layout already processed.
2799 void Buffer::simpleLinuxDocOnePar(ostream & os,
2800                                   Paragraph * par, 
2801                                   Paragraph::depth_type /*depth*/)
2802 {
2803         LyXLayout const & style = textclasslist.Style(params.textclass,
2804                                                       par->getLayout());
2805         string::size_type char_line_count = 5;     // Heuristic choice ;-) 
2806
2807         // gets paragraph main font
2808         LyXFont font_old;
2809         bool desc_on;
2810         if (style.labeltype == LABEL_MANUAL) {
2811                 font_old = style.labelfont;
2812                 desc_on = true;
2813         } else {
2814                 font_old = style.font;
2815                 desc_on = false;
2816         }
2817
2818         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2819         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2820         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
2821         bool is_em = false;
2822
2823         stack < PAR_TAG > tag_state;
2824         // parsing main loop
2825         for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2826
2827                 PAR_TAG tag_close = NONE;
2828                 list < PAR_TAG > tag_open;
2829
2830                 LyXFont const font = par->getFont(params, i);
2831
2832                 if (font_old.family() != font.family()) {
2833                         switch (family_type) {
2834                         case LyXFont::SANS_FAMILY:
2835                                 tag_close |= SF;
2836                                 break;
2837                         case LyXFont::TYPEWRITER_FAMILY:
2838                                 tag_close |= TT;
2839                                 break;
2840                         default:
2841                                 break;
2842                         }
2843
2844                         family_type = font.family();
2845
2846                         switch (family_type) {
2847                         case LyXFont::SANS_FAMILY:
2848                                 tag_open.push_back(SF);
2849                                 break;
2850                         case LyXFont::TYPEWRITER_FAMILY:
2851                                 tag_open.push_back(TT);
2852                                 break;
2853                         default:
2854                                 break;
2855                         }
2856                 }
2857
2858                 if (font_old.series() != font.series()) {
2859                         switch (series_type) {
2860                         case LyXFont::BOLD_SERIES:
2861                                 tag_close |= BF;
2862                                 break;
2863                         default:
2864                                 break;
2865                         }
2866
2867                         series_type = font.series();
2868
2869                         switch (series_type) {
2870                         case LyXFont::BOLD_SERIES:
2871                                 tag_open.push_back(BF);
2872                                 break;
2873                         default:
2874                                 break;
2875                         }
2876
2877                 }
2878
2879                 if (font_old.shape() != font.shape()) {
2880                         switch (shape_type) {
2881                         case LyXFont::ITALIC_SHAPE:
2882                                 tag_close |= IT;
2883                                 break;
2884                         case LyXFont::SLANTED_SHAPE:
2885                                 tag_close |= SL;
2886                                 break;
2887                         default:
2888                                 break;
2889                         }
2890
2891                         shape_type = font.shape();
2892
2893                         switch (shape_type) {
2894                         case LyXFont::ITALIC_SHAPE:
2895                                 tag_open.push_back(IT);
2896                                 break;
2897                         case LyXFont::SLANTED_SHAPE:
2898                                 tag_open.push_back(SL);
2899                                 break;
2900                         default:
2901                                 break;
2902                         }
2903                 }
2904                 // handle <em> tag
2905                 if (font_old.emph() != font.emph()) {
2906                         if (font.emph() == LyXFont::ON) {
2907                                 tag_open.push_back(EM);
2908                                 is_em = true;
2909                         }
2910                         else if (is_em) {
2911                                 tag_close |= EM;
2912                                 is_em = false;
2913                         }
2914                 }
2915
2916                 list < PAR_TAG > temp;
2917                 while(!tag_state.empty() && tag_close ) {
2918                         PAR_TAG k =  tag_state.top();
2919                         tag_state.pop();
2920                         os << "</" << tag_name(k) << ">";
2921                         if (tag_close & k)
2922                                 reset(tag_close,k);
2923                         else
2924                                 temp.push_back(k);
2925                 }
2926
2927                 for(list< PAR_TAG >::const_iterator j = temp.begin();
2928                     j != temp.end(); ++j) {
2929                         tag_state.push(*j);
2930                         os << "<" << tag_name(*j) << ">";
2931                 }
2932
2933                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2934                     j != tag_open.end(); ++j) {
2935                         tag_state.push(*j);
2936                         os << "<" << tag_name(*j) << ">";
2937                 }
2938
2939                 char c = par->getChar(i);
2940
2941                 if (c == Paragraph::META_INSET) {
2942                         Inset * inset = par->getInset(i);
2943                         inset->linuxdoc(this, os);
2944                         font_old = font;
2945                         continue;
2946                 }
2947
2948                 if (
2949 #ifndef NO_LATEX
2950                         font.latex() == LyXFont::ON ||
2951 #endif
2952                     style.latexparam() == "CDATA") {
2953                         // "TeX"-Mode on == > SGML-Mode on.
2954                         if (c != '\0')
2955                                 os << c;
2956                         ++char_line_count;
2957                 } else {
2958                         string sgml_string;
2959                         if (par->linuxDocConvertChar(c, sgml_string)
2960                             && !style.free_spacing) { 
2961                                 // in freespacing mode, spaces are
2962                                 // non-breaking characters
2963                                 if (desc_on) {// if char is ' ' then...
2964
2965                                         ++char_line_count;
2966                                         linux_doc_line_break(os, char_line_count, 6);
2967                                         os << "</tag>";
2968                                         desc_on = false;
2969                                 } else  {
2970                                         linux_doc_line_break(os, char_line_count, 1);
2971                                         os << c;
2972                                 }
2973                         } else {
2974                                 os << sgml_string;
2975                                 char_line_count += sgml_string.length();
2976                         }
2977                 }
2978                 font_old = font;
2979         }
2980
2981         while (!tag_state.empty()) {
2982                 os << "</" << tag_name(tag_state.top()) << ">";
2983                 tag_state.pop();
2984         }
2985
2986         // resets description flag correctly
2987         if (desc_on) {
2988                 // <tag> not closed...
2989                 linux_doc_line_break(os, char_line_count, 6);
2990                 os << "</tag>";
2991         }
2992 }
2993
2994
2995 // Print an error message.
2996 void Buffer::linuxDocError(Paragraph * par, int pos,
2997                            string const & message) 
2998 {
2999         // insert an error marker in text
3000         InsetError * new_inset = new InsetError(message);
3001         par->insertInset(pos, new_inset);
3002 }
3003
3004
3005 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3006 {
3007         ofstream ofs(fname.c_str());
3008         if (!ofs) {
3009                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3010                 return;
3011         }
3012
3013         Paragraph * par = paragraph;
3014
3015         niceFile = nice; // this will be used by Insetincludes.
3016
3017         LyXTextClass const & tclass =
3018                 textclasslist.TextClass(params.textclass);
3019
3020         LaTeXFeatures features(params, tclass.numLayouts());
3021         validate(features);
3022    
3023         texrow.reset();
3024
3025         string top_element = textclasslist.LatexnameOfClass(params.textclass);
3026
3027         if (!only_body) {
3028                 string sgml_includedfiles = features.getIncludedFiles(fname);
3029
3030                 ofs << "<!doctype " << top_element
3031                     << " public \"-//OASIS//DTD DocBook V3.1//EN\"";
3032
3033                 if (params.preamble.empty() && sgml_includedfiles.empty())
3034                         ofs << ">\n\n";
3035                 else
3036                         ofs << "\n [ " << params.preamble 
3037                             << sgml_includedfiles << " \n]>\n\n";
3038         }
3039
3040         string top = top_element;       
3041         top += " lang=\"";
3042         top += params.language->code();
3043         top += "\"";
3044
3045         if (!params.options.empty()) {
3046                 top += " ";
3047                 top += params.options;
3048         }
3049         sgmlOpenTag(ofs, 0, top);
3050
3051         ofs << "<!-- DocBook file was created by " << LYX_DOCVERSION 
3052             << "\n  See http://www.lyx.org/ for more information -->\n";
3053
3054         vector<string> environment_stack(10);
3055         vector<string> environment_inner(10);
3056         vector<string> command_stack(10);
3057
3058         bool command_flag = false;
3059         Paragraph::depth_type command_depth = 0;
3060         Paragraph::depth_type command_base = 0;
3061         Paragraph::depth_type cmd_depth = 0;
3062         Paragraph::depth_type depth = 0; // paragraph depth
3063
3064         string item_name;
3065         string command_name;
3066
3067         while (par) {
3068                 string sgmlparam;
3069                 string c_depth;
3070                 string c_params;
3071                 int desc_on = 0; // description mode
3072
3073                 LyXLayout const & style =
3074                         textclasslist.Style(params.textclass,
3075                                             par->layout);
3076
3077                 // environment tag closing
3078                 for (; depth > par->params().depth(); --depth) {
3079                         if (environment_inner[depth] != "!-- --") {
3080                                 item_name = "listitem";
3081                                 sgmlCloseTag(ofs, command_depth + depth,
3082                                              item_name);
3083                                 if (environment_inner[depth] == "varlistentry")
3084                                         sgmlCloseTag(ofs, depth+command_depth,
3085                                                      environment_inner[depth]);
3086                         }
3087                         sgmlCloseTag(ofs, depth + command_depth,
3088                                      environment_stack[depth]);
3089                         environment_stack[depth].erase();
3090                         environment_inner[depth].erase();
3091                 }
3092
3093                 if (depth == par->params().depth()
3094                    && environment_stack[depth] != style.latexname()
3095                    && !environment_stack[depth].empty()) {
3096                         if (environment_inner[depth] != "!-- --") {
3097                                 item_name= "listitem";
3098                                 sgmlCloseTag(ofs, command_depth+depth,
3099                                              item_name);
3100                                 if (environment_inner[depth] == "varlistentry")
3101                                         sgmlCloseTag(ofs,
3102                                                      depth + command_depth,
3103                                                      environment_inner[depth]);
3104                         }
3105                         
3106                         sgmlCloseTag(ofs, depth + command_depth,
3107                                      environment_stack[depth]);
3108                         
3109                         environment_stack[depth].erase();
3110                         environment_inner[depth].erase();
3111                 }
3112
3113                 // Write opening SGML tags.
3114                 switch (style.latextype) {
3115                 case LATEX_PARAGRAPH:
3116                         sgmlOpenTag(ofs, depth + command_depth,
3117                                     style.latexname());
3118                         break;
3119
3120                 case LATEX_COMMAND:
3121                         if (depth != 0)
3122                                 linuxDocError(par, 0,
3123                                               _("Error : Wrong depth for "
3124                                                 "LatexType Command.\n"));
3125                         
3126                         command_name = style.latexname();
3127                         
3128                         sgmlparam = style.latexparam();
3129                         c_params = split(sgmlparam, c_depth,'|');
3130                         
3131                         cmd_depth = lyx::atoi(c_depth);
3132                         
3133                         if (command_flag) {
3134                                 if (cmd_depth < command_base) {
3135                                         for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3136                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3137                                         command_depth = command_base = cmd_depth;
3138                                 } else if (cmd_depth <= command_depth) {
3139                                         for (int j = command_depth; j >= int(cmd_depth); --j)
3140                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3141                                         command_depth = cmd_depth;
3142                                 } else
3143                                         command_depth = cmd_depth;
3144                         } else {
3145                                 command_depth = command_base = cmd_depth;
3146                                 command_flag = true;
3147                         }
3148                         if (command_stack.size() == command_depth + 1)
3149                                 command_stack.push_back(string());
3150                         command_stack[command_depth] = command_name;
3151
3152                         // treat label as a special case for
3153                         // more WYSIWYM handling.
3154                         if (par->getChar(0) == Paragraph::META_INSET) {
3155                                 Inset * inset = par->getInset(0);
3156                                 Inset::Code lyx_code = inset->lyxCode();
3157                                 if (lyx_code == Inset::LABEL_CODE){
3158                                         command_name += " id=\"";
3159                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3160                                         command_name += "\"";
3161                                         desc_on = 3;
3162                                 }
3163                         }
3164
3165                         sgmlOpenTag(ofs, depth + command_depth, command_name);
3166                         if (c_params.empty())
3167                                 item_name = "title";
3168                         else
3169                                 item_name = c_params;
3170                         sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3171                         break;
3172
3173                 case LATEX_ENVIRONMENT:
3174                 case LATEX_ITEM_ENVIRONMENT:
3175                         if (depth < par->params().depth()) {
3176                                 depth = par->params().depth();
3177                                 environment_stack[depth].erase();
3178                         }
3179
3180                         if (environment_stack[depth] != style.latexname()) {
3181                                 if(environment_stack.size() == depth + 1) {
3182                                         environment_stack.push_back("!-- --");
3183                                         environment_inner.push_back("!-- --");
3184                                 }
3185                                 environment_stack[depth] = style.latexname();
3186                                 environment_inner[depth] = "!-- --";
3187                                 sgmlOpenTag(ofs, depth + command_depth,
3188                                             environment_stack[depth]);
3189                         } else {
3190                                 if (environment_inner[depth] != "!-- --") {
3191                                         item_name= "listitem";
3192                                         sgmlCloseTag(ofs,
3193                                                      command_depth + depth,
3194                                                      item_name);
3195                                         if (environment_inner[depth] == "varlistentry")
3196                                                 sgmlCloseTag(ofs,
3197                                                              depth + command_depth,
3198                                                              environment_inner[depth]);
3199                                 }
3200                         }
3201                         
3202                         if (style.latextype == LATEX_ENVIRONMENT) {
3203                                 if (!style.latexparam().empty()) {
3204                                         if(style.latexparam() == "CDATA")
3205                                                 ofs << "<![CDATA[";
3206                                         else
3207                                                 sgmlOpenTag(ofs, depth + command_depth,
3208                                                             style.latexparam());
3209                                 }
3210                                 break;
3211                         }
3212
3213                         desc_on = (style.labeltype == LABEL_MANUAL);
3214
3215                         if (desc_on)
3216                                 environment_inner[depth]= "varlistentry";
3217                         else
3218                                 environment_inner[depth]= "listitem";
3219
3220                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3221                                     environment_inner[depth]);
3222
3223                         if (desc_on) {
3224                                 item_name= "term";
3225                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3226                                             item_name);
3227                         } else {
3228                                 item_name= "para";
3229                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3230                                             item_name);
3231                         }
3232                         break;
3233                 default:
3234                         sgmlOpenTag(ofs, depth + command_depth,
3235                                     style.latexname());
3236                         break;
3237                 }
3238
3239                 string extra_par;
3240                 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3241                                     depth + 1 + command_depth);
3242                 par = par->next();
3243
3244                 string end_tag;
3245                 // write closing SGML tags
3246                 switch (style.latextype) {
3247                 case LATEX_COMMAND:
3248                         if (c_params.empty())
3249                                 end_tag = "title";
3250                         else
3251                                 end_tag = c_params;
3252                         sgmlCloseTag(ofs, depth + command_depth, end_tag);
3253                         break;
3254                 case LATEX_ENVIRONMENT:
3255                         if (!style.latexparam().empty()) {
3256                                 if(style.latexparam() == "CDATA")
3257                                         ofs << "]]>";
3258                                 else
3259                                         sgmlCloseTag(ofs, depth + command_depth,
3260                                                      style.latexparam());
3261                         }
3262                         break;
3263                 case LATEX_ITEM_ENVIRONMENT:
3264                         if (desc_on == 1) break;
3265                         end_tag= "para";
3266                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3267                         break;
3268                 case LATEX_PARAGRAPH:
3269                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3270                         break;
3271                 default:
3272                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3273                         break;
3274                 }
3275         }
3276
3277         // Close open tags
3278         for (int d = depth; d >= 0; --d) {
3279                 if (!environment_stack[depth].empty()) {
3280                         if (environment_inner[depth] != "!-- --") {
3281                                 item_name = "listitem";
3282                                 sgmlCloseTag(ofs, command_depth + depth,
3283                                              item_name);
3284                                if (environment_inner[depth] == "varlistentry")
3285                                        sgmlCloseTag(ofs, depth + command_depth,
3286                                                     environment_inner[depth]);
3287                         }
3288                         
3289                         sgmlCloseTag(ofs, depth + command_depth,
3290                                      environment_stack[depth]);
3291                 }
3292         }
3293         
3294         for (int j = command_depth; j >= 0 ; --j)
3295                 if (!command_stack[j].empty())
3296                         sgmlCloseTag(ofs, j, command_stack[j]);
3297
3298         ofs << "\n\n";
3299         sgmlCloseTag(ofs, 0, top_element);
3300
3301         ofs.close();
3302         // How to check for successful close
3303 }
3304
3305
3306 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3307                                  Paragraph * par, int & desc_on,
3308                                  Paragraph::depth_type depth) const
3309 {
3310         bool emph_flag = false;
3311
3312         LyXLayout const & style = textclasslist.Style(params.textclass,
3313                                                       par->getLayout());
3314
3315         LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3316
3317         int char_line_count = depth;
3318         //if (!style.free_spacing)
3319         //      os << string(depth,' ');
3320
3321         // parsing main loop
3322         for (Paragraph::size_type i = 0;
3323              i < par->size(); ++i) {
3324                 LyXFont font = par->getFont(params, i);
3325
3326                 // handle <emphasis> tag
3327                 if (font_old.emph() != font.emph()) {
3328                         if (font.emph() == LyXFont::ON) {
3329                                 os << "<emphasis>";
3330                                 emph_flag = true;
3331                         }else if(i) {
3332                                 os << "</emphasis>";
3333                                 emph_flag = false;
3334                         }
3335                 }
3336       
3337                 char c = par->getChar(i);
3338
3339                 if (c == Paragraph::META_INSET) {
3340                         Inset * inset = par->getInset(i);
3341                         ostringstream ost;
3342                         inset->docBook(this, ost);
3343                         string tmp_out = ost.str().c_str();
3344
3345                         //
3346                         // This code needs some explanation:
3347                         // Two insets are treated specially
3348                         //   label if it is the first element in a command paragraph
3349                         //         desc_on == 3
3350                         //   graphics inside tables or figure floats can't go on
3351                         //   title (the equivalente in latex for this case is caption
3352                         //   and title should come first
3353                         //         desc_on == 4
3354                         //
3355                         if (desc_on!= 3 || i!= 0) {
3356                                 if (!tmp_out.empty() && tmp_out[0] == '@') {
3357                                         if (desc_on == 4)
3358                                                 extra += frontStrip(tmp_out, '@');
3359                                         else
3360                                                 os << frontStrip(tmp_out, '@');
3361                                 }
3362                                 else
3363                                         os << tmp_out;
3364                         }
3365 #ifndef NO_LATEX
3366                 } else if (font.latex() == LyXFont::ON) {
3367                         // "TeX"-Mode on ==> SGML-Mode on.
3368                         if (c != '\0')
3369                                 os << c;
3370                         ++char_line_count;
3371 #endif
3372                 } else {
3373                         string sgml_string;
3374                         if (par->linuxDocConvertChar(c, sgml_string)
3375                             && !style.free_spacing) { // in freespacing
3376                                                      // mode, spaces are
3377                                                      // non-breaking characters
3378                                 // char is ' '
3379                                 if (desc_on == 1) {
3380                                         ++char_line_count;
3381                                         os << "\n</term><listitem><para>";
3382                                         desc_on = 2;
3383                                 } else {
3384                                         os << c;
3385                                 }
3386                         } else {
3387                                 os << sgml_string;
3388                         }
3389                 }
3390                 font_old = font;
3391         }
3392
3393         if (emph_flag) {
3394                 os << "</emphasis>";
3395         }
3396         
3397         // resets description flag correctly
3398         if (desc_on == 1) {
3399                 // <term> not closed...
3400                 os << "</term>";
3401         }
3402         if(style.free_spacing) os << '\n';
3403 }
3404
3405
3406 // This should be enabled when the Chktex class is implemented. (Asger)
3407 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3408 // Other flags: -wall -v0 -x
3409 int Buffer::runChktex()
3410 {
3411         if (!users->text) return 0;
3412
3413         users->owner()->prohibitInput();
3414
3415         // get LaTeX-Filename
3416         string const name = getLatexName();
3417         string path = OnlyPath(filename);
3418
3419         string const org_path = path;
3420         if (lyxrc.use_tempdir || (IsDirWriteable(path) < 1)) {
3421                 path = tmppath;  
3422         }
3423
3424         Path p(path); // path to LaTeX file
3425         users->owner()->message(_("Running chktex..."));
3426
3427         // Remove all error insets
3428         bool const removedErrorInsets = users->removeAutoInsets();
3429
3430         // Generate the LaTeX file if neccessary
3431         makeLaTeXFile(name, org_path, false);
3432
3433         TeXErrors terr;
3434         Chktex chktex(lyxrc.chktex_command, name, filepath);
3435         int res = chktex.run(terr); // run chktex
3436
3437         if (res == -1) {
3438                 WriteAlert(_("chktex did not work!"),
3439                            _("Could not run with file:"), name);
3440         } else if (res > 0) {
3441                 // Insert all errors as errors boxes
3442                 users->insertErrors(terr);
3443         }
3444
3445         // if we removed error insets before we ran chktex or if we inserted
3446         // error insets after we ran chktex, this must be run:
3447         if (removedErrorInsets || res){
3448                 users->redraw();
3449                 users->fitCursor(users->text);
3450         }
3451         users->owner()->allowInput();
3452
3453         return res;
3454 }
3455
3456
3457 void Buffer::validate(LaTeXFeatures & features) const
3458 {
3459         Paragraph * par = paragraph;
3460         LyXTextClass const & tclass = 
3461                 textclasslist.TextClass(params.textclass);
3462     
3463         // AMS Style is at document level
3464         features.amsstyle = (params.use_amsmath ||
3465                              tclass.provides(LyXTextClass::amsmath));
3466     
3467         while (par) {
3468                 // We don't use "lyxerr.debug" because of speed. (Asger)
3469                 if (lyxerr.debugging(Debug::LATEX))
3470                         lyxerr << "Paragraph: " <<  par << endl;
3471
3472                 // Now just follow the list of paragraphs and run
3473                 // validate on each of them.
3474                 par->validate(features);
3475
3476                 // and then the next paragraph
3477                 par = par->next();
3478         }
3479
3480         // the bullet shapes are buffer level not paragraph level
3481         // so they are tested here
3482         for (int i = 0; i < 4; ++i) {
3483                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3484                         int const font = params.user_defined_bullets[i].getFont();
3485                         if (font == 0) {
3486                                 int const c = params
3487                                         .user_defined_bullets[i]
3488                                         .getCharacter();
3489                                 if (c == 16
3490                                    || c == 17
3491                                    || c == 25
3492                                    || c == 26
3493                                    || c == 31) {
3494                                         features.latexsym = true;
3495                                 }
3496                         } else if (font == 1) {
3497                                 features.amssymb = true;
3498                         } else if ((font >= 2 && font <= 5)) {
3499                                 features.pifont = true;
3500                         }
3501                 }
3502         }
3503         
3504         if (lyxerr.debugging(Debug::LATEX)) {
3505                 features.showStruct();
3506         }
3507 }
3508
3509
3510 void Buffer::setPaperStuff()
3511 {
3512         params.papersize = BufferParams::PAPER_DEFAULT;
3513         char const c1 = params.paperpackage;
3514         if (c1 == BufferParams::PACKAGE_NONE) {
3515                 char const c2 = params.papersize2;
3516                 if (c2 == BufferParams::VM_PAPER_USLETTER)
3517                         params.papersize = BufferParams::PAPER_USLETTER;
3518                 else if (c2 == BufferParams::VM_PAPER_USLEGAL)
3519                         params.papersize = BufferParams::PAPER_LEGALPAPER;
3520                 else if (c2 == BufferParams::VM_PAPER_USEXECUTIVE)
3521                         params.papersize = BufferParams::PAPER_EXECUTIVEPAPER;
3522                 else if (c2 == BufferParams::VM_PAPER_A3)
3523                         params.papersize = BufferParams::PAPER_A3PAPER;
3524                 else if (c2 == BufferParams::VM_PAPER_A4)
3525                         params.papersize = BufferParams::PAPER_A4PAPER;
3526                 else if (c2 == BufferParams::VM_PAPER_A5)
3527                         params.papersize = BufferParams::PAPER_A5PAPER;
3528                 else if ((c2 == BufferParams::VM_PAPER_B3) || (c2 == BufferParams::VM_PAPER_B4) ||
3529                          (c2 == BufferParams::VM_PAPER_B5))
3530                         params.papersize = BufferParams::PAPER_B5PAPER;
3531         } else if ((c1 == BufferParams::PACKAGE_A4) || (c1 == BufferParams::PACKAGE_A4WIDE) ||
3532                    (c1 == BufferParams::PACKAGE_WIDEMARGINSA4))
3533                 params.papersize = BufferParams::PAPER_A4PAPER;
3534 }
3535
3536
3537 // This function should be in Buffer because it's a buffer's property (ale)
3538 string const Buffer::getIncludeonlyList(char delim)
3539 {
3540         string lst;
3541         for (inset_iterator it = inset_iterator_begin();
3542             it != inset_iterator_end(); ++it) {
3543                 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3544                         InsetInclude * insetinc = 
3545                                 static_cast<InsetInclude *>(*it);
3546                         if (insetinc->isIncludeOnly()) {
3547                                 if (!lst.empty())
3548                                         lst += delim;
3549                                 lst += insetinc->getRelFileBaseName();
3550                         }
3551                 }
3552         }
3553         lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3554         return lst;
3555 }
3556
3557
3558 vector<string> const Buffer::getLabelList()
3559 {
3560         /// if this is a child document and the parent is already loaded
3561         /// Use the parent's list instead  [ale990407]
3562         if (!params.parentname.empty()
3563             && bufferlist.exists(params.parentname)) {
3564                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3565                 if (tmp)
3566                         return tmp->getLabelList();
3567         }
3568
3569         vector<string> label_list;
3570         for (inset_iterator it = inset_iterator_begin();
3571              it != inset_iterator_end(); ++it) {
3572                 vector<string> const l = (*it)->getLabelList();
3573                 label_list.insert(label_list.end(), l.begin(), l.end());
3574         }
3575         return label_list;
3576 }
3577
3578
3579 Buffer::Lists const Buffer::getLists() const
3580 {
3581         Lists l;
3582         Paragraph * par = paragraph;
3583         bool found;
3584         LyXTextClassList::size_type cap;
3585         boost::tie(found, cap) = textclasslist
3586                 .NumberOfLayout(params.textclass, "Caption");
3587
3588         while (par) {
3589                 char const labeltype =
3590                         textclasslist.Style(params.textclass, 
3591                                             par->getLayout()).labeltype;
3592                 
3593                 if (labeltype >= LABEL_COUNTER_CHAPTER
3594                     && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3595                                 // insert this into the table of contents
3596                         SingleList & item = l["TOC"];
3597                         int depth = max(0,
3598                                         labeltype - 
3599                                         textclasslist.TextClass(params.textclass).maxcounter());
3600                         item.push_back(TocItem(par, depth, par->asString(this, true)));
3601                 }
3602                 // For each paragrph, traverse its insets and look for
3603                 // FLOAT_CODE
3604                 
3605                 if (found) {
3606                         Paragraph::inset_iterator it =
3607                                 par->inset_iterator_begin();
3608                         Paragraph::inset_iterator end =
3609                                 par->inset_iterator_end();
3610                         
3611                         for (; it != end; ++it) {
3612                                 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3613                                         InsetFloat * il =
3614                                                 static_cast<InsetFloat*>(*it);
3615                                         
3616                                         string const type = il->type();
3617                                         
3618                                         // Now find the caption in the float...
3619                                         // We now tranverse the paragraphs of
3620                                         // the inset...
3621                                         Paragraph * tmp = il->inset.paragraph();
3622                                         while (tmp) {
3623                                                 if (tmp->layout == cap) {
3624                                                         SingleList & item = l[type];
3625                                                         string const str =
3626                                                                 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3627                                                         item.push_back(TocItem(tmp, 0 , str));
3628                                                 }
3629                                                 tmp = tmp->next();
3630                                         }
3631                                 }
3632                         }
3633                 } else {
3634                         lyxerr << "caption not found" << endl;
3635                 }
3636                 
3637                 par = par->next();
3638         }
3639         return l;
3640 }
3641
3642
3643 // This is also a buffer property (ale)
3644 vector<pair<string, string> > const Buffer::getBibkeyList()
3645 {
3646         /// if this is a child document and the parent is already loaded
3647         /// Use the parent's list instead  [ale990412]
3648         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3649                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3650                 if (tmp)
3651                         return tmp->getBibkeyList();
3652         }
3653
3654         vector<pair<string, string> > keys;
3655         Paragraph * par = paragraph;
3656         while (par) {
3657                 if (par->bibkey)
3658                         keys.push_back(pair<string, string>(par->bibkey->getContents(),
3659                                                            par->asString(this, false)));
3660                 par = par->next();
3661         }
3662
3663         // Might be either using bibtex or a child has bibliography
3664         if (keys.empty()) {
3665                 for (inset_iterator it = inset_iterator_begin();
3666                         it != inset_iterator_end(); ++it) {
3667                         // Search for Bibtex or Include inset
3668                         if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3669                                 vector<pair<string,string> > tmp =
3670                                         static_cast<InsetBibtex*>(*it)->getKeys(this);
3671                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3672                         } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3673                                 vector<pair<string,string> > const tmp =
3674                                         static_cast<InsetInclude*>(*it)->getKeys();
3675                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3676                         }
3677                 }
3678         }
3679  
3680         return keys;
3681 }
3682
3683
3684 bool Buffer::isDepClean(string const & name) const
3685 {
3686         DEPCLEAN * item = dep_clean;
3687         while (item && item->master != name)
3688                 item = item->next;
3689         if (!item) return true;
3690         return item->clean;
3691 }
3692
3693
3694 void Buffer::markDepClean(string const & name)
3695 {
3696         if (!dep_clean) {
3697                 dep_clean = new DEPCLEAN;
3698                 dep_clean->clean = true;
3699                 dep_clean->master = name;
3700                 dep_clean->next = 0;
3701         } else {
3702                 DEPCLEAN * item = dep_clean;
3703                 while (item && item->master != name)
3704                         item = item->next;
3705                 if (item) {
3706                         item->clean = true;
3707                 } else {
3708                         item = new DEPCLEAN;
3709                         item->clean = true;
3710                         item->master = name;
3711                         item->next = 0;
3712                 }
3713         }
3714 }
3715
3716
3717 bool Buffer::dispatch(string const & command)
3718 {
3719         // Split command string into command and argument
3720         string cmd;
3721         string line = frontStrip(command);
3722         string const arg = strip(frontStrip(split(line, cmd, ' ')));
3723
3724         return dispatch(lyxaction.LookupFunc(cmd), arg);
3725 }
3726
3727
3728 bool Buffer::dispatch(int action, string const & argument)
3729 {
3730         bool dispatched = true;
3731         switch (action) {
3732                 case LFUN_EXPORT: 
3733                         Exporter::Export(this, argument, false);
3734                         break;
3735
3736                 default:
3737                         dispatched = false;
3738         }
3739         return dispatched;
3740 }
3741
3742
3743 void Buffer::resizeInsets(BufferView * bv)
3744 {
3745         /// then remove all LyXText in text-insets
3746         Paragraph * par = paragraph;
3747         for (; par; par = par->next()) {
3748             par->resizeInsetsLyXText(bv);
3749         }
3750 }
3751
3752
3753 void Buffer::redraw()
3754 {
3755         users->redraw(); 
3756         users->fitCursor(users->text); 
3757 }
3758
3759
3760 void Buffer::changeLanguage(Language const * from, Language const * to)
3761 {
3762
3763         Paragraph * par = paragraph;
3764         while (par) {
3765                 par->changeLanguage(params, from, to);
3766                 par = par->next();
3767         }
3768 }
3769
3770
3771 bool Buffer::isMultiLingual()
3772 {
3773         Paragraph * par = paragraph;
3774         while (par) {
3775                 if (par->isMultiLingual(params))
3776                         return true;
3777                 par = par->next();
3778         }
3779         return false;
3780 }
3781
3782
3783 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3784                                        Paragraph::size_type pos)
3785         : par(paragraph)
3786 {
3787         it = par->InsetIterator(pos);
3788         if (it == par->inset_iterator_end()) {
3789                 par = par->next();
3790                 setParagraph();
3791         }
3792 }
3793
3794
3795 void Buffer::inset_iterator::setParagraph()
3796 {
3797         while (par) {
3798                 it = par->inset_iterator_begin();
3799                 if (it != par->inset_iterator_end())
3800                         return;
3801                 par = par->next();
3802         }
3803         //it = 0;
3804         // We maintain an invariant that whenever par = 0 then it = 0
3805 }
3806
3807
3808 Inset * Buffer::getInsetFromID(int id_arg) const
3809 {
3810         for (inset_iterator it = inset_const_iterator_begin();
3811                  it != inset_const_iterator_end(); ++it)
3812         {
3813                 if ((*it)->id() == id_arg)
3814                         return *it;
3815                 Inset * in = (*it)->getInsetFromID(id_arg);
3816                 if (in)
3817                         return in;
3818         }
3819         return 0;
3820 }
3821
3822
3823 Paragraph * Buffer::getParFromID(int id) const
3824 {
3825         if (id < 0) return 0;
3826         Paragraph * par = paragraph;
3827         while (par) {
3828                 if (par->id() == id) {
3829                         return par;
3830                 }
3831                 Paragraph * tmp = par->getParFromID(id);
3832                 if (tmp) {
3833                         return tmp;
3834                 }
3835                 par = par->next();
3836         }
3837         return 0;
3838 }