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