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