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