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