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