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