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