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