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