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