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