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