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