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