]> git.lyx.org Git - lyx.git/blob - src/buffer.C
more stuff from Lars' diff-6 (write one par at a time)
[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         ParagraphList::iterator pit = paragraphs.begin();
1847         ParagraphList::iterator pend = paragraphs.end();
1848         for (; pit != pend; ++pit)
1849                 pit->write(this, ofs, params, depth);
1850
1851         // Write marker that shows file is complete
1852         ofs << "\n\\the_end" << endl;
1853
1854         ofs.close();
1855
1856         // how to check if close went ok?
1857         // Following is an attempt... (BE 20001011)
1858
1859         // good() returns false if any error occured, including some
1860         //        formatting error.
1861         // bad()  returns true if something bad happened in the buffer,
1862         //        which should include file system full errors.
1863
1864         bool status = true;
1865         if (!ofs.good()) {
1866                 status = false;
1867 #if 0
1868                 if (ofs.bad()) {
1869                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1870                 } else {
1871                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1872                                << endl;
1873                 }
1874 #endif
1875         }
1876
1877         return status;
1878 }
1879
1880
1881 namespace {
1882
1883 pair<int, string> const addDepth(int depth, int ldepth)
1884 {
1885         int d = depth * 2;
1886         if (ldepth > depth)
1887                 d += (ldepth - depth) * 2;
1888         return make_pair(d, string(d, ' '));
1889 }
1890
1891 }
1892
1893
1894 string const Buffer::asciiParagraph(Paragraph const & par,
1895                                     unsigned int linelen,
1896                                     bool noparbreak) const
1897 {
1898         ostringstream buffer;
1899         Paragraph::depth_type depth = 0;
1900         int ltype = 0;
1901         Paragraph::depth_type ltype_depth = 0;
1902         bool ref_printed = false;
1903 //      if (!par->previous()) {
1904 #if 0
1905         // begins or ends a deeper area ?
1906         if (depth != par->params().depth()) {
1907                 if (par->params().depth() > depth) {
1908                         while (par->params().depth() > depth) {
1909                                 ++depth;
1910                         }
1911                 } else {
1912                         while (par->params().depth() < depth) {
1913                                 --depth;
1914                         }
1915                 }
1916         }
1917 #else
1918         depth = par.params().depth();
1919 #endif
1920
1921         // First write the layout
1922         string const & tmp = par.layout()->name();
1923         if (compare_no_case(tmp, "itemize") == 0) {
1924                 ltype = 1;
1925                 ltype_depth = depth + 1;
1926         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1927                 ltype = 2;
1928                 ltype_depth = depth + 1;
1929         } else if (contains(ascii_lowercase(tmp), "ection")) {
1930                 ltype = 3;
1931                 ltype_depth = depth + 1;
1932         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1933                 ltype = 4;
1934                 ltype_depth = depth + 1;
1935         } else if (compare_ascii_no_case(tmp, "description") == 0) {
1936                 ltype = 5;
1937                 ltype_depth = depth + 1;
1938         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1939                 ltype = 6;
1940                 ltype_depth = 0;
1941         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1942                 ltype = 7;
1943                 ltype_depth = 0;
1944         } else {
1945                 ltype = 0;
1946                 ltype_depth = 0;
1947         }
1948
1949         /* maybe some vertical spaces */
1950
1951         /* the labelwidthstring used in lists */
1952
1953         /* some lines? */
1954
1955         /* some pagebreaks? */
1956
1957         /* noindent ? */
1958
1959         /* what about the alignment */
1960 //      } else {
1961 //              lyxerr << "Should this ever happen?" << endl;
1962 //      }
1963
1964         // linelen <= 0 is special and means we don't have paragraph breaks
1965
1966         string::size_type currlinelen = 0;
1967
1968         if (!noparbreak) {
1969                 if (linelen > 0)
1970                         buffer << "\n\n";
1971
1972                 buffer << string(depth * 2, ' ');
1973                 currlinelen += depth * 2;
1974
1975                 //--
1976                 // we should probably change to the paragraph language in the
1977                 // gettext here (if possible) so that strings are outputted in
1978                 // the correct language! (20012712 Jug)
1979                 //--
1980                 switch (ltype) {
1981                 case 0: // Standard
1982                 case 4: // (Sub)Paragraph
1983                 case 5: // Description
1984                         break;
1985                 case 6: // Abstract
1986                         if (linelen > 0) {
1987                                 buffer << _("Abstract") << "\n\n";
1988                                 currlinelen = 0;
1989                         } else {
1990                                 string const abst = _("Abstract: ");
1991                                 buffer << abst;
1992                                 currlinelen += abst.length();
1993                         }
1994                         break;
1995                 case 7: // Bibliography
1996                         if (!ref_printed) {
1997                                 if (linelen > 0) {
1998                                         buffer << _("References") << "\n\n";
1999                                         currlinelen = 0;
2000                                 } else {
2001                                         string const refs = _("References: ");
2002                                         buffer << refs;
2003                                         currlinelen += refs.length();
2004                                 }
2005
2006                                 ref_printed = true;
2007                         }
2008                         break;
2009                 default:
2010                 {
2011                         string const parlab = par.params().labelString();
2012                         buffer << parlab << " ";
2013                         currlinelen += parlab.length() + 1;
2014                 }
2015                 break;
2016
2017                 }
2018         }
2019
2020         if (!currlinelen) {
2021                 pair<int, string> p = addDepth(depth, ltype_depth);
2022                 buffer << p.second;
2023                 currlinelen += p.first;
2024         }
2025
2026         // this is to change the linebreak to do it by word a bit more
2027         // intelligent hopefully! (only in the case where we have a
2028         // max linelenght!) (Jug)
2029
2030         string word;
2031
2032         for (pos_type i = 0; i < par.size(); ++i) {
2033                 char c = par.getUChar(params, i);
2034                 switch (c) {
2035                 case Paragraph::META_INSET:
2036                 {
2037                         Inset const * inset = par.getInset(i);
2038                         if (inset) {
2039                                 if (linelen > 0) {
2040                                         buffer << word;
2041                                         currlinelen += word.length();
2042                                         word.erase();
2043                                 }
2044                                 if (inset->ascii(this, buffer, linelen)) {
2045                                         // to be sure it breaks paragraph
2046                                         currlinelen += linelen;
2047                                 }
2048                         }
2049                 }
2050                 break;
2051
2052                 case Paragraph::META_NEWLINE:
2053                         if (linelen > 0) {
2054                                 buffer << word << "\n";
2055                                 word.erase();
2056
2057                                 pair<int, string> p = addDepth(depth,
2058                                                                ltype_depth);
2059                                 buffer << p.second;
2060                                 currlinelen = p.first;
2061                         }
2062                         break;
2063
2064                 case Paragraph::META_HFILL:
2065                         buffer << word << "\t";
2066                         currlinelen += word.length() + 1;
2067                         word.erase();
2068                         break;
2069
2070                 default:
2071                         if (c == ' ') {
2072                                 if (linelen > 0 &&
2073                                     currlinelen + word.length() > linelen - 10) {
2074                                         buffer << "\n";
2075                                         pair<int, string> p =
2076                                                 addDepth(depth, ltype_depth);
2077                                         buffer << p.second;
2078                                         currlinelen = p.first;
2079                                 }
2080
2081                                 buffer << word << ' ';
2082                                 currlinelen += word.length() + 1;
2083                                 word.erase();
2084
2085                         } else {
2086                                 if (c != '\0') {
2087                                         word += c;
2088                                 } else {
2089                                         lyxerr[Debug::INFO] <<
2090                                                 "writeAsciiFile: NULL char in structure." << endl;
2091                                 }
2092                                 if ((linelen > 0) &&
2093                                         (currlinelen + word.length()) > linelen)
2094                                 {
2095                                         buffer << "\n";
2096
2097                                         pair<int, string> p =
2098                                                 addDepth(depth, ltype_depth);
2099                                         buffer << p.second;
2100                                         currlinelen = p.first;
2101                                 }
2102                         }
2103                         break;
2104                 }
2105         }
2106         buffer << word;
2107         return buffer.str().c_str();
2108 }
2109
2110
2111 void Buffer::writeFileAscii(string const & fname, int linelen)
2112 {
2113         ofstream ofs(fname.c_str());
2114         if (!ofs) {
2115                 Alert::err_alert(_("Error: Cannot write file:"), fname);
2116                 return;
2117         }
2118         writeFileAscii(ofs, linelen);
2119 }
2120
2121
2122 void Buffer::writeFileAscii(ostream & os, int linelen)
2123 {
2124         ParagraphList::iterator beg = paragraphs.begin();
2125         ParagraphList::iterator end = paragraphs.end();
2126         ParagraphList::iterator it = beg;
2127         for (; it != end; ++it) {
2128                 os << asciiParagraph(*it, linelen, it == beg);
2129         }
2130         os << "\n";
2131 }
2132
2133
2134 bool use_babel;
2135
2136
2137 void Buffer::makeLaTeXFile(string const & fname,
2138                            string const & original_path,
2139                            bool nice, bool only_body, bool only_preamble)
2140 {
2141         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2142
2143         ofstream ofs(fname.c_str());
2144         if (!ofs) {
2145                 Alert::err_alert(_("Error: Cannot open file: "), fname);
2146                 return;
2147         }
2148
2149         makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
2150
2151         ofs.close();
2152         if (ofs.fail()) {
2153                 lyxerr << "File was not closed properly." << endl;
2154         }
2155 }
2156
2157
2158 void Buffer::makeLaTeXFile(ostream & os,
2159                            string const & original_path,
2160                            bool nice, bool only_body, bool only_preamble)
2161 {
2162         niceFile = nice; // this will be used by Insetincludes.
2163
2164         // validate the buffer.
2165         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
2166         LaTeXFeatures features(params);
2167         validate(features);
2168         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
2169
2170         texrow.reset();
2171         // The starting paragraph of the coming rows is the
2172         // first paragraph of the document. (Asger)
2173         texrow.start(&*(paragraphs.begin()), 0);
2174
2175         if (!only_body && nice) {
2176                 os << "%% " << lyx_docversion << " created this file.  "
2177                         "For more info, see http://www.lyx.org/.\n"
2178                         "%% Do not edit unless you really know what "
2179                         "you are doing.\n";
2180                 texrow.newline();
2181                 texrow.newline();
2182         }
2183         lyxerr[Debug::INFO] << "lyx header finished" << endl;
2184         // There are a few differences between nice LaTeX and usual files:
2185         // usual is \batchmode and has a
2186         // special input@path to allow the including of figures
2187         // with either \input or \includegraphics (what figinsets do).
2188         // input@path is set when the actual parameter
2189         // original_path is set. This is done for usual tex-file, but not
2190         // for nice-latex-file. (Matthias 250696)
2191         if (!only_body) {
2192                 if (!nice) {
2193                         // code for usual, NOT nice-latex-file
2194                         os << "\\batchmode\n"; // changed
2195                         // from \nonstopmode
2196                         texrow.newline();
2197                 }
2198                 if (!original_path.empty()) {
2199                         string inputpath = os::external_path(original_path);
2200                         subst(inputpath, "~", "\\string~");
2201                         os << "\\makeatletter\n"
2202                             << "\\def\\input@path{{"
2203                             << inputpath << "/}}\n"
2204                             << "\\makeatother\n";
2205                         texrow.newline();
2206                         texrow.newline();
2207                         texrow.newline();
2208                 }
2209
2210                 os << "\\documentclass";
2211
2212                 LyXTextClass const & tclass = params.getLyXTextClass();
2213
2214                 ostringstream options; // the document class options.
2215
2216                 if (tokenPos(tclass.opt_fontsize(),
2217                              '|', params.fontsize) >= 0) {
2218                         // only write if existing in list (and not default)
2219                         options << params.fontsize << "pt,";
2220                 }
2221
2222
2223                 if (!params.use_geometry &&
2224                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2225                         switch (params.papersize) {
2226                         case BufferParams::PAPER_A4PAPER:
2227                                 options << "a4paper,";
2228                                 break;
2229                         case BufferParams::PAPER_USLETTER:
2230                                 options << "letterpaper,";
2231                                 break;
2232                         case BufferParams::PAPER_A5PAPER:
2233                                 options << "a5paper,";
2234                                 break;
2235                         case BufferParams::PAPER_B5PAPER:
2236                                 options << "b5paper,";
2237                                 break;
2238                         case BufferParams::PAPER_EXECUTIVEPAPER:
2239                                 options << "executivepaper,";
2240                                 break;
2241                         case BufferParams::PAPER_LEGALPAPER:
2242                                 options << "legalpaper,";
2243                                 break;
2244                         }
2245                 }
2246
2247                 // if needed
2248                 if (params.sides != tclass.sides()) {
2249                         switch (params.sides) {
2250                         case LyXTextClass::OneSide:
2251                                 options << "oneside,";
2252                                 break;
2253                         case LyXTextClass::TwoSides:
2254                                 options << "twoside,";
2255                                 break;
2256                         }
2257                 }
2258
2259                 // if needed
2260                 if (params.columns != tclass.columns()) {
2261                         if (params.columns == 2)
2262                                 options << "twocolumn,";
2263                         else
2264                                 options << "onecolumn,";
2265                 }
2266
2267                 if (!params.use_geometry
2268                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2269                         options << "landscape,";
2270
2271                 // language should be a parameter to \documentclass
2272                 use_babel = false;
2273                 ostringstream language_options;
2274                 if (params.language->babel() == "hebrew"
2275                     && default_language->babel() != "hebrew")
2276                          // This seems necessary
2277                         features.useLanguage(default_language);
2278
2279                 if (lyxrc.language_use_babel ||
2280                     params.language->lang() != lyxrc.default_language ||
2281                     features.hasLanguages()) {
2282                         use_babel = true;
2283                         language_options << features.getLanguages();
2284                         language_options << params.language->babel();
2285                         if (lyxrc.language_global_options)
2286                                 options << language_options.str() << ',';
2287                 }
2288
2289                 // the user-defined options
2290                 if (!params.options.empty()) {
2291                         options << params.options << ',';
2292                 }
2293
2294                 string strOptions(options.str().c_str());
2295                 if (!strOptions.empty()) {
2296                         strOptions = rtrim(strOptions, ",");
2297                         os << '[' << strOptions << ']';
2298                 }
2299
2300                 os << '{' << tclass.latexname() << "}\n";
2301                 texrow.newline();
2302                 // end of \documentclass defs
2303
2304                 // font selection must be done before loading fontenc.sty
2305                 // The ae package is not needed when using OT1 font encoding.
2306                 if (params.fonts != "default" &&
2307                     (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2308                         os << "\\usepackage{" << params.fonts << "}\n";
2309                         texrow.newline();
2310                         if (params.fonts == "ae") {
2311                                 os << "\\usepackage{aecompl}\n";
2312                                 texrow.newline();
2313                         }
2314                 }
2315                 // this one is not per buffer
2316                 if (lyxrc.fontenc != "default") {
2317                         os << "\\usepackage[" << lyxrc.fontenc
2318                             << "]{fontenc}\n";
2319                         texrow.newline();
2320                 }
2321
2322                 if (params.inputenc == "auto") {
2323                         string const doc_encoding =
2324                                 params.language->encoding()->LatexName();
2325
2326                         // Create a list with all the input encodings used
2327                         // in the document
2328                         set<string> encodings = features.getEncodingSet(doc_encoding);
2329
2330                         os << "\\usepackage[";
2331                         std::copy(encodings.begin(), encodings.end(),
2332                                   std::ostream_iterator<string>(os, ","));
2333                         os << doc_encoding << "]{inputenc}\n";
2334                         texrow.newline();
2335                 } else if (params.inputenc != "default") {
2336                         os << "\\usepackage[" << params.inputenc
2337                             << "]{inputenc}\n";
2338                         texrow.newline();
2339                 }
2340
2341                 // At the very beginning the text parameters.
2342                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2343                         switch (params.paperpackage) {
2344                         case BufferParams::PACKAGE_A4:
2345                                 os << "\\usepackage{a4}\n";
2346                                 texrow.newline();
2347                                 break;
2348                         case BufferParams::PACKAGE_A4WIDE:
2349                                 os << "\\usepackage{a4wide}\n";
2350                                 texrow.newline();
2351                                 break;
2352                         case BufferParams::PACKAGE_WIDEMARGINSA4:
2353                                 os << "\\usepackage[widemargins]{a4}\n";
2354                                 texrow.newline();
2355                                 break;
2356                         }
2357                 }
2358                 if (params.use_geometry) {
2359                         os << "\\usepackage{geometry}\n";
2360                         texrow.newline();
2361                         os << "\\geometry{verbose";
2362                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2363                                 os << ",landscape";
2364                         switch (params.papersize2) {
2365                         case BufferParams::VM_PAPER_CUSTOM:
2366                                 if (!params.paperwidth.empty())
2367                                         os << ",paperwidth="
2368                                             << params.paperwidth;
2369                                 if (!params.paperheight.empty())
2370                                         os << ",paperheight="
2371                                             << params.paperheight;
2372                                 break;
2373                         case BufferParams::VM_PAPER_USLETTER:
2374                                 os << ",letterpaper";
2375                                 break;
2376                         case BufferParams::VM_PAPER_USLEGAL:
2377                                 os << ",legalpaper";
2378                                 break;
2379                         case BufferParams::VM_PAPER_USEXECUTIVE:
2380                                 os << ",executivepaper";
2381                                 break;
2382                         case BufferParams::VM_PAPER_A3:
2383                                 os << ",a3paper";
2384                                 break;
2385                         case BufferParams::VM_PAPER_A4:
2386                                 os << ",a4paper";
2387                                 break;
2388                         case BufferParams::VM_PAPER_A5:
2389                                 os << ",a5paper";
2390                                 break;
2391                         case BufferParams::VM_PAPER_B3:
2392                                 os << ",b3paper";
2393                                 break;
2394                         case BufferParams::VM_PAPER_B4:
2395                                 os << ",b4paper";
2396                                 break;
2397                         case BufferParams::VM_PAPER_B5:
2398                                 os << ",b5paper";
2399                                 break;
2400                         default:
2401                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2402                                 switch (lyxrc.default_papersize) {
2403                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2404                                 case BufferParams::PAPER_USLETTER:
2405                                         os << ",letterpaper";
2406                                         break;
2407                                 case BufferParams::PAPER_LEGALPAPER:
2408                                         os << ",legalpaper";
2409                                         break;
2410                                 case BufferParams::PAPER_EXECUTIVEPAPER:
2411                                         os << ",executivepaper";
2412                                         break;
2413                                 case BufferParams::PAPER_A3PAPER:
2414                                         os << ",a3paper";
2415                                         break;
2416                                 case BufferParams::PAPER_A4PAPER:
2417                                         os << ",a4paper";
2418                                         break;
2419                                 case BufferParams::PAPER_A5PAPER:
2420                                         os << ",a5paper";
2421                                         break;
2422                                 case BufferParams::PAPER_B5PAPER:
2423                                         os << ",b5paper";
2424                                         break;
2425                                 }
2426                         }
2427                         if (!params.topmargin.empty())
2428                                 os << ",tmargin=" << params.topmargin;
2429                         if (!params.bottommargin.empty())
2430                                 os << ",bmargin=" << params.bottommargin;
2431                         if (!params.leftmargin.empty())
2432                                 os << ",lmargin=" << params.leftmargin;
2433                         if (!params.rightmargin.empty())
2434                                 os << ",rmargin=" << params.rightmargin;
2435                         if (!params.headheight.empty())
2436                                 os << ",headheight=" << params.headheight;
2437                         if (!params.headsep.empty())
2438                                 os << ",headsep=" << params.headsep;
2439                         if (!params.footskip.empty())
2440                                 os << ",footskip=" << params.footskip;
2441                         os << "}\n";
2442                         texrow.newline();
2443                 }
2444
2445                 if (tokenPos(tclass.opt_pagestyle(),
2446                              '|', params.pagestyle) >= 0) {
2447                         if (params.pagestyle == "fancy") {
2448                                 os << "\\usepackage{fancyhdr}\n";
2449                                 texrow.newline();
2450                         }
2451                         os << "\\pagestyle{" << params.pagestyle << "}\n";
2452                         texrow.newline();
2453                 }
2454
2455                 if (params.secnumdepth != tclass.secnumdepth()) {
2456                         os << "\\setcounter{secnumdepth}{"
2457                             << params.secnumdepth
2458                             << "}\n";
2459                         texrow.newline();
2460                 }
2461                 if (params.tocdepth != tclass.tocdepth()) {
2462                         os << "\\setcounter{tocdepth}{"
2463                             << params.tocdepth
2464                             << "}\n";
2465                         texrow.newline();
2466                 }
2467
2468                 if (params.paragraph_separation) {
2469                         switch (params.defskip.kind()) {
2470                         case VSpace::SMALLSKIP:
2471                                 os << "\\setlength\\parskip{\\smallskipamount}\n";
2472                                 break;
2473                         case VSpace::MEDSKIP:
2474                                 os << "\\setlength\\parskip{\\medskipamount}\n";
2475                                 break;
2476                         case VSpace::BIGSKIP:
2477                                 os << "\\setlength\\parskip{\\bigskipamount}\n";
2478                                 break;
2479                         case VSpace::LENGTH:
2480                                 os << "\\setlength\\parskip{"
2481                                     << params.defskip.length().asLatexString()
2482                                     << "}\n";
2483                                 break;
2484                         default: // should never happen // Then delete it.
2485                                 os << "\\setlength\\parskip{\\medskipamount}\n";
2486                                 break;
2487                         }
2488                         texrow.newline();
2489
2490                         os << "\\setlength\\parindent{0pt}\n";
2491                         texrow.newline();
2492                 }
2493
2494                 // Now insert the LyX specific LaTeX commands...
2495
2496                 // The optional packages;
2497                 string preamble(features.getPackages());
2498
2499                 // this might be useful...
2500                 preamble += "\n\\makeatletter\n";
2501
2502                 // Some macros LyX will need
2503                 string tmppreamble(features.getMacros());
2504
2505                 if (!tmppreamble.empty()) {
2506                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2507                                 "LyX specific LaTeX commands.\n"
2508                                 + tmppreamble + '\n';
2509                 }
2510
2511                 // the text class specific preamble
2512                 tmppreamble = features.getTClassPreamble();
2513                 if (!tmppreamble.empty()) {
2514                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2515                                 "Textclass specific LaTeX commands.\n"
2516                                 + tmppreamble + '\n';
2517                 }
2518
2519                 /* the user-defined preamble */
2520                 if (!params.preamble.empty()) {
2521                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2522                                 "User specified LaTeX commands.\n"
2523                                 + params.preamble + '\n';
2524                 }
2525
2526                 // Itemize bullet settings need to be last in case the user
2527                 // defines their own bullets that use a package included
2528                 // in the user-defined preamble -- ARRae
2529                 // Actually it has to be done much later than that
2530                 // since some packages like frenchb make modifications
2531                 // at \begin{document} time -- JMarc
2532                 string bullets_def;
2533                 for (int i = 0; i < 4; ++i) {
2534                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2535                                 if (bullets_def.empty())
2536                                         bullets_def="\\AtBeginDocument{\n";
2537                                 bullets_def += "  \\renewcommand{\\labelitemi";
2538                                 switch (i) {
2539                                 // `i' is one less than the item to modify
2540                                 case 0:
2541                                         break;
2542                                 case 1:
2543                                         bullets_def += 'i';
2544                                         break;
2545                                 case 2:
2546                                         bullets_def += "ii";
2547                                         break;
2548                                 case 3:
2549                                         bullets_def += 'v';
2550                                         break;
2551                                 }
2552                                 bullets_def += "}{" +
2553                                   params.user_defined_bullets[i].getText()
2554                                   + "}\n";
2555                         }
2556                 }
2557
2558                 if (!bullets_def.empty())
2559                   preamble += bullets_def + "}\n\n";
2560
2561                 int const nlines =
2562                         int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2563                 for (int j = 0; j != nlines; ++j) {
2564                         texrow.newline();
2565                 }
2566
2567                 // We try to load babel late, in case it interferes
2568                 // with other packages.
2569                 if (use_babel) {
2570                         string tmp = lyxrc.language_package;
2571                         if (!lyxrc.language_global_options
2572                             && tmp == "\\usepackage{babel}")
2573                                 tmp = string("\\usepackage[") +
2574                                         language_options.str().c_str() +
2575                                         "]{babel}";
2576                         preamble += tmp + "\n";
2577                         preamble += features.getBabelOptions();
2578                 }
2579
2580                 preamble += "\\makeatother\n";
2581
2582                 os << preamble;
2583
2584                 if (only_preamble)
2585                         return;
2586
2587                 // make the body.
2588                 os << "\\begin{document}\n";
2589                 texrow.newline();
2590         } // only_body
2591         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2592
2593         if (!lyxrc.language_auto_begin) {
2594                 os << subst(lyxrc.language_command_begin, "$$lang",
2595                              params.language->babel())
2596                     << endl;
2597                 texrow.newline();
2598         }
2599
2600         latexParagraphs(os, &*(paragraphs.begin()), 0, texrow);
2601
2602         // add this just in case after all the paragraphs
2603         os << endl;
2604         texrow.newline();
2605
2606         if (!lyxrc.language_auto_end) {
2607                 os << subst(lyxrc.language_command_end, "$$lang",
2608                              params.language->babel())
2609                     << endl;
2610                 texrow.newline();
2611         }
2612
2613         if (!only_body) {
2614                 os << "\\end{document}\n";
2615                 texrow.newline();
2616
2617                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2618         } else {
2619                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2620                                      << endl;
2621         }
2622
2623         // Just to be sure. (Asger)
2624         texrow.newline();
2625
2626         lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2627         lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2628
2629         // we want this to be true outside previews (for insetexternal)
2630         niceFile = true;
2631 }
2632
2633
2634 //
2635 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2636 //
2637 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2638                              Paragraph * endpar, TexRow & texrow,
2639                              bool moving_arg) const
2640 {
2641         bool was_title = false;
2642         bool already_title = false;
2643
2644         // if only_body
2645         while (par != endpar) {
2646                 Inset * in = par->inInset();
2647                 // well we have to check if we are in an inset with unlimited
2648                 // length (all in one row) if that is true then we don't allow
2649                 // any special options in the paragraph and also we don't allow
2650                 // any environment other then "Standard" to be valid!
2651                 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2652                         LyXLayout_ptr const & layout = par->layout();
2653
2654                         if (layout->intitle) {
2655                                 if (already_title) {
2656                                         lyxerr <<"Error in latexParagraphs: You"
2657                                                 " should not mix title layouts"
2658                                                 " with normal ones." << endl;
2659                                 } else
2660                                         was_title = true;
2661                         } else if (was_title && !already_title) {
2662                                 ofs << "\\maketitle\n";
2663                                 texrow.newline();
2664                                 already_title = true;
2665                                 was_title = false;
2666                         }
2667
2668                         if (layout->isEnvironment() ||
2669                                 !par->params().leftIndent().zero())
2670                         {
2671                                 par = par->TeXEnvironment(this, params, ofs, texrow);
2672                         } else {
2673                                 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2674                         }
2675                 } else {
2676                         par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2677                 }
2678         }
2679         // It might be that we only have a title in this document
2680         if (was_title && !already_title) {
2681                 ofs << "\\maketitle\n";
2682                 texrow.newline();
2683         }
2684 }
2685
2686
2687 bool Buffer::isLatex() const
2688 {
2689         return params.getLyXTextClass().outputType() == LATEX;
2690 }
2691
2692
2693 bool Buffer::isLinuxDoc() const
2694 {
2695         return params.getLyXTextClass().outputType() == LINUXDOC;
2696 }
2697
2698
2699 bool Buffer::isLiterate() const
2700 {
2701         return params.getLyXTextClass().outputType() == LITERATE;
2702 }
2703
2704
2705 bool Buffer::isDocBook() const
2706 {
2707         return params.getLyXTextClass().outputType() == DOCBOOK;
2708 }
2709
2710
2711 bool Buffer::isSGML() const
2712 {
2713         LyXTextClass const & tclass = params.getLyXTextClass();
2714
2715         return tclass.outputType() == LINUXDOC ||
2716                tclass.outputType() == DOCBOOK;
2717 }
2718
2719
2720 int Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2721                          string const & latexname) const
2722 {
2723         if (!latexname.empty() && latexname != "!-- --") {
2724                 if (!mixcont)
2725                         os << string(" ",depth);
2726                 os << "<" << latexname << ">";
2727         }
2728
2729         if (!mixcont)
2730                 os << endl;
2731
2732         return mixcont?0:1;
2733 }
2734
2735
2736 int Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2737                           string const & latexname) const
2738 {
2739         if (!latexname.empty() && latexname != "!-- --") {
2740                 if (!mixcont)
2741                         os << endl << string(" ",depth);
2742                 os << "</" << latexname << ">";
2743         }
2744
2745         if (!mixcont)
2746                 os << endl;
2747
2748         return mixcont?0:1;
2749 }
2750
2751
2752 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2753 {
2754         ofstream ofs(fname.c_str());
2755
2756         if (!ofs) {
2757                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2758                 return;
2759         }
2760
2761         niceFile = nice; // this will be used by included files.
2762
2763         LaTeXFeatures features(params);
2764
2765         validate(features);
2766
2767         texrow.reset();
2768
2769         LyXTextClass const & tclass = params.getLyXTextClass();
2770
2771         string top_element = tclass.latexname();
2772
2773         if (!body_only) {
2774                 ofs << "<!doctype linuxdoc system";
2775
2776                 string preamble = params.preamble;
2777                 const string name = nice ? ChangeExtension(filename_, ".sgml")
2778                          : fname;
2779                 preamble += features.getIncludedFiles(name);
2780                 preamble += features.getLyXSGMLEntities();
2781
2782                 if (!preamble.empty()) {
2783                         ofs << " [ " << preamble << " ]";
2784                 }
2785                 ofs << ">\n\n";
2786
2787                 if (params.options.empty())
2788                         sgmlOpenTag(ofs, 0, false, top_element);
2789                 else {
2790                         string top = top_element;
2791                         top += " ";
2792                         top += params.options;
2793                         sgmlOpenTag(ofs, 0, false, top);
2794                 }
2795         }
2796
2797         ofs << "<!-- "  << lyx_docversion
2798             << " created this file. For more info see http://www.lyx.org/"
2799             << " -->\n";
2800
2801         Paragraph::depth_type depth = 0; // paragraph depth
2802         Paragraph * par = &*(paragraphs.begin());
2803         string item_name;
2804         vector<string> environment_stack(5);
2805
2806         while (par) {
2807                 LyXLayout_ptr const & style = par->layout();
2808                 // treat <toc> as a special case for compatibility with old code
2809                 if (par->isInset(0)) {
2810                         Inset * inset = par->getInset(0);
2811                         Inset::Code lyx_code = inset->lyxCode();
2812                         if (lyx_code == Inset::TOC_CODE) {
2813                                 string const temp = "toc";
2814                                 sgmlOpenTag(ofs, depth, false, temp);
2815
2816                                 par = par->next();
2817                                 continue;
2818                         }
2819                 }
2820
2821                 // environment tag closing
2822                 for (; depth > par->params().depth(); --depth) {
2823                         sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2824                         environment_stack[depth].erase();
2825                 }
2826
2827                 // write opening SGML tags
2828                 switch (style->latextype) {
2829                 case LATEX_PARAGRAPH:
2830                         if (depth == par->params().depth()
2831                            && !environment_stack[depth].empty()) {
2832                                 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2833                                 environment_stack[depth].erase();
2834                                 if (depth)
2835                                         --depth;
2836                                 else
2837                                         ofs << "</p>";
2838                         }
2839                         sgmlOpenTag(ofs, depth, false, style->latexname());
2840                         break;
2841
2842                 case LATEX_COMMAND:
2843                         if (depth!= 0)
2844                                 sgmlError(par, 0,
2845                                           _("Error : Wrong depth for"
2846                                             " LatexType Command.\n"));
2847
2848                         if (!environment_stack[depth].empty()) {
2849                                 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2850                                 ofs << "</p>";
2851                         }
2852
2853                         environment_stack[depth].erase();
2854                         sgmlOpenTag(ofs, depth, false, style->latexname());
2855                         break;
2856
2857                 case LATEX_ENVIRONMENT:
2858                 case LATEX_ITEM_ENVIRONMENT:
2859                 {
2860                         string const & latexname = style->latexname();
2861
2862                         if (depth == par->params().depth()
2863                             && environment_stack[depth] != latexname) {
2864                                 sgmlCloseTag(ofs, depth, false,
2865                                              environment_stack[depth]);
2866                                 environment_stack[depth].erase();
2867                         }
2868                         if (depth < par->params().depth()) {
2869                                depth = par->params().depth();
2870                                environment_stack[depth].erase();
2871                         }
2872                         if (environment_stack[depth] != latexname) {
2873                                 if (depth == 0) {
2874                                         sgmlOpenTag(ofs, depth, false, "p");
2875                                 }
2876                                 sgmlOpenTag(ofs, depth, false, latexname);
2877
2878                                 if (environment_stack.size() == depth + 1)
2879                                         environment_stack.push_back("!-- --");
2880                                 environment_stack[depth] = latexname;
2881                         }
2882
2883                         if (style->latexparam() == "CDATA")
2884                                 ofs << "<![CDATA[";
2885
2886                         if (style->latextype == LATEX_ENVIRONMENT) break;
2887
2888                         if (style->labeltype == LABEL_MANUAL)
2889                                 item_name = "tag";
2890                         else
2891                                 item_name = "item";
2892
2893                         sgmlOpenTag(ofs, depth + 1, false, item_name);
2894                 }
2895                 break;
2896
2897                 default:
2898                         sgmlOpenTag(ofs, depth, false, style->latexname());
2899                         break;
2900                 }
2901
2902                 simpleLinuxDocOnePar(ofs, par, depth);
2903
2904                 par = par->next();
2905
2906                 ofs << "\n";
2907                 // write closing SGML tags
2908                 switch (style->latextype) {
2909                 case LATEX_COMMAND:
2910                         break;
2911                 case LATEX_ENVIRONMENT:
2912                 case LATEX_ITEM_ENVIRONMENT:
2913                         if (style->latexparam() == "CDATA")
2914                                 ofs << "]]>";
2915                         break;
2916                 default:
2917                         sgmlCloseTag(ofs, depth, false, style->latexname());
2918                         break;
2919                 }
2920         }
2921
2922         // Close open tags
2923         for (int i = depth; i >= 0; --i)
2924                 sgmlCloseTag(ofs, depth, false, environment_stack[i]);
2925
2926         if (!body_only) {
2927                 ofs << "\n\n";
2928                 sgmlCloseTag(ofs, 0, false, top_element);
2929         }
2930
2931         ofs.close();
2932         // How to check for successful close
2933
2934         // we want this to be true outside previews (for insetexternal)
2935         niceFile = true;
2936 }
2937
2938
2939 // checks, if newcol chars should be put into this line
2940 // writes newline, if necessary.
2941 namespace {
2942
2943 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2944                           string::size_type newcol)
2945 {
2946         colcount += newcol;
2947         if (colcount > lyxrc.ascii_linelen) {
2948                 os << "\n";
2949                 colcount = newcol; // assume write after this call
2950         }
2951 }
2952
2953 enum PAR_TAG {
2954         NONE=0,
2955         TT = 1,
2956         SF = 2,
2957         BF = 4,
2958         IT = 8,
2959         SL = 16,
2960         EM = 32
2961 };
2962
2963
2964 string tag_name(PAR_TAG const & pt) {
2965         switch (pt) {
2966         case NONE: return "!-- --";
2967         case TT: return "tt";
2968         case SF: return "sf";
2969         case BF: return "bf";
2970         case IT: return "it";
2971         case SL: return "sl";
2972         case EM: return "em";
2973         }
2974         return "";
2975 }
2976
2977
2978 inline
2979 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2980 {
2981         p1 = static_cast<PAR_TAG>(p1 | p2);
2982 }
2983
2984
2985 inline
2986 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2987 {
2988         p1 = static_cast<PAR_TAG>(p1 & ~p2);
2989 }
2990
2991 } // anon
2992
2993
2994 // Handle internal paragraph parsing -- layout already processed.
2995 void Buffer::simpleLinuxDocOnePar(ostream & os,
2996         Paragraph * par,
2997         Paragraph::depth_type /*depth*/)
2998 {
2999         LyXLayout_ptr const & style = par->layout();
3000
3001         string::size_type char_line_count = 5;     // Heuristic choice ;-)
3002
3003         // gets paragraph main font
3004         LyXFont font_old;
3005         bool desc_on;
3006         if (style->labeltype == LABEL_MANUAL) {
3007                 font_old = style->labelfont;
3008                 desc_on = true;
3009         } else {
3010                 font_old = style->font;
3011                 desc_on = false;
3012         }
3013
3014         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
3015         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
3016         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
3017         bool is_em = false;
3018
3019         stack<PAR_TAG> tag_state;
3020         // parsing main loop
3021         for (pos_type i = 0; i < par->size(); ++i) {
3022
3023                 PAR_TAG tag_close = NONE;
3024                 list < PAR_TAG > tag_open;
3025
3026                 LyXFont const font = par->getFont(params, i);
3027
3028                 if (font_old.family() != font.family()) {
3029                         switch (family_type) {
3030                         case LyXFont::SANS_FAMILY:
3031                                 tag_close |= SF;
3032                                 break;
3033                         case LyXFont::TYPEWRITER_FAMILY:
3034                                 tag_close |= TT;
3035                                 break;
3036                         default:
3037                                 break;
3038                         }
3039
3040                         family_type = font.family();
3041
3042                         switch (family_type) {
3043                         case LyXFont::SANS_FAMILY:
3044                                 tag_open.push_back(SF);
3045                                 break;
3046                         case LyXFont::TYPEWRITER_FAMILY:
3047                                 tag_open.push_back(TT);
3048                                 break;
3049                         default:
3050                                 break;
3051                         }
3052                 }
3053
3054                 if (font_old.series() != font.series()) {
3055                         switch (series_type) {
3056                         case LyXFont::BOLD_SERIES:
3057                                 tag_close |= BF;
3058                                 break;
3059                         default:
3060                                 break;
3061                         }
3062
3063                         series_type = font.series();
3064
3065                         switch (series_type) {
3066                         case LyXFont::BOLD_SERIES:
3067                                 tag_open.push_back(BF);
3068                                 break;
3069                         default:
3070                                 break;
3071                         }
3072
3073                 }
3074
3075                 if (font_old.shape() != font.shape()) {
3076                         switch (shape_type) {
3077                         case LyXFont::ITALIC_SHAPE:
3078                                 tag_close |= IT;
3079                                 break;
3080                         case LyXFont::SLANTED_SHAPE:
3081                                 tag_close |= SL;
3082                                 break;
3083                         default:
3084                                 break;
3085                         }
3086
3087                         shape_type = font.shape();
3088
3089                         switch (shape_type) {
3090                         case LyXFont::ITALIC_SHAPE:
3091                                 tag_open.push_back(IT);
3092                                 break;
3093                         case LyXFont::SLANTED_SHAPE:
3094                                 tag_open.push_back(SL);
3095                                 break;
3096                         default:
3097                                 break;
3098                         }
3099                 }
3100                 // handle <em> tag
3101                 if (font_old.emph() != font.emph()) {
3102                         if (font.emph() == LyXFont::ON) {
3103                                 tag_open.push_back(EM);
3104                                 is_em = true;
3105                         }
3106                         else if (is_em) {
3107                                 tag_close |= EM;
3108                                 is_em = false;
3109                         }
3110                 }
3111
3112                 list < PAR_TAG > temp;
3113                 while (!tag_state.empty() && tag_close) {
3114                         PAR_TAG k =  tag_state.top();
3115                         tag_state.pop();
3116                         os << "</" << tag_name(k) << ">";
3117                         if (tag_close & k)
3118                                 reset(tag_close,k);
3119                         else
3120                                 temp.push_back(k);
3121                 }
3122
3123                 for(list< PAR_TAG >::const_iterator j = temp.begin();
3124                     j != temp.end(); ++j) {
3125                         tag_state.push(*j);
3126                         os << "<" << tag_name(*j) << ">";
3127                 }
3128
3129                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
3130                     j != tag_open.end(); ++j) {
3131                         tag_state.push(*j);
3132                         os << "<" << tag_name(*j) << ">";
3133                 }
3134
3135                 char c = par->getChar(i);
3136
3137                 if (c == Paragraph::META_INSET) {
3138                         Inset * inset = par->getInset(i);
3139                         inset->linuxdoc(this, os);
3140                         font_old = font;
3141                         continue;
3142                 }
3143
3144                 if (style->latexparam() == "CDATA") {
3145                         // "TeX"-Mode on == > SGML-Mode on.
3146                         if (c != '\0')
3147                                 os << c;
3148                         ++char_line_count;
3149                 } else {
3150                         bool ws;
3151                         string str;
3152                         boost::tie(ws, str) = sgml::escapeChar(c);
3153                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
3154                                 // in freespacing mode, spaces are
3155                                 // non-breaking characters
3156                                 if (desc_on) {// if char is ' ' then...
3157
3158                                         ++char_line_count;
3159                                         sgmlLineBreak(os, char_line_count, 6);
3160                                         os << "</tag>";
3161                                         desc_on = false;
3162                                 } else  {
3163                                         sgmlLineBreak(os, char_line_count, 1);
3164                                         os << c;
3165                                 }
3166                         } else {
3167                                 os << str;
3168                                 char_line_count += str.length();
3169                         }
3170                 }
3171                 font_old = font;
3172         }
3173
3174         while (!tag_state.empty()) {
3175                 os << "</" << tag_name(tag_state.top()) << ">";
3176                 tag_state.pop();
3177         }
3178
3179         // resets description flag correctly
3180         if (desc_on) {
3181                 // <tag> not closed...
3182                 sgmlLineBreak(os, char_line_count, 6);
3183                 os << "</tag>";
3184         }
3185 }
3186
3187
3188 // Print an error message.
3189 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
3190         string const & /*message*/) const
3191 {
3192 #ifdef WITH_WARNINGS
3193 #warning This is wrong we cannot insert an inset like this!!!
3194         // I guess this was Jose' so I explain you more or less why this
3195         // is wrong. This way you insert something in the paragraph and
3196         // don't tell it to LyXText (row rebreaking and undo handling!!!)
3197         // I deactivate this code, have a look at BufferView::insertErrors
3198         // how you should do this correctly! (Jug 20020315)
3199 #endif
3200 #if 0
3201         // insert an error marker in text
3202         InsetError * new_inset = new InsetError(message);
3203         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
3204                          params.language));
3205 #endif
3206 }
3207
3208
3209 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3210 {
3211         ofstream ofs(fname.c_str());
3212         if (!ofs) {
3213                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3214                 return;
3215         }
3216
3217         Paragraph * par = &*(paragraphs.begin());
3218
3219         niceFile = nice; // this will be used by Insetincludes.
3220
3221         LaTeXFeatures features(params);
3222         validate(features);
3223
3224         texrow.reset();
3225
3226         LyXTextClass const & tclass = params.getLyXTextClass();
3227         string top_element = tclass.latexname();
3228
3229         if (!only_body) {
3230                 ofs << "<!DOCTYPE " << top_element
3231                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3232
3233                 string preamble = params.preamble;
3234                 const string name = nice ? ChangeExtension(filename_, ".sgml")
3235                          : fname;
3236                 preamble += features.getIncludedFiles(name);
3237                 preamble += features.getLyXSGMLEntities();
3238
3239                 if (!preamble.empty()) {
3240                         ofs << "\n [ " << preamble << " ]";
3241                 }
3242                 ofs << ">\n\n";
3243         }
3244
3245         string top = top_element;
3246         top += " lang=\"";
3247         top += params.language->code();
3248         top += "\"";
3249
3250         if (!params.options.empty()) {
3251                 top += " ";
3252                 top += params.options;
3253         }
3254         sgmlOpenTag(ofs, 0, false, top);
3255
3256         ofs << "<!-- DocBook file was created by " << lyx_docversion
3257             << "\n  See http://www.lyx.org/ for more information -->\n";
3258
3259         vector<string> environment_stack(10);
3260         vector<string> environment_inner(10);
3261         vector<string> command_stack(10);
3262
3263         bool command_flag = false;
3264         Paragraph::depth_type command_depth = 0;
3265         Paragraph::depth_type command_base = 0;
3266         Paragraph::depth_type cmd_depth = 0;
3267         Paragraph::depth_type depth = 0; // paragraph depth
3268
3269         string item_name;
3270         string command_name;
3271
3272         while (par) {
3273                 string sgmlparam;
3274                 string c_depth;
3275                 string c_params;
3276                 int desc_on = 0; // description mode
3277
3278                 LyXLayout_ptr const & style = par->layout();
3279
3280                 // environment tag closing
3281                 for (; depth > par->params().depth(); --depth) {
3282                         if (environment_inner[depth] != "!-- --") {
3283                                 item_name = "listitem";
3284                                 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
3285                                 if (environment_inner[depth] == "varlistentry")
3286                                         sgmlCloseTag(ofs, depth+command_depth, false, environment_inner[depth]);
3287                         }
3288                         sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
3289                         environment_stack[depth].erase();
3290                         environment_inner[depth].erase();
3291                 }
3292
3293                 if (depth == par->params().depth()
3294                    && environment_stack[depth] != style->latexname()
3295                    && !environment_stack[depth].empty()) {
3296                         if (environment_inner[depth] != "!-- --") {
3297                                 item_name= "listitem";
3298                                 sgmlCloseTag(ofs, command_depth+depth, false, item_name);
3299                                 if (environment_inner[depth] == "varlistentry")
3300                                         sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
3301                         }
3302
3303                         sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
3304
3305                         environment_stack[depth].erase();
3306                         environment_inner[depth].erase();
3307                 }
3308
3309                 // Write opening SGML tags.
3310                 switch (style->latextype) {
3311                 case LATEX_PARAGRAPH:
3312                         sgmlOpenTag(ofs, depth + command_depth,
3313                                     false, style->latexname());
3314                         break;
3315
3316                 case LATEX_COMMAND:
3317                         if (depth != 0)
3318                                 sgmlError(par, 0,
3319                                           _("Error : Wrong depth for "
3320                                             "LatexType Command.\n"));
3321
3322                         command_name = style->latexname();
3323
3324                         sgmlparam = style->latexparam();
3325                         c_params = split(sgmlparam, c_depth,'|');
3326
3327                         cmd_depth = lyx::atoi(c_depth);
3328
3329                         if (command_flag) {
3330                                 if (cmd_depth < command_base) {
3331                                         for (Paragraph::depth_type j = command_depth;
3332                                              j >= command_base; --j) {
3333                                                 sgmlCloseTag(ofs, j, false, command_stack[j]);
3334                                                 ofs << endl;
3335                                         }
3336                                         command_depth = command_base = cmd_depth;
3337                                 } else if (cmd_depth <= command_depth) {
3338                                         for (int j = command_depth;
3339                                              j >= int(cmd_depth); --j) {
3340                                                 sgmlCloseTag(ofs, j, false, command_stack[j]);
3341                                                 ofs << endl;
3342                                         }
3343                                         command_depth = cmd_depth;
3344                                 } else
3345                                         command_depth = cmd_depth;
3346                         } else {
3347                                 command_depth = command_base = cmd_depth;
3348                                 command_flag = true;
3349                         }
3350                         if (command_stack.size() == command_depth + 1)
3351                                 command_stack.push_back(string());
3352                         command_stack[command_depth] = command_name;
3353
3354                         // treat label as a special case for
3355                         // more WYSIWYM handling.
3356                         // This is a hack while paragraphs can't have
3357                         // attributes, like id in this case.
3358                         if (par->isInset(0)) {
3359                                 Inset * inset = par->getInset(0);
3360                                 Inset::Code lyx_code = inset->lyxCode();
3361                                 if (lyx_code == Inset::LABEL_CODE) {
3362                                         command_name += " id=\"";
3363                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3364                                         command_name += "\"";
3365                                         desc_on = 3;
3366                                 }
3367                         }
3368
3369                         sgmlOpenTag(ofs, depth + command_depth, false, command_name);
3370
3371                         item_name = c_params.empty()?"title":c_params;
3372                         sgmlOpenTag(ofs, depth + 1 + command_depth, false, item_name);
3373                         break;
3374
3375                 case LATEX_ENVIRONMENT:
3376                 case LATEX_ITEM_ENVIRONMENT:
3377                         if (depth < par->params().depth()) {
3378                                 depth = par->params().depth();
3379                                 environment_stack[depth].erase();
3380                         }
3381
3382                         if (environment_stack[depth] != style->latexname()) {
3383                                 if (environment_stack.size() == depth + 1) {
3384                                         environment_stack.push_back("!-- --");
3385                                         environment_inner.push_back("!-- --");
3386                                 }
3387                                 environment_stack[depth] = style->latexname();
3388                                 environment_inner[depth] = "!-- --";
3389                                 sgmlOpenTag(ofs, depth + command_depth, false, environment_stack[depth]);
3390                         } else {
3391                                 if (environment_inner[depth] != "!-- --") {
3392                                         item_name= "listitem";
3393                                         sgmlCloseTag(ofs, command_depth + depth, false, item_name);
3394                                         if (environment_inner[depth] == "varlistentry")
3395                                                 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
3396                                 }
3397                         }
3398
3399                         if (style->latextype == LATEX_ENVIRONMENT) {
3400                                 if (!style->latexparam().empty()) {
3401                                         if (style->latexparam() == "CDATA")
3402                                                 ofs << "<![CDATA[";
3403                                         else
3404                                                 sgmlOpenTag(ofs, depth + command_depth, false, style->latexparam());
3405                                 }
3406                                 break;
3407                         }
3408
3409                         desc_on = (style->labeltype == LABEL_MANUAL);
3410
3411                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
3412                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3413                                     false, environment_inner[depth]);
3414
3415                         item_name = desc_on ? "term" : "para";
3416                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3417                                     false, item_name);
3418                         break;
3419                 default:
3420                         sgmlOpenTag(ofs, depth + command_depth,
3421                                     false, style->latexname());
3422                         break;
3423                 }
3424
3425                 simpleDocBookOnePar(ofs, par, desc_on,
3426                                     depth + 1 + command_depth);
3427                 par = par->next();
3428
3429                 string end_tag;
3430                 // write closing SGML tags
3431                 switch (style->latextype) {
3432                 case LATEX_COMMAND:
3433                         end_tag = c_params.empty() ? "title" : c_params;
3434                         sgmlCloseTag(ofs, depth + command_depth,
3435                                      false, end_tag);
3436                         break;
3437                 case LATEX_ENVIRONMENT:
3438                         if (!style->latexparam().empty()) {
3439                                 if (style->latexparam() == "CDATA")
3440                                         ofs << "]]>";
3441                                 else
3442                                         sgmlCloseTag(ofs, depth + command_depth, false, style->latexparam());
3443                         }
3444                         break;
3445                 case LATEX_ITEM_ENVIRONMENT:
3446                         if (desc_on == 1) break;
3447                         end_tag= "para";
3448                         sgmlCloseTag(ofs, depth + 1 + command_depth, false, end_tag);
3449                         break;
3450                 case LATEX_PARAGRAPH:
3451                         sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
3452                         break;
3453                 default:
3454                         sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
3455                         break;
3456                 }
3457         }
3458
3459         // Close open tags
3460         for (int d = depth; d >= 0; --d) {
3461                 if (!environment_stack[depth].empty()) {
3462                         if (environment_inner[depth] != "!-- --") {
3463                                 item_name = "listitem";
3464                                 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
3465                                if (environment_inner[depth] == "varlistentry")
3466                                        sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
3467                         }
3468
3469                         sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
3470                 }
3471         }
3472
3473         for (int j = command_depth; j >= 0 ; --j)
3474                 if (!command_stack[j].empty()) {
3475                         sgmlCloseTag(ofs, j, false, command_stack[j]);
3476                         ofs << endl;
3477                 }
3478
3479         ofs << "\n\n";
3480         sgmlCloseTag(ofs, 0, false, top_element);
3481
3482         ofs.close();
3483         // How to check for successful close
3484
3485         // we want this to be true outside previews (for insetexternal)
3486         niceFile = true;
3487 }
3488
3489
3490 void Buffer::simpleDocBookOnePar(ostream & os,
3491                                  Paragraph * par, int & desc_on,
3492                                  Paragraph::depth_type depth) const
3493 {
3494         bool emph_flag = false;
3495
3496         LyXLayout_ptr const & style = par->layout();
3497
3498         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
3499
3500         int char_line_count = depth;
3501         //if (!style.free_spacing)
3502         //      os << string(depth,' ');
3503
3504         // parsing main loop
3505         for (pos_type i = 0; i < par->size(); ++i) {
3506                 LyXFont font = par->getFont(params, i);
3507
3508                 // handle <emphasis> tag
3509                 if (font_old.emph() != font.emph()) {
3510                         if (font.emph() == LyXFont::ON) {
3511                                 if (style->latexparam() == "CDATA")
3512                                         os << "]]>";
3513                                 os << "<emphasis>";
3514                                 if (style->latexparam() == "CDATA")
3515                                         os << "<![CDATA[";
3516                                 emph_flag = true;
3517                         } else if (i) {
3518                                 if (style->latexparam() == "CDATA")
3519                                         os << "]]>";
3520                                 os << "</emphasis>";
3521                                 if (style->latexparam() == "CDATA")
3522                                         os << "<![CDATA[";
3523                                 emph_flag = false;
3524                         }
3525                 }
3526
3527
3528                 if (par->isInset(i)) {
3529                         Inset * inset = par->getInset(i);
3530                         // don't print the inset in position 0 if desc_on == 3 (label)
3531                         if (i || desc_on != 3) {
3532                                 if (style->latexparam() == "CDATA")
3533                                         os << "]]>";
3534                                 inset->docbook(this, os, false);
3535                                 if (style->latexparam() == "CDATA")
3536                                         os << "<![CDATA[";
3537                         }
3538                 } else {
3539                         char c = par->getChar(i);
3540                         bool ws;
3541                         string str;
3542                         boost::tie(ws, str) = sgml::escapeChar(c);
3543
3544                         if (style->pass_thru) {
3545                                 os << c;
3546                         } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
3547                                         os << str;
3548                         } else if (desc_on ==1) {
3549                                 ++char_line_count;
3550                                 os << "\n</term><listitem><para>";
3551                                 desc_on = 2;
3552                         } else {
3553                                 os << ' ';
3554                         }
3555                 }
3556                 font_old = font;
3557         }
3558
3559         if (emph_flag) {
3560                 if (style->latexparam() == "CDATA")
3561                         os << "]]>";
3562                 os << "</emphasis>";
3563                 if (style->latexparam() == "CDATA")
3564                         os << "<![CDATA[";
3565         }
3566
3567         // resets description flag correctly
3568         if (desc_on == 1) {
3569                 // <term> not closed...
3570                 os << "</term>\n<listitem><para>&nbsp;</para>";
3571         }
3572         if (style->free_spacing)
3573                 os << '\n';
3574 }
3575
3576
3577 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3578 // Other flags: -wall -v0 -x
3579 int Buffer::runChktex()
3580 {
3581         if (!users->text) return 0;
3582
3583         users->owner()->prohibitInput();
3584
3585         // get LaTeX-Filename
3586         string const name = getLatexName();
3587         string path = filePath();
3588
3589         string const org_path = path;
3590         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3591                 path = tmppath;
3592         }
3593
3594         Path p(path); // path to LaTeX file
3595         users->owner()->message(_("Running chktex..."));
3596
3597         // Remove all error insets
3598         bool const removedErrorInsets = users->removeAutoInsets();
3599
3600         // Generate the LaTeX file if neccessary
3601         makeLaTeXFile(name, org_path, false);
3602
3603         TeXErrors terr;
3604         Chktex chktex(lyxrc.chktex_command, name, filePath());
3605         int res = chktex.run(terr); // run chktex
3606
3607         if (res == -1) {
3608                 Alert::alert(_("chktex did not work!"),
3609                            _("Could not run with file:"), name);
3610         } else if (res > 0) {
3611                 // Insert all errors as errors boxes
3612                 users->insertErrors(terr);
3613         }
3614
3615         // if we removed error insets before we ran chktex or if we inserted
3616         // error insets after we ran chktex, this must be run:
3617         if (removedErrorInsets || res) {
3618 #warning repaint needed here, or do you mean update() ?
3619                 users->repaint();
3620                 users->fitCursor();
3621         }
3622         users->owner()->allowInput();
3623
3624         return res;
3625 }
3626
3627
3628 void Buffer::validate(LaTeXFeatures & features) const
3629 {
3630         LyXTextClass const & tclass = params.getLyXTextClass();
3631
3632         // AMS Style is at document level
3633         if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3634                 features.require("amsmath");
3635
3636         for_each(paragraphs.begin(), paragraphs.end(),
3637                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
3638
3639         // the bullet shapes are buffer level not paragraph level
3640         // so they are tested here
3641         for (int i = 0; i < 4; ++i) {
3642                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3643                         int const font = params.user_defined_bullets[i].getFont();
3644                         if (font == 0) {
3645                                 int const c = params
3646                                         .user_defined_bullets[i]
3647                                         .getCharacter();
3648                                 if (c == 16
3649                                    || c == 17
3650                                    || c == 25
3651                                    || c == 26
3652                                    || c == 31) {
3653                                         features.require("latexsym");
3654                                 }
3655                         } else if (font == 1) {
3656                                 features.require("amssymb");
3657                         } else if ((font >= 2 && font <= 5)) {
3658                                 features.require("pifont");
3659                         }
3660                 }
3661         }
3662
3663         if (lyxerr.debugging(Debug::LATEX)) {
3664                 features.showStruct();
3665         }
3666 }
3667
3668
3669 // This function should be in Buffer because it's a buffer's property (ale)
3670 string const Buffer::getIncludeonlyList(char delim)
3671 {
3672         string lst;
3673         for (inset_iterator it = inset_iterator_begin();
3674             it != inset_iterator_end(); ++it) {
3675                 if (it->lyxCode() == Inset::INCLUDE_CODE) {
3676                         InsetInclude & inc = static_cast<InsetInclude &>(*it);
3677                         if (inc.isIncludeOnly()) {
3678                                 if (!lst.empty())
3679                                         lst += delim;
3680                                 lst += inc.getRelFileBaseName();
3681                         }
3682                 }
3683         }
3684         lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3685         return lst;
3686 }
3687
3688
3689 vector<string> const Buffer::getLabelList() const
3690 {
3691         /// if this is a child document and the parent is already loaded
3692         /// Use the parent's list instead  [ale990407]
3693         if (!params.parentname.empty()
3694             && bufferlist.exists(params.parentname)) {
3695                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3696                 if (tmp)
3697                         return tmp->getLabelList();
3698         }
3699
3700         vector<string> label_list;
3701         for (inset_iterator it = inset_const_iterator_begin();
3702              it != inset_const_iterator_end(); ++it) {
3703                 vector<string> const l = it->getLabelList();
3704                 label_list.insert(label_list.end(), l.begin(), l.end());
3705         }
3706         return label_list;
3707 }
3708
3709
3710 // This is also a buffer property (ale)
3711 vector<pair<string, string> > const Buffer::getBibkeyList() const
3712 {
3713         typedef pair<string, string> StringPair;
3714         /// if this is a child document and the parent is already loaded
3715         /// Use the parent's list instead  [ale990412]
3716         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3717                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3718                 if (tmp)
3719                         return tmp->getBibkeyList();
3720         }
3721
3722         vector<StringPair> keys;
3723         ParagraphList::iterator pit = paragraphs.begin();
3724         ParagraphList::iterator pend = paragraphs.end();
3725         for (; pit != pend; ++pit) {
3726                 if (pit->bibkey) {
3727                         string const key = pit->bibkey->getContents();
3728                         string const opt = pit->bibkey->getOptions();
3729                         string const ref = pit->asString(this, false);
3730                         string const info = opt + "TheBibliographyRef" + ref;
3731
3732                         keys.push_back(StringPair(key, info));
3733                 }
3734         }
3735
3736         // Might be either using bibtex or a child has bibliography
3737         if (keys.empty()) {
3738                 for (inset_iterator it = inset_const_iterator_begin();
3739                         it != inset_const_iterator_end(); ++it) {
3740                         // Search for Bibtex or Include inset
3741                         if (it->lyxCode() == Inset::BIBTEX_CODE) {
3742                                 vector<StringPair> tmp =
3743                                         static_cast<InsetBibtex &>(*it).getKeys(this);
3744                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3745                         } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
3746                                 vector<StringPair> const tmp =
3747                                         static_cast<InsetInclude &>(*it).getKeys();
3748                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3749                         }
3750                 }
3751         }
3752
3753         return keys;
3754 }
3755
3756
3757 bool Buffer::isDepClean(string const & name) const
3758 {
3759         DEPCLEAN * item = dep_clean;
3760         while (item && item->master != name)
3761                 item = item->next;
3762         if (!item) return true;
3763         return item->clean;
3764 }
3765
3766
3767 void Buffer::markDepClean(string const & name)
3768 {
3769         if (!dep_clean) {
3770                 dep_clean = new DEPCLEAN;
3771                 dep_clean->clean = true;
3772                 dep_clean->master = name;
3773                 dep_clean->next = 0;
3774         } else {
3775                 DEPCLEAN * item = dep_clean;
3776                 while (item && item->master != name)
3777                         item = item->next;
3778                 if (item) {
3779                         item->clean = true;
3780                 } else {
3781                         item = new DEPCLEAN;
3782                         item->clean = true;
3783                         item->master = name;
3784                         item->next = 0;
3785                 }
3786         }
3787 }
3788
3789
3790 bool Buffer::dispatch(string const & command, bool * result)
3791 {
3792         // Split command string into command and argument
3793         string cmd;
3794         string line = ltrim(command);
3795         string const arg = trim(split(line, cmd, ' '));
3796
3797         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
3798 }
3799
3800
3801 bool Buffer::dispatch(int action, string const & argument, bool * result)
3802 {
3803         bool dispatched = true;
3804
3805         switch (action) {
3806                 case LFUN_EXPORT: {
3807                         bool const tmp = Exporter::Export(this, argument, false);
3808                         if (result)
3809                                 *result = tmp;
3810                         break;
3811                 }
3812
3813                 default:
3814                         dispatched = false;
3815         }
3816         return dispatched;
3817 }
3818
3819
3820 void Buffer::resizeInsets(BufferView * bv)
3821 {
3822         /// then remove all LyXText in text-insets
3823         for_each(paragraphs.begin(), paragraphs.end(),
3824                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
3825 }
3826
3827
3828 void Buffer::redraw()
3829 {
3830 #warning repaint needed here, or do you mean update() ?
3831         users->repaint();
3832         users->fitCursor();
3833 }
3834
3835
3836 void Buffer::changeLanguage(Language const * from, Language const * to)
3837 {
3838
3839         ParIterator end = par_iterator_end();
3840         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3841                 (*it)->changeLanguage(params, from, to);
3842 }
3843
3844
3845 bool Buffer::isMultiLingual()
3846 {
3847         ParIterator end = par_iterator_end();
3848         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3849                 if ((*it)->isMultiLingual(params))
3850                         return true;
3851
3852         return false;
3853 }
3854
3855
3856 Counters & Buffer::counters() const
3857 {
3858         return *ctrs.get();
3859 }
3860
3861
3862 void Buffer::inset_iterator::setParagraph()
3863 {
3864         while (pit != pend) {
3865                 it = pit->insetlist.begin();
3866                 if (it != pit->insetlist.end())
3867                         return;
3868                 ++pit;
3869         }
3870 }
3871
3872
3873 Inset * Buffer::getInsetFromID(int id_arg) const
3874 {
3875         for (inset_iterator it = inset_const_iterator_begin();
3876                  it != inset_const_iterator_end(); ++it)
3877         {
3878                 if (it->id() == id_arg)
3879                         return &(*it);
3880                 Inset * in = it->getInsetFromID(id_arg);
3881                 if (in)
3882                         return in;
3883         }
3884         return 0;
3885 }
3886
3887
3888 Paragraph * Buffer::getParFromID(int id) const
3889 {
3890         if (id < 0)
3891                 return 0;
3892
3893         ParagraphList::iterator it = paragraphs.begin();
3894         ParagraphList::iterator end = paragraphs.end();
3895         for (; it != end; ++it) {
3896                 if (it->id() == id) {
3897                         return &*it;
3898                 }
3899                 Paragraph * tmp = it->getParFromID(id);
3900                 if (tmp) {
3901                         return tmp;
3902                 }
3903         }
3904         return 0;
3905 }
3906
3907
3908 ParIterator Buffer::par_iterator_begin()
3909 {
3910         return ParIterator(&*(paragraphs.begin()));
3911 }
3912
3913
3914 ParIterator Buffer::par_iterator_end()
3915 {
3916         return ParIterator();
3917 }
3918
3919
3920 void Buffer::addUser(BufferView * u)
3921 {
3922         users = u;
3923 }
3924
3925
3926 void Buffer::delUser(BufferView *)
3927 {
3928         users = 0;
3929 }
3930
3931
3932 Language const * Buffer::getLanguage() const
3933 {
3934         return params.language;
3935 }
3936
3937
3938 bool Buffer::isClean() const
3939 {
3940         return lyx_clean;
3941 }
3942
3943
3944 bool Buffer::isBakClean() const
3945 {
3946         return bak_clean;
3947 }
3948
3949
3950 void Buffer::markClean() const
3951 {
3952         if (!lyx_clean) {
3953                 lyx_clean = true;
3954                 updateTitles();
3955         }
3956         // if the .lyx file has been saved, we don't need an
3957         // autosave
3958         bak_clean = true;
3959 }
3960
3961
3962 void Buffer::markBakClean()
3963 {
3964         bak_clean = true;
3965 }
3966
3967
3968 void Buffer::setUnnamed(bool flag)
3969 {
3970         unnamed = flag;
3971 }
3972
3973
3974 bool Buffer::isUnnamed()
3975 {
3976         return unnamed;
3977 }
3978
3979
3980 void Buffer::markDirty()
3981 {
3982         if (lyx_clean) {
3983                 lyx_clean = false;
3984                 updateTitles();
3985         }
3986         bak_clean = false;
3987         DEPCLEAN * tmp = dep_clean;
3988         while (tmp) {
3989                 tmp->clean = false;
3990                 tmp = tmp->next;
3991         }
3992 }
3993
3994
3995 string const & Buffer::fileName() const
3996 {
3997         return filename_;
3998 }
3999
4000
4001 string const & Buffer::filePath() const
4002 {
4003         return filepath_;
4004 }
4005
4006
4007 bool Buffer::isReadonly() const
4008 {
4009         return read_only;
4010 }
4011
4012
4013 BufferView * Buffer::getUser() const
4014 {
4015         return users;
4016 }
4017
4018
4019 void Buffer::setParentName(string const & name)
4020 {
4021         params.parentname = name;
4022 }
4023
4024
4025 Buffer::inset_iterator::inset_iterator()
4026         : pit(0), pend(0)
4027 {}
4028
4029
4030 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
4031         : pit(p), pend(e)
4032 {
4033         setParagraph();
4034 }
4035
4036
4037 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
4038 {
4039         if (pit != pend) {
4040                 ++it;
4041                 if (it == pit->insetlist.end()) {
4042                         ++pit;
4043                         setParagraph();
4044                 }
4045         }
4046         return *this;
4047 }
4048
4049
4050 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
4051 {
4052         inset_iterator tmp = *this;
4053         ++*this;
4054         return tmp;
4055 }
4056
4057
4058 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
4059 {
4060         return *it.getInset();
4061 }
4062
4063
4064 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
4065 {
4066         return it.getInset();
4067 }
4068
4069
4070 Paragraph * Buffer::inset_iterator::getPar()
4071 {
4072         return &(*pit);
4073 }
4074
4075
4076 lyx::pos_type Buffer::inset_iterator::getPos() const
4077 {
4078         return it.getPos();
4079 }
4080
4081
4082 bool operator==(Buffer::inset_iterator const & iter1,
4083                 Buffer::inset_iterator const & iter2)
4084 {
4085         return iter1.pit == iter2.pit
4086                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
4087 }
4088
4089
4090 bool operator!=(Buffer::inset_iterator const & iter1,
4091                 Buffer::inset_iterator const & iter2)
4092 {
4093         return !(iter1 == iter2);
4094 }
4095