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