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