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