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