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