]> git.lyx.org Git - lyx.git/blob - src/buffer.C
f1d774986ea65ab201cfa790c35010ce39eadeac
[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.UsedLanguages.insert(default_language);
2061
2062                 if (lyxrc.language_use_babel ||
2063                     params.language->lang() != lyxrc.default_language ||
2064                     !features.UsedLanguages.empty()) {
2065                         use_babel = true;
2066                         for (LaTeXFeatures::LanguageList::const_iterator cit =
2067                                      features.UsedLanguages.begin();
2068                              cit != features.UsedLanguages.end(); ++cit)
2069                                 language_options << (*cit)->babel() << ',';
2070                         language_options << params.language->babel();
2071                         if (lyxrc.language_global_options)
2072                                 options << language_options.str() << ',';
2073                 }
2074
2075                 // the user-defined options
2076                 if (!params.options.empty()) {
2077                         options << params.options << ',';
2078                 }
2079
2080                 string strOptions(options.str().c_str());
2081                 if (!strOptions.empty()){
2082                         strOptions = strip(strOptions, ',');
2083                         ofs << '[' << strOptions << ']';
2084                 }
2085                 
2086                 ofs << '{'
2087                     << textclasslist.LatexnameOfClass(params.textclass)
2088                     << "}\n";
2089                 texrow.newline();
2090                 // end of \documentclass defs
2091                 
2092                 // font selection must be done before loading fontenc.sty
2093                 // The ae package is not needed when using OT1 font encoding.
2094                 if (params.fonts != "default" &&
2095                     (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2096                         ofs << "\\usepackage{" << params.fonts << "}\n";
2097                         texrow.newline();
2098                         if (params.fonts == "ae") {
2099                                 ofs << "\\usepackage{aecompl}\n";
2100                                 texrow.newline();
2101                         }
2102                 }
2103                 // this one is not per buffer
2104                 if (lyxrc.fontenc != "default") {
2105                         ofs << "\\usepackage[" << lyxrc.fontenc
2106                             << "]{fontenc}\n";
2107                         texrow.newline();
2108                 }
2109
2110                 if (params.inputenc == "auto") {
2111                         string const doc_encoding =
2112                                 params.language->encoding()->LatexName();
2113
2114                         // Create a list with all the input encodings used 
2115                         // in the document
2116                         set<string> encodings;
2117                         for (LaTeXFeatures::LanguageList::const_iterator it =
2118                                      features.UsedLanguages.begin();
2119                              it != features.UsedLanguages.end(); ++it)
2120                                 if ((*it)->encoding()->LatexName() != doc_encoding)
2121                                         encodings.insert((*it)->encoding()->LatexName());
2122
2123                         ofs << "\\usepackage[";
2124                         std::copy(encodings.begin(), encodings.end(),
2125                                   std::ostream_iterator<string>(ofs, ","));
2126                         ofs << doc_encoding << "]{inputenc}\n";
2127                         texrow.newline();
2128                 } else if (params.inputenc != "default") {
2129                         ofs << "\\usepackage[" << params.inputenc
2130                             << "]{inputenc}\n";
2131                         texrow.newline();
2132                 }
2133
2134                 // At the very beginning the text parameters.
2135                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2136                         switch (params.paperpackage) {
2137                         case BufferParams::PACKAGE_A4:
2138                                 ofs << "\\usepackage{a4}\n";
2139                                 texrow.newline();
2140                                 break;
2141                         case BufferParams::PACKAGE_A4WIDE:
2142                                 ofs << "\\usepackage{a4wide}\n";
2143                                 texrow.newline();
2144                                 break;
2145                         case BufferParams::PACKAGE_WIDEMARGINSA4:
2146                                 ofs << "\\usepackage[widemargins]{a4}\n";
2147                                 texrow.newline();
2148                                 break;
2149                         }
2150                 }
2151                 if (params.use_geometry) {
2152                         ofs << "\\usepackage{geometry}\n";
2153                         texrow.newline();
2154                         ofs << "\\geometry{verbose";
2155                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2156                                 ofs << ",landscape";
2157                         switch (params.papersize2) {
2158                         case BufferParams::VM_PAPER_CUSTOM:
2159                                 if (!params.paperwidth.empty())
2160                                         ofs << ",paperwidth="
2161                                             << params.paperwidth;
2162                                 if (!params.paperheight.empty())
2163                                         ofs << ",paperheight="
2164                                             << params.paperheight;
2165                                 break;
2166                         case BufferParams::VM_PAPER_USLETTER:
2167                                 ofs << ",letterpaper";
2168                                 break;
2169                         case BufferParams::VM_PAPER_USLEGAL:
2170                                 ofs << ",legalpaper";
2171                                 break;
2172                         case BufferParams::VM_PAPER_USEXECUTIVE:
2173                                 ofs << ",executivepaper";
2174                                 break;
2175                         case BufferParams::VM_PAPER_A3:
2176                                 ofs << ",a3paper";
2177                                 break;
2178                         case BufferParams::VM_PAPER_A4:
2179                                 ofs << ",a4paper";
2180                                 break;
2181                         case BufferParams::VM_PAPER_A5:
2182                                 ofs << ",a5paper";
2183                                 break;
2184                         case BufferParams::VM_PAPER_B3:
2185                                 ofs << ",b3paper";
2186                                 break;
2187                         case BufferParams::VM_PAPER_B4:
2188                                 ofs << ",b4paper";
2189                                 break;
2190                         case BufferParams::VM_PAPER_B5:
2191                                 ofs << ",b5paper";
2192                                 break;
2193                         default:
2194                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2195                                 switch (lyxrc.default_papersize) {
2196                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2197                                 case BufferParams::PAPER_USLETTER:
2198                                         ofs << ",letterpaper";
2199                                         break;
2200                                 case BufferParams::PAPER_LEGALPAPER:
2201                                         ofs << ",legalpaper";
2202                                         break;
2203                                 case BufferParams::PAPER_EXECUTIVEPAPER:
2204                                         ofs << ",executivepaper";
2205                                         break;
2206                                 case BufferParams::PAPER_A3PAPER:
2207                                         ofs << ",a3paper";
2208                                         break;
2209                                 case BufferParams::PAPER_A4PAPER:
2210                                         ofs << ",a4paper";
2211                                         break;
2212                                 case BufferParams::PAPER_A5PAPER:
2213                                         ofs << ",a5paper";
2214                                         break;
2215                                 case BufferParams::PAPER_B5PAPER:
2216                                         ofs << ",b5paper";
2217                                         break;
2218                                 }
2219                         }
2220                         if (!params.topmargin.empty())
2221                                 ofs << ",tmargin=" << params.topmargin;
2222                         if (!params.bottommargin.empty())
2223                                 ofs << ",bmargin=" << params.bottommargin;
2224                         if (!params.leftmargin.empty())
2225                                 ofs << ",lmargin=" << params.leftmargin;
2226                         if (!params.rightmargin.empty())
2227                                 ofs << ",rmargin=" << params.rightmargin;
2228                         if (!params.headheight.empty())
2229                                 ofs << ",headheight=" << params.headheight;
2230                         if (!params.headsep.empty())
2231                                 ofs << ",headsep=" << params.headsep;
2232                         if (!params.footskip.empty())
2233                                 ofs << ",footskip=" << params.footskip;
2234                         ofs << "}\n";
2235                         texrow.newline();
2236                 }
2237                 if (features.amsstyle
2238                     && !tclass.provides(LyXTextClass::amsmath)) {
2239                         ofs << "\\usepackage{amsmath}\n";
2240                         texrow.newline();
2241                 }
2242
2243                 if (tokenPos(tclass.opt_pagestyle(),
2244                              '|', params.pagestyle) >= 0) {
2245                         if (params.pagestyle == "fancy") {
2246                                 ofs << "\\usepackage{fancyhdr}\n";
2247                                 texrow.newline();
2248                         }
2249                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2250                         texrow.newline();
2251                 }
2252
2253                 if (params.secnumdepth != tclass.secnumdepth()) {
2254                         ofs << "\\setcounter{secnumdepth}{"
2255                             << params.secnumdepth
2256                             << "}\n";
2257                         texrow.newline();
2258                 }
2259                 if (params.tocdepth != tclass.tocdepth()) {
2260                         ofs << "\\setcounter{tocdepth}{"
2261                             << params.tocdepth
2262                             << "}\n";
2263                         texrow.newline();
2264                 }
2265                 
2266                 if (params.paragraph_separation) {
2267                         switch (params.defskip.kind()) {
2268                         case VSpace::SMALLSKIP: 
2269                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2270                                 break;
2271                         case VSpace::MEDSKIP:
2272                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2273                                 break;
2274                         case VSpace::BIGSKIP:
2275                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2276                                 break;
2277                         case VSpace::LENGTH:
2278                                 ofs << "\\setlength\\parskip{"
2279                                     << params.defskip.length().asLatexString()
2280                                     << "}\n";
2281                                 break;
2282                         default: // should never happen // Then delete it.
2283                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2284                                 break;
2285                         }
2286                         texrow.newline();
2287                         
2288                         ofs << "\\setlength\\parindent{0pt}\n";
2289                         texrow.newline();
2290                 }
2291
2292                 // Now insert the LyX specific LaTeX commands...
2293
2294                 // The optional packages;
2295                 string preamble(features.getPackages());
2296
2297                 // this might be useful...
2298                 preamble += "\n\\makeatletter\n";
2299
2300                 // Some macros LyX will need
2301                 string tmppreamble(features.getMacros());
2302
2303                 if (!tmppreamble.empty()) {
2304                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2305                                 "LyX specific LaTeX commands.\n"
2306                                 + tmppreamble + '\n';
2307                 }
2308
2309                 // the text class specific preamble 
2310                 tmppreamble = features.getTClassPreamble();
2311                 if (!tmppreamble.empty()) {
2312                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2313                                 "Textclass specific LaTeX commands.\n"
2314                                 + tmppreamble + '\n';
2315                 }
2316
2317                 /* the user-defined preamble */
2318                 if (!params.preamble.empty()) {
2319                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2320                                 "User specified LaTeX commands.\n"
2321                                 + params.preamble + '\n';
2322                 }
2323
2324                 preamble += "\\makeatother\n";
2325
2326                 // Itemize bullet settings need to be last in case the user
2327                 // defines their own bullets that use a package included
2328                 // in the user-defined preamble -- ARRae
2329                 // Actually it has to be done much later than that
2330                 // since some packages like frenchb make modifications
2331                 // at \begin{document} time -- JMarc 
2332                 string bullets_def;
2333                 for (int i = 0; i < 4; ++i) {
2334                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2335                                 if (bullets_def.empty())
2336                                         bullets_def="\\AtBeginDocument{\n";
2337                                 bullets_def += "  \\renewcommand{\\labelitemi";
2338                                 switch (i) {
2339                                 // `i' is one less than the item to modify
2340                                 case 0:
2341                                         break;
2342                                 case 1:
2343                                         bullets_def += 'i';
2344                                         break;
2345                                 case 2:
2346                                         bullets_def += "ii";
2347                                         break;
2348                                 case 3:
2349                                         bullets_def += 'v';
2350                                         break;
2351                                 }
2352                                 bullets_def += "}{" + 
2353                                   params.user_defined_bullets[i].getText() 
2354                                   + "}\n";
2355                         }
2356                 }
2357
2358                 if (!bullets_def.empty())
2359                   preamble += bullets_def + "}\n\n";
2360
2361                 for (int j = countChar(preamble, '\n'); j-- ;) {
2362                         texrow.newline();
2363                 }
2364
2365                 ofs << preamble;
2366
2367                 // We try to load babel late, in case it interferes
2368                 // with other packages.
2369                 if (use_babel) {
2370                         string tmp = lyxrc.language_package;
2371                         if (!lyxrc.language_global_options
2372                             && tmp == "\\usepackage{babel}")
2373                                 tmp = string("\\usepackage[") +
2374                                         language_options.str().c_str() +
2375                                         "]{babel}";
2376                         ofs << tmp << "\n";
2377                         texrow.newline();
2378                 }
2379
2380                 // make the body.
2381                 ofs << "\\begin{document}\n";
2382                 texrow.newline();
2383         } // only_body
2384         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2385
2386         if (!lyxrc.language_auto_begin) {
2387                 ofs << subst(lyxrc.language_command_begin, "$$lang",
2388                              params.language->babel())
2389                     << endl;
2390                 texrow.newline();
2391         }
2392         
2393         latexParagraphs(ofs, paragraph, 0, texrow);
2394
2395         // add this just in case after all the paragraphs
2396         ofs << endl;
2397         texrow.newline();
2398
2399         if (!lyxrc.language_auto_end) {
2400                 ofs << subst(lyxrc.language_command_end, "$$lang",
2401                              params.language->babel())
2402                     << endl;
2403                 texrow.newline();
2404         }
2405
2406         if (!only_body) {
2407                 ofs << "\\end{document}\n";
2408                 texrow.newline();
2409         
2410                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2411         } else {
2412                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2413                                      << endl;
2414         }
2415
2416         // Just to be sure. (Asger)
2417         texrow.newline();
2418
2419         // tex_code_break_column's value is used to decide
2420         // if we are in batchmode or not (within mathed_write()
2421         // in math_write.C) so we must set it to a non-zero
2422         // value when we leave otherwise we save incorrect .lyx files.
2423         tex_code_break_column = lyxrc.ascii_linelen;
2424
2425         ofs.close();
2426         if (ofs.fail()) {
2427                 lyxerr << "File was not closed properly." << endl;
2428         }
2429         
2430         lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2431 }
2432
2433
2434 //
2435 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2436 //
2437 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2438                              Paragraph * endpar, TexRow & texrow) const
2439 {
2440         bool was_title = false;
2441         bool already_title = false;
2442
2443         // if only_body
2444         while (par != endpar) {
2445                 LyXLayout const & layout =
2446                         textclasslist.Style(params.textclass,
2447                                             par->layout);
2448             
2449                 if (layout.intitle) {
2450                         if (already_title) {
2451                                 lyxerr <<"Error in latexParagraphs: You"
2452                                         " should not mix title layouts"
2453                                         " with normal ones." << endl;
2454                         } else
2455                                 was_title = true;
2456                 } else if (was_title && !already_title) {
2457                         ofs << "\\maketitle\n";
2458                         texrow.newline();
2459                         already_title = true;
2460                         was_title = false;                  
2461                 }
2462                 
2463                 if (layout.isEnvironment()) {
2464                         par = par->TeXEnvironment(this, params, ofs, texrow);
2465                 } else {
2466                         par = par->TeXOnePar(this, params, ofs, texrow, false);
2467                 }
2468         }
2469         // It might be that we only have a title in this document
2470         if (was_title && !already_title) {
2471                 ofs << "\\maketitle\n";
2472                 texrow.newline();
2473         }
2474 }
2475
2476
2477 bool Buffer::isLatex() const
2478 {
2479         return textclasslist.TextClass(params.textclass).outputType() == LATEX;
2480 }
2481
2482
2483 bool Buffer::isLinuxDoc() const
2484 {
2485         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC;
2486 }
2487
2488
2489 bool Buffer::isLiterate() const
2490 {
2491         return textclasslist.TextClass(params.textclass).outputType() == LITERATE;
2492 }
2493
2494
2495 bool Buffer::isDocBook() const
2496 {
2497         return textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2498 }
2499
2500
2501 bool Buffer::isSGML() const
2502 {
2503         return textclasslist.TextClass(params.textclass).outputType() == LINUXDOC ||
2504                textclasslist.TextClass(params.textclass).outputType() == DOCBOOK;
2505 }
2506
2507
2508 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2509                          string const & latexname) const
2510 {
2511         if (!latexname.empty() && latexname != "!-- --")
2512                 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2513                 os << string(depth, ' ') << "<" << latexname << ">\n";
2514 }
2515
2516
2517 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2518                           string const & latexname) const
2519 {
2520         if (!latexname.empty() && latexname != "!-- --")
2521                 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2522                 os << string(depth, ' ') << "</" << latexname << ">\n";
2523 }
2524
2525
2526 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2527 {
2528         ofstream ofs(fname.c_str());
2529
2530         if (!ofs) {
2531                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2532                 return;
2533         }
2534
2535         niceFile = nice; // this will be used by included files.
2536
2537         LyXTextClass const & tclass =
2538                 textclasslist.TextClass(params.textclass);
2539
2540         LaTeXFeatures features(params, tclass.numLayouts());
2541         validate(features);
2542
2543         texrow.reset();
2544
2545         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2546
2547         if (!body_only) {
2548                 ofs << "<!doctype linuxdoc system";
2549
2550                 string preamble = params.preamble;
2551                 preamble += features.getIncludedFiles(fname);
2552                 preamble += features.getLyXSGMLEntities();
2553
2554                 if (!preamble.empty()) {
2555                         ofs << " [ " << preamble << " ]";
2556                 }
2557                 ofs << ">\n\n";
2558
2559                 if (params.options.empty())
2560                         sgmlOpenTag(ofs, 0, top_element);
2561                 else {
2562                         string top = top_element;
2563                         top += " ";
2564                         top += params.options;
2565                         sgmlOpenTag(ofs, 0, top);
2566                 }
2567         }
2568
2569         ofs << "<!-- "  << lyx_docversion
2570             << " created this file. For more info see http://www.lyx.org/"
2571             << " -->\n";
2572
2573         Paragraph::depth_type depth = 0; // paragraph depth
2574         Paragraph * par = paragraph;
2575         string item_name;
2576         vector<string> environment_stack(5);
2577
2578         while (par) {
2579                 LyXLayout const & style =
2580                         textclasslist.Style(params.textclass,
2581                                             par->layout);
2582
2583                 // treat <toc> as a special case for compatibility with old code
2584                 if (par->getChar(0) == Paragraph::META_INSET) {
2585                         Inset * inset = par->getInset(0);
2586                         Inset::Code lyx_code = inset->lyxCode();
2587                         if (lyx_code == Inset::TOC_CODE){
2588                                 string const temp = "toc";
2589                                 sgmlOpenTag(ofs, depth, temp);
2590
2591                                 par = par->next();
2592                                 continue;
2593                         }
2594                 }
2595
2596                 // environment tag closing
2597                 for (; depth > par->params().depth(); --depth) {
2598                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2599                         environment_stack[depth].erase();
2600                 }
2601
2602                 // write opening SGML tags
2603                 switch (style.latextype) {
2604                 case LATEX_PARAGRAPH:
2605                         if (depth == par->params().depth() 
2606                            && !environment_stack[depth].empty()) {
2607                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2608                                 environment_stack[depth].erase();
2609                                 if (depth) 
2610                                         --depth;
2611                                 else
2612                                         ofs << "</p>";
2613                         }
2614                         sgmlOpenTag(ofs, depth, style.latexname());
2615                         break;
2616
2617                 case LATEX_COMMAND:
2618                         if (depth!= 0)
2619                                 sgmlError(par, 0,
2620                                           _("Error : Wrong depth for"
2621                                             " LatexType Command.\n"));
2622
2623                         if (!environment_stack[depth].empty()){
2624                                 sgmlCloseTag(ofs, depth,
2625                                              environment_stack[depth]);
2626                                 ofs << "</p>";
2627                         }
2628
2629                         environment_stack[depth].erase();
2630                         sgmlOpenTag(ofs, depth, style.latexname());
2631                         break;
2632
2633                 case LATEX_ENVIRONMENT:
2634                 case LATEX_ITEM_ENVIRONMENT:
2635                         if (depth == par->params().depth() 
2636                             && environment_stack[depth] != style.latexname()) {
2637                                 sgmlCloseTag(ofs, depth,
2638                                              environment_stack[depth]);
2639                                 environment_stack[depth].erase();
2640                         }
2641                         if (depth < par->params().depth()) {
2642                                depth = par->params().depth();
2643                                environment_stack[depth].erase();
2644                         }
2645                         if (environment_stack[depth] != style.latexname()) {
2646                                 if (depth == 0) {
2647                                         sgmlOpenTag(ofs, depth, "p");
2648                                 }
2649                                 sgmlOpenTag(ofs, depth, style.latexname());
2650
2651                                 if (environment_stack.size() == depth + 1)
2652                                         environment_stack.push_back("!-- --");
2653                                 environment_stack[depth] = style.latexname();
2654                         }
2655
2656                         if (style.latexparam() == "CDATA")
2657                                 ofs << "<![CDATA[";
2658
2659                         if (style.latextype == LATEX_ENVIRONMENT) break;
2660
2661                         if (style.labeltype == LABEL_MANUAL)
2662                                 item_name = "tag";
2663                         else
2664                                 item_name = "item";
2665
2666                         sgmlOpenTag(ofs, depth + 1, item_name);
2667                         break;
2668                 default:
2669                         sgmlOpenTag(ofs, depth, style.latexname());
2670                         break;
2671                 }
2672
2673                 simpleLinuxDocOnePar(ofs, par, depth);
2674
2675                 par = par->next();
2676
2677                 ofs << "\n";
2678                 // write closing SGML tags
2679                 switch (style.latextype) {
2680                 case LATEX_COMMAND:
2681                         break;
2682                 case LATEX_ENVIRONMENT:
2683                 case LATEX_ITEM_ENVIRONMENT:
2684                         if (style.latexparam() == "CDATA")
2685                                 ofs << "]]>";
2686                         break;
2687                 default:
2688                         sgmlCloseTag(ofs, depth, style.latexname());
2689                         break;
2690                 }
2691         }
2692    
2693         // Close open tags
2694         for (int i=depth; i >= 0; --i)
2695                 sgmlCloseTag(ofs, depth, environment_stack[i]);
2696
2697         if (!body_only) {
2698                 ofs << "\n\n";
2699                 sgmlCloseTag(ofs, 0, top_element);
2700         }
2701
2702         ofs.close();
2703         // How to check for successful close
2704 }
2705
2706
2707 // checks, if newcol chars should be put into this line
2708 // writes newline, if necessary.
2709 namespace {
2710
2711 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2712                           string::size_type newcol)
2713 {
2714         colcount += newcol;
2715         if (colcount > lyxrc.ascii_linelen) {
2716                 os << "\n";
2717                 colcount = newcol; // assume write after this call
2718         }
2719 }
2720
2721 enum PAR_TAG {
2722         NONE=0,
2723         TT = 1,
2724         SF = 2,
2725         BF = 4,
2726         IT = 8,
2727         SL = 16,
2728         EM = 32
2729 };
2730
2731
2732 string tag_name(PAR_TAG const & pt) {
2733         switch (pt) {
2734         case NONE: return "!-- --";
2735         case TT: return "tt";
2736         case SF: return "sf";
2737         case BF: return "bf";
2738         case IT: return "it";
2739         case SL: return "sl";
2740         case EM: return "em";
2741         }
2742         return "";
2743 }
2744
2745
2746 inline
2747 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2748 {
2749         p1 = static_cast<PAR_TAG>(p1 | p2);
2750 }
2751
2752
2753 inline
2754 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2755 {
2756         p1 = static_cast<PAR_TAG>( p1 & ~p2);
2757 }
2758
2759 } // namespace anon
2760
2761
2762 // Handle internal paragraph parsing -- layout already processed.
2763 void Buffer::simpleLinuxDocOnePar(ostream & os,
2764                                   Paragraph * par, 
2765                                   Paragraph::depth_type /*depth*/)
2766 {
2767         LyXLayout const & style = textclasslist.Style(params.textclass,
2768                                                       par->getLayout());
2769         string::size_type char_line_count = 5;     // Heuristic choice ;-) 
2770
2771         // gets paragraph main font
2772         LyXFont font_old;
2773         bool desc_on;
2774         if (style.labeltype == LABEL_MANUAL) {
2775                 font_old = style.labelfont;
2776                 desc_on = true;
2777         } else {
2778                 font_old = style.font;
2779                 desc_on = false;
2780         }
2781
2782         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2783         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2784         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
2785         bool is_em = false;
2786
2787         stack<PAR_TAG> tag_state;
2788         // parsing main loop
2789         for (Paragraph::size_type i = 0; i < par->size(); ++i) {
2790
2791                 PAR_TAG tag_close = NONE;
2792                 list < PAR_TAG > tag_open;
2793
2794                 LyXFont const font = par->getFont(params, i);
2795
2796                 if (font_old.family() != font.family()) {
2797                         switch (family_type) {
2798                         case LyXFont::SANS_FAMILY:
2799                                 tag_close |= SF;
2800                                 break;
2801                         case LyXFont::TYPEWRITER_FAMILY:
2802                                 tag_close |= TT;
2803                                 break;
2804                         default:
2805                                 break;
2806                         }
2807
2808                         family_type = font.family();
2809
2810                         switch (family_type) {
2811                         case LyXFont::SANS_FAMILY:
2812                                 tag_open.push_back(SF);
2813                                 break;
2814                         case LyXFont::TYPEWRITER_FAMILY:
2815                                 tag_open.push_back(TT);
2816                                 break;
2817                         default:
2818                                 break;
2819                         }
2820                 }
2821
2822                 if (font_old.series() != font.series()) {
2823                         switch (series_type) {
2824                         case LyXFont::BOLD_SERIES:
2825                                 tag_close |= BF;
2826                                 break;
2827                         default:
2828                                 break;
2829                         }
2830
2831                         series_type = font.series();
2832
2833                         switch (series_type) {
2834                         case LyXFont::BOLD_SERIES:
2835                                 tag_open.push_back(BF);
2836                                 break;
2837                         default:
2838                                 break;
2839                         }
2840
2841                 }
2842
2843                 if (font_old.shape() != font.shape()) {
2844                         switch (shape_type) {
2845                         case LyXFont::ITALIC_SHAPE:
2846                                 tag_close |= IT;
2847                                 break;
2848                         case LyXFont::SLANTED_SHAPE:
2849                                 tag_close |= SL;
2850                                 break;
2851                         default:
2852                                 break;
2853                         }
2854
2855                         shape_type = font.shape();
2856
2857                         switch (shape_type) {
2858                         case LyXFont::ITALIC_SHAPE:
2859                                 tag_open.push_back(IT);
2860                                 break;
2861                         case LyXFont::SLANTED_SHAPE:
2862                                 tag_open.push_back(SL);
2863                                 break;
2864                         default:
2865                                 break;
2866                         }
2867                 }
2868                 // handle <em> tag
2869                 if (font_old.emph() != font.emph()) {
2870                         if (font.emph() == LyXFont::ON) {
2871                                 tag_open.push_back(EM);
2872                                 is_em = true;
2873                         }
2874                         else if (is_em) {
2875                                 tag_close |= EM;
2876                                 is_em = false;
2877                         }
2878                 }
2879
2880                 list < PAR_TAG > temp;
2881                 while(!tag_state.empty() && tag_close ) {
2882                         PAR_TAG k =  tag_state.top();
2883                         tag_state.pop();
2884                         os << "</" << tag_name(k) << ">";
2885                         if (tag_close & k)
2886                                 reset(tag_close,k);
2887                         else
2888                                 temp.push_back(k);
2889                 }
2890
2891                 for(list< PAR_TAG >::const_iterator j = temp.begin();
2892                     j != temp.end(); ++j) {
2893                         tag_state.push(*j);
2894                         os << "<" << tag_name(*j) << ">";
2895                 }
2896
2897                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2898                     j != tag_open.end(); ++j) {
2899                         tag_state.push(*j);
2900                         os << "<" << tag_name(*j) << ">";
2901                 }
2902
2903                 char c = par->getChar(i);
2904
2905                 if (c == Paragraph::META_INSET) {
2906                         Inset * inset = par->getInset(i);
2907                         inset->linuxdoc(this, os);
2908                         font_old = font;
2909                         continue;
2910                 }
2911
2912                 if (style.latexparam() == "CDATA") {
2913                         // "TeX"-Mode on == > SGML-Mode on.
2914                         if (c != '\0')
2915                                 os << c;
2916                         ++char_line_count;
2917                 } else {
2918                         string sgml_string;
2919                         if (par->sgmlConvertChar(c, sgml_string)
2920                             && !style.free_spacing) { 
2921                                 // in freespacing mode, spaces are
2922                                 // non-breaking characters
2923                                 if (desc_on) {// if char is ' ' then...
2924
2925                                         ++char_line_count;
2926                                         sgmlLineBreak(os, char_line_count, 6);
2927                                         os << "</tag>";
2928                                         desc_on = false;
2929                                 } else  {
2930                                         sgmlLineBreak(os, char_line_count, 1);
2931                                         os << c;
2932                                 }
2933                         } else {
2934                                 os << sgml_string;
2935                                 char_line_count += sgml_string.length();
2936                         }
2937                 }
2938                 font_old = font;
2939         }
2940
2941         while (!tag_state.empty()) {
2942                 os << "</" << tag_name(tag_state.top()) << ">";
2943                 tag_state.pop();
2944         }
2945
2946         // resets description flag correctly
2947         if (desc_on) {
2948                 // <tag> not closed...
2949                 sgmlLineBreak(os, char_line_count, 6);
2950                 os << "</tag>";
2951         }
2952 }
2953
2954
2955 // Print an error message.
2956 void Buffer::sgmlError(Paragraph * par, int pos,
2957                        string const & message) const
2958 {
2959         // insert an error marker in text
2960         InsetError * new_inset = new InsetError(message);
2961         par->insertInset(pos, new_inset);
2962 }
2963
2964
2965 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2966 {
2967         ofstream ofs(fname.c_str());
2968         if (!ofs) {
2969                 WriteAlert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2970                 return;
2971         }
2972
2973         Paragraph * par = paragraph;
2974
2975         niceFile = nice; // this will be used by Insetincludes.
2976
2977         LyXTextClass const & tclass =
2978                 textclasslist.TextClass(params.textclass);
2979
2980         LaTeXFeatures features(params, tclass.numLayouts());
2981         validate(features);
2982    
2983         texrow.reset();
2984
2985         string top_element = textclasslist.LatexnameOfClass(params.textclass);
2986
2987         if (!only_body) {
2988                 ofs << "<!DOCTYPE " << top_element
2989                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2990
2991                 string preamble = params.preamble;
2992                 preamble += features.getIncludedFiles(fname);
2993                 preamble += features.getLyXSGMLEntities();
2994
2995                 if (!preamble.empty()) {
2996                         ofs << "\n [ " << preamble << " ]";
2997                 }
2998                 ofs << ">\n\n";
2999         }
3000
3001         string top = top_element;       
3002         top += " lang=\"";
3003         top += params.language->code();
3004         top += "\"";
3005
3006         if (!params.options.empty()) {
3007                 top += " ";
3008                 top += params.options;
3009         }
3010         sgmlOpenTag(ofs, 0, top);
3011
3012         ofs << "<!-- DocBook file was created by " << lyx_docversion
3013             << "\n  See http://www.lyx.org/ for more information -->\n";
3014
3015         vector<string> environment_stack(10);
3016         vector<string> environment_inner(10);
3017         vector<string> command_stack(10);
3018
3019         bool command_flag = false;
3020         Paragraph::depth_type command_depth = 0;
3021         Paragraph::depth_type command_base = 0;
3022         Paragraph::depth_type cmd_depth = 0;
3023         Paragraph::depth_type depth = 0; // paragraph depth
3024
3025         string item_name;
3026         string command_name;
3027
3028         while (par) {
3029                 string sgmlparam;
3030                 string c_depth;
3031                 string c_params;
3032                 int desc_on = 0; // description mode
3033
3034                 LyXLayout const & style =
3035                         textclasslist.Style(params.textclass,
3036                                             par->layout);
3037
3038                 // environment tag closing
3039                 for (; depth > par->params().depth(); --depth) {
3040                         if (environment_inner[depth] != "!-- --") {
3041                                 item_name = "listitem";
3042                                 sgmlCloseTag(ofs, command_depth + depth,
3043                                              item_name);
3044                                 if (environment_inner[depth] == "varlistentry")
3045                                         sgmlCloseTag(ofs, depth+command_depth,
3046                                                      environment_inner[depth]);
3047                         }
3048                         sgmlCloseTag(ofs, depth + command_depth,
3049                                      environment_stack[depth]);
3050                         environment_stack[depth].erase();
3051                         environment_inner[depth].erase();
3052                 }
3053
3054                 if (depth == par->params().depth()
3055                    && environment_stack[depth] != style.latexname()
3056                    && !environment_stack[depth].empty()) {
3057                         if (environment_inner[depth] != "!-- --") {
3058                                 item_name= "listitem";
3059                                 sgmlCloseTag(ofs, command_depth+depth,
3060                                              item_name);
3061                                 if (environment_inner[depth] == "varlistentry")
3062                                         sgmlCloseTag(ofs,
3063                                                      depth + command_depth,
3064                                                      environment_inner[depth]);
3065                         }
3066                         
3067                         sgmlCloseTag(ofs, depth + command_depth,
3068                                      environment_stack[depth]);
3069                         
3070                         environment_stack[depth].erase();
3071                         environment_inner[depth].erase();
3072                 }
3073
3074                 // Write opening SGML tags.
3075                 switch (style.latextype) {
3076                 case LATEX_PARAGRAPH:
3077                         sgmlOpenTag(ofs, depth + command_depth,
3078                                     style.latexname());
3079                         break;
3080
3081                 case LATEX_COMMAND:
3082                         if (depth != 0)
3083                                 sgmlError(par, 0,
3084                                           _("Error : Wrong depth for "
3085                                             "LatexType Command.\n"));
3086                         
3087                         command_name = style.latexname();
3088                         
3089                         sgmlparam = style.latexparam();
3090                         c_params = split(sgmlparam, c_depth,'|');
3091                         
3092                         cmd_depth = lyx::atoi(c_depth);
3093                         
3094                         if (command_flag) {
3095                                 if (cmd_depth < command_base) {
3096                                         for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3097                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3098                                         command_depth = command_base = cmd_depth;
3099                                 } else if (cmd_depth <= command_depth) {
3100                                         for (int j = command_depth; j >= int(cmd_depth); --j)
3101                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3102                                         command_depth = cmd_depth;
3103                                 } else
3104                                         command_depth = cmd_depth;
3105                         } else {
3106                                 command_depth = command_base = cmd_depth;
3107                                 command_flag = true;
3108                         }
3109                         if (command_stack.size() == command_depth + 1)
3110                                 command_stack.push_back(string());
3111                         command_stack[command_depth] = command_name;
3112
3113                         // treat label as a special case for
3114                         // more WYSIWYM handling.
3115                         if (par->getChar(0) == Paragraph::META_INSET) {
3116                                 Inset * inset = par->getInset(0);
3117                                 Inset::Code lyx_code = inset->lyxCode();
3118                                 if (lyx_code == Inset::LABEL_CODE){
3119                                         command_name += " id=\"";
3120                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3121                                         command_name += "\"";
3122                                         desc_on = 3;
3123                                 }
3124                         }
3125
3126                         sgmlOpenTag(ofs, depth + command_depth, command_name);
3127                         if (c_params.empty())
3128                                 item_name = "title";
3129                         else
3130                                 item_name = c_params;
3131                         sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3132                         break;
3133
3134                 case LATEX_ENVIRONMENT:
3135                 case LATEX_ITEM_ENVIRONMENT:
3136                         if (depth < par->params().depth()) {
3137                                 depth = par->params().depth();
3138                                 environment_stack[depth].erase();
3139                         }
3140
3141                         if (environment_stack[depth] != style.latexname()) {
3142                                 if(environment_stack.size() == depth + 1) {
3143                                         environment_stack.push_back("!-- --");
3144                                         environment_inner.push_back("!-- --");
3145                                 }
3146                                 environment_stack[depth] = style.latexname();
3147                                 environment_inner[depth] = "!-- --";
3148                                 sgmlOpenTag(ofs, depth + command_depth,
3149                                             environment_stack[depth]);
3150                         } else {
3151                                 if (environment_inner[depth] != "!-- --") {
3152                                         item_name= "listitem";
3153                                         sgmlCloseTag(ofs,
3154                                                      command_depth + depth,
3155                                                      item_name);
3156                                         if (environment_inner[depth] == "varlistentry")
3157                                                 sgmlCloseTag(ofs,
3158                                                              depth + command_depth,
3159                                                              environment_inner[depth]);
3160                                 }
3161                         }
3162                         
3163                         if (style.latextype == LATEX_ENVIRONMENT) {
3164                                 if (!style.latexparam().empty()) {
3165                                         if(style.latexparam() == "CDATA")
3166                                                 ofs << "<![CDATA[";
3167                                         else
3168                                                 sgmlOpenTag(ofs, depth + command_depth,
3169                                                             style.latexparam());
3170                                 }
3171                                 break;
3172                         }
3173
3174                         desc_on = (style.labeltype == LABEL_MANUAL);
3175
3176                         if (desc_on)
3177                                 environment_inner[depth]= "varlistentry";
3178                         else
3179                                 environment_inner[depth]= "listitem";
3180
3181                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3182                                     environment_inner[depth]);
3183
3184                         if (desc_on) {
3185                                 item_name= "term";
3186                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3187                                             item_name);
3188                         } else {
3189                                 item_name= "para";
3190                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3191                                             item_name);
3192                         }
3193                         break;
3194                 default:
3195                         sgmlOpenTag(ofs, depth + command_depth,
3196                                     style.latexname());
3197                         break;
3198                 }
3199
3200                 string extra_par;
3201                 simpleDocBookOnePar(ofs, extra_par, par, desc_on,
3202                                     depth + 1 + command_depth);
3203                 par = par->next();
3204
3205                 string end_tag;
3206                 // write closing SGML tags
3207                 switch (style.latextype) {
3208                 case LATEX_COMMAND:
3209                         if (c_params.empty())
3210                                 end_tag = "title";
3211                         else
3212                                 end_tag = c_params;
3213                         sgmlCloseTag(ofs, depth + command_depth, end_tag);
3214                         break;
3215                 case LATEX_ENVIRONMENT:
3216                         if (!style.latexparam().empty()) {
3217                                 if(style.latexparam() == "CDATA")
3218                                         ofs << "]]>";
3219                                 else
3220                                         sgmlCloseTag(ofs, depth + command_depth,
3221                                                      style.latexparam());
3222                         }
3223                         break;
3224                 case LATEX_ITEM_ENVIRONMENT:
3225                         if (desc_on == 1) break;
3226                         end_tag= "para";
3227                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3228                         break;
3229                 case LATEX_PARAGRAPH:
3230                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3231                         break;
3232                 default:
3233                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3234                         break;
3235                 }
3236         }
3237
3238         // Close open tags
3239         for (int d = depth; d >= 0; --d) {
3240                 if (!environment_stack[depth].empty()) {
3241                         if (environment_inner[depth] != "!-- --") {
3242                                 item_name = "listitem";
3243                                 sgmlCloseTag(ofs, command_depth + depth,
3244                                              item_name);
3245                                if (environment_inner[depth] == "varlistentry")
3246                                        sgmlCloseTag(ofs, depth + command_depth,
3247                                                     environment_inner[depth]);
3248                         }
3249                         
3250                         sgmlCloseTag(ofs, depth + command_depth,
3251                                      environment_stack[depth]);
3252                 }
3253         }
3254         
3255         for (int j = command_depth; j >= 0 ; --j)
3256                 if (!command_stack[j].empty())
3257                         sgmlCloseTag(ofs, j, command_stack[j]);
3258
3259         ofs << "\n\n";
3260         sgmlCloseTag(ofs, 0, top_element);
3261
3262         ofs.close();
3263         // How to check for successful close
3264 }
3265
3266
3267 void Buffer::simpleDocBookOnePar(ostream & os, string & extra,
3268                                  Paragraph * par, int & desc_on,
3269                                  Paragraph::depth_type depth) const
3270 {
3271         bool emph_flag = false;
3272
3273         LyXLayout const & style = textclasslist.Style(params.textclass,
3274                                                       par->getLayout());
3275
3276         LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3277
3278         int char_line_count = depth;
3279         //if (!style.free_spacing)
3280         //      os << string(depth,' ');
3281
3282         // parsing main loop
3283         for (Paragraph::size_type i = 0;
3284              i < par->size(); ++i) {
3285                 LyXFont font = par->getFont(params, i);
3286
3287                 // handle <emphasis> tag
3288                 if (font_old.emph() != font.emph()) {
3289                         if (font.emph() == LyXFont::ON) {
3290                                 os << "<emphasis>";
3291                                 emph_flag = true;
3292                         }else if(i) {
3293                                 os << "</emphasis>";
3294                                 emph_flag = false;
3295                         }
3296                 }
3297       
3298                 char c = par->getChar(i);
3299
3300                 if (c == Paragraph::META_INSET) {
3301                         Inset * inset = par->getInset(i);
3302                         inset->docbook(this, os);
3303                 } else {
3304                         string sgml_string;
3305                         par->sgmlConvertChar(c, sgml_string);
3306
3307                         if (style.pass_thru) {
3308                                 os << c;
3309                         } else if(style.free_spacing || c != ' ') {
3310                                         os << sgml_string;
3311                         } else if (desc_on ==1) {
3312                                 ++char_line_count;
3313                                 os << "\n</term><listitem><para>";
3314                                 desc_on = 2;
3315                         } else {
3316                                 os << ' ';
3317                         }
3318                 }
3319                 font_old = font;
3320         }
3321
3322         if (emph_flag) {
3323                 os << "</emphasis>";
3324         }
3325         
3326         // resets description flag correctly
3327         if (desc_on == 1) {
3328                 // <term> not closed...
3329                 os << "</term>";
3330         }
3331         if(style.free_spacing) os << '\n';
3332 }
3333
3334
3335 // This should be enabled when the Chktex class is implemented. (Asger)
3336 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3337 // Other flags: -wall -v0 -x
3338 int Buffer::runChktex()
3339 {
3340         if (!users->text) return 0;
3341
3342         users->owner()->prohibitInput();
3343
3344         // get LaTeX-Filename
3345         string const name = getLatexName();
3346         string path = OnlyPath(filename);
3347
3348         string const org_path = path;
3349         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3350                 path = tmppath;  
3351         }
3352
3353         Path p(path); // path to LaTeX file
3354         users->owner()->message(_("Running chktex..."));
3355
3356         // Remove all error insets
3357         bool const removedErrorInsets = users->removeAutoInsets();
3358
3359         // Generate the LaTeX file if neccessary
3360         makeLaTeXFile(name, org_path, false);
3361
3362         TeXErrors terr;
3363         Chktex chktex(lyxrc.chktex_command, name, filepath);
3364         int res = chktex.run(terr); // run chktex
3365
3366         if (res == -1) {
3367                 WriteAlert(_("chktex did not work!"),
3368                            _("Could not run with file:"), name);
3369         } else if (res > 0) {
3370                 // Insert all errors as errors boxes
3371                 users->insertErrors(terr);
3372         }
3373
3374         // if we removed error insets before we ran chktex or if we inserted
3375         // error insets after we ran chktex, this must be run:
3376         if (removedErrorInsets || res){
3377                 users->redraw();
3378                 users->fitCursor();
3379         }
3380         users->owner()->allowInput();
3381
3382         return res;
3383 }
3384
3385
3386 void Buffer::validate(LaTeXFeatures & features) const
3387 {
3388         Paragraph * par = paragraph;
3389         LyXTextClass const & tclass = 
3390                 textclasslist.TextClass(params.textclass);
3391     
3392         // AMS Style is at document level
3393         features.amsstyle = (params.use_amsmath ||
3394                              tclass.provides(LyXTextClass::amsmath));
3395     
3396         while (par) {
3397                 // We don't use "lyxerr.debug" because of speed. (Asger)
3398                 if (lyxerr.debugging(Debug::LATEX))
3399                         lyxerr << "Paragraph: " <<  par << endl;
3400
3401                 // Now just follow the list of paragraphs and run
3402                 // validate on each of them.
3403                 par->validate(features);
3404
3405                 // and then the next paragraph
3406                 par = par->next();
3407         }
3408
3409         // the bullet shapes are buffer level not paragraph level
3410         // so they are tested here
3411         for (int i = 0; i < 4; ++i) {
3412                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3413                         int const font = params.user_defined_bullets[i].getFont();
3414                         if (font == 0) {
3415                                 int const c = params
3416                                         .user_defined_bullets[i]
3417                                         .getCharacter();
3418                                 if (c == 16
3419                                    || c == 17
3420                                    || c == 25
3421                                    || c == 26
3422                                    || c == 31) {
3423                                         features.latexsym = true;
3424                                 }
3425                         } else if (font == 1) {
3426                                 features.amssymb = true;
3427                         } else if ((font >= 2 && font <= 5)) {
3428                                 features.pifont = true;
3429                         }
3430                 }
3431         }
3432         
3433         if (lyxerr.debugging(Debug::LATEX)) {
3434                 features.showStruct();
3435         }
3436 }
3437
3438
3439 // This function should be in Buffer because it's a buffer's property (ale)
3440 string const Buffer::getIncludeonlyList(char delim)
3441 {
3442         string lst;
3443         for (inset_iterator it = inset_iterator_begin();
3444             it != inset_iterator_end(); ++it) {
3445                 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3446                         InsetInclude * insetinc = 
3447                                 static_cast<InsetInclude *>(*it);
3448                         if (insetinc->isIncludeOnly()) {
3449                                 if (!lst.empty())
3450                                         lst += delim;
3451                                 lst += insetinc->getRelFileBaseName();
3452                         }
3453                 }
3454         }
3455         lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3456         return lst;
3457 }
3458
3459
3460 vector<string> const Buffer::getLabelList()
3461 {
3462         /// if this is a child document and the parent is already loaded
3463         /// Use the parent's list instead  [ale990407]
3464         if (!params.parentname.empty()
3465             && bufferlist.exists(params.parentname)) {
3466                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3467                 if (tmp)
3468                         return tmp->getLabelList();
3469         }
3470
3471         vector<string> label_list;
3472         for (inset_iterator it = inset_iterator_begin();
3473              it != inset_iterator_end(); ++it) {
3474                 vector<string> const l = (*it)->getLabelList();
3475                 label_list.insert(label_list.end(), l.begin(), l.end());
3476         }
3477         return label_list;
3478 }
3479
3480
3481 Buffer::Lists const Buffer::getLists() const
3482 {
3483         Lists l;
3484         Paragraph * par = paragraph;
3485
3486 #if 1
3487         std::pair<bool, LyXTextClassList::size_type> const tmp =
3488                 textclasslist.NumberOfLayout(params.textclass, "Caption");
3489         bool const found = tmp.first;
3490         LyXTextClassList::size_type const cap = tmp.second;
3491         
3492 #else
3493         // This is the prefered way to to this, but boost::tie can break
3494         // some compilers
3495         bool found;
3496         LyXTextClassList::size_type cap;
3497         boost::tie(found, cap) = textclasslist
3498                 .NumberOfLayout(params.textclass, "Caption");
3499 #endif
3500
3501         while (par) {
3502                 char const labeltype =
3503                         textclasslist.Style(params.textclass, 
3504                                             par->getLayout()).labeltype;
3505                 
3506                 if (labeltype >= LABEL_COUNTER_CHAPTER
3507                     && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3508                                 // insert this into the table of contents
3509                         SingleList & item = l["TOC"];
3510                         int depth = max(0,
3511                                         labeltype - 
3512                                         textclasslist.TextClass(params.textclass).maxcounter());
3513                         item.push_back(TocItem(par, depth, par->asString(this, true)));
3514                 }
3515                 // For each paragrph, traverse its insets and look for
3516                 // FLOAT_CODE
3517                 
3518                 if (found) {
3519                         Paragraph::inset_iterator it =
3520                                 par->inset_iterator_begin();
3521                         Paragraph::inset_iterator end =
3522                                 par->inset_iterator_end();
3523                         
3524                         for (; it != end; ++it) {
3525                                 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3526                                         InsetFloat * il =
3527                                                 static_cast<InsetFloat*>(*it);
3528                                         
3529                                         string const type = il->type();
3530                                         
3531                                         // Now find the caption in the float...
3532                                         // We now tranverse the paragraphs of
3533                                         // the inset...
3534                                         Paragraph * tmp = il->inset.paragraph();
3535                                         while (tmp) {
3536                                                 if (tmp->layout == cap) {
3537                                                         SingleList & item = l[type];
3538                                                         string const str =
3539                                                                 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3540                                                         item.push_back(TocItem(tmp, 0 , str));
3541                                                 }
3542                                                 tmp = tmp->next();
3543                                         }
3544                                 }
3545                         }
3546                 } else {
3547                         lyxerr << "caption not found" << endl;
3548                 }
3549                 
3550                 par = par->next();
3551         }
3552         return l;
3553 }
3554
3555
3556 // This is also a buffer property (ale)
3557 vector<pair<string, string> > const Buffer::getBibkeyList()
3558 {
3559         /// if this is a child document and the parent is already loaded
3560         /// Use the parent's list instead  [ale990412]
3561         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3562                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3563                 if (tmp)
3564                         return tmp->getBibkeyList();
3565         }
3566
3567         vector<pair<string, string> > keys;
3568         Paragraph * par = paragraph;
3569         while (par) {
3570                 if (par->bibkey)
3571                         keys.push_back(pair<string, string>(par->bibkey->getContents(),
3572                                                            par->asString(this, false)));
3573                 par = par->next();
3574         }
3575
3576         // Might be either using bibtex or a child has bibliography
3577         if (keys.empty()) {
3578                 for (inset_iterator it = inset_iterator_begin();
3579                         it != inset_iterator_end(); ++it) {
3580                         // Search for Bibtex or Include inset
3581                         if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3582                                 vector<pair<string,string> > tmp =
3583                                         static_cast<InsetBibtex*>(*it)->getKeys(this);
3584                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3585                         } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3586                                 vector<pair<string,string> > const tmp =
3587                                         static_cast<InsetInclude*>(*it)->getKeys();
3588                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3589                         }
3590                 }
3591         }
3592  
3593         return keys;
3594 }
3595
3596
3597 bool Buffer::isDepClean(string const & name) const
3598 {
3599         DEPCLEAN * item = dep_clean;
3600         while (item && item->master != name)
3601                 item = item->next;
3602         if (!item) return true;
3603         return item->clean;
3604 }
3605
3606
3607 void Buffer::markDepClean(string const & name)
3608 {
3609         if (!dep_clean) {
3610                 dep_clean = new DEPCLEAN;
3611                 dep_clean->clean = true;
3612                 dep_clean->master = name;
3613                 dep_clean->next = 0;
3614         } else {
3615                 DEPCLEAN * item = dep_clean;
3616                 while (item && item->master != name)
3617                         item = item->next;
3618                 if (item) {
3619                         item->clean = true;
3620                 } else {
3621                         item = new DEPCLEAN;
3622                         item->clean = true;
3623                         item->master = name;
3624                         item->next = 0;
3625                 }
3626         }
3627 }
3628
3629
3630 bool Buffer::dispatch(string const & command)
3631 {
3632         // Split command string into command and argument
3633         string cmd;
3634         string line = frontStrip(command);
3635         string const arg = strip(frontStrip(split(line, cmd, ' ')));
3636
3637         return dispatch(lyxaction.LookupFunc(cmd), arg);
3638 }
3639
3640
3641 bool Buffer::dispatch(int action, string const & argument)
3642 {
3643         bool dispatched = true;
3644         switch (action) {
3645                 case LFUN_EXPORT: 
3646                         Exporter::Export(this, argument, false);
3647                         break;
3648
3649                 default:
3650                         dispatched = false;
3651         }
3652         return dispatched;
3653 }
3654
3655
3656 void Buffer::resizeInsets(BufferView * bv)
3657 {
3658         /// then remove all LyXText in text-insets
3659         Paragraph * par = paragraph;
3660         for (; par; par = par->next()) {
3661             par->resizeInsetsLyXText(bv);
3662         }
3663 }
3664
3665
3666 void Buffer::redraw()
3667 {
3668         users->redraw(); 
3669         users->fitCursor(); 
3670 }
3671
3672
3673 void Buffer::changeLanguage(Language const * from, Language const * to)
3674 {
3675
3676         ParIterator end = par_iterator_end();
3677         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3678                 (*it)->changeLanguage(params, from, to);
3679 }
3680
3681
3682 bool Buffer::isMultiLingual()
3683 {
3684         ParIterator end = par_iterator_end();
3685         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3686                 if ((*it)->isMultiLingual(params))
3687                         return true;
3688
3689         return false;
3690 }
3691
3692
3693 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph,
3694                                        Paragraph::size_type pos)
3695         : par(paragraph)
3696 {
3697         it = par->InsetIterator(pos);
3698         if (it == par->inset_iterator_end()) {
3699                 par = par->next();
3700                 setParagraph();
3701         }
3702 }
3703
3704
3705 void Buffer::inset_iterator::setParagraph()
3706 {
3707         while (par) {
3708                 it = par->inset_iterator_begin();
3709                 if (it != par->inset_iterator_end())
3710                         return;
3711                 par = par->next();
3712         }
3713         //it = 0;
3714         // We maintain an invariant that whenever par = 0 then it = 0
3715 }
3716
3717
3718 Inset * Buffer::getInsetFromID(int id_arg) const
3719 {
3720         for (inset_iterator it = inset_const_iterator_begin();
3721                  it != inset_const_iterator_end(); ++it)
3722         {
3723                 if ((*it)->id() == id_arg)
3724                         return *it;
3725                 Inset * in = (*it)->getInsetFromID(id_arg);
3726                 if (in)
3727                         return in;
3728         }
3729         return 0;
3730 }
3731
3732
3733 Paragraph * Buffer::getParFromID(int id) const
3734 {
3735         if (id < 0) return 0;
3736         Paragraph * par = paragraph;
3737         while (par) {
3738                 if (par->id() == id) {
3739                         return par;
3740                 }
3741                 Paragraph * tmp = par->getParFromID(id);
3742                 if (tmp) {
3743                         return tmp;
3744                 }
3745                 par = par->next();
3746         }
3747         return 0;
3748 }
3749
3750
3751 ParIterator Buffer::par_iterator_begin()
3752 {
3753         return ParIterator(paragraph);
3754 }
3755
3756
3757 ParIterator Buffer::par_iterator_end()
3758 {
3759         return ParIterator();
3760 }