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