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