]> git.lyx.org Git - lyx.git/blob - src/buffer.C
update no.po
[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 const 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                                 _("-- substituting default."));
625 #else
626                         Alert::alert(
627                                 _("Textclass error"),
628                                 _("The document uses an unknown textclass ")
629                                 + lex.getString(),
630                                 _("-- substituting default."));
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 << '\''
1208                                                             << endl;
1209                                         cmd_ret const ret = RunCommand(command);
1210                                         if (ret.first) {
1211                                                 Alert::alert(_("ERROR!"),
1212                                                              _("An error occured while "
1213                                                                "running the conversion script."));
1214                                                 return false;
1215                                         }
1216                                         istringstream is(STRCONV(ret.second));
1217                                         LyXLex tmplex(0, 0);
1218                                         tmplex.setStream(is);
1219                                         return readFile(tmplex, string(), par);
1220                                 } else {
1221                                         // This code is reached if lyx2lyx failed (for
1222                                         // some reason) to change the file format of
1223                                         // the file.
1224                                         lyx::Assert(false);
1225                                         return false;
1226                                 }
1227                         }
1228                         bool the_end = readLyXformat2(lex, par);
1229                         params.setPaperStuff();
1230
1231 #if 0
1232                         // the_end was added in 213
1233                         if (file_format < 213)
1234                                 the_end = true;
1235 #endif
1236
1237                         if (!the_end) {
1238                                 Alert::alert(_("Warning!"),
1239                                            _("Reading of document is not complete"),
1240                                            _("Maybe the document is truncated"));
1241                         }
1242                         return true;
1243                 } else { // "\\lyxformat" not found
1244                         Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1245                 }
1246         } else
1247                 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1248         return false;
1249 }
1250
1251
1252 // Should probably be moved to somewhere else: BufferView? LyXView?
1253 bool Buffer::save() const
1254 {
1255         // We don't need autosaves in the immediate future. (Asger)
1256         resetAutosaveTimers();
1257
1258         // make a backup
1259         string s;
1260         if (lyxrc.make_backup) {
1261                 s = fileName() + '~';
1262                 if (!lyxrc.backupdir_path.empty())
1263                         s = AddName(lyxrc.backupdir_path,
1264                                     subst(os::slashify_path(s),'/','!'));
1265
1266                 // Rename is the wrong way of making a backup,
1267                 // this is the correct way.
1268                 /* truss cp fil fil2:
1269                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1270                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1271                    open("LyXVC.lyx", O_RDONLY)                     = 3
1272                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1273                    fstat(4, 0xEFFFF508)                            = 0
1274                    fstat(3, 0xEFFFF508)                            = 0
1275                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1276                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1277                    read(3, 0xEFFFD4A0, 8192)                       = 0
1278                    close(4)                                        = 0
1279                    close(3)                                        = 0
1280                    chmod("LyXVC3.lyx", 0100644)                    = 0
1281                    lseek(0, 0, SEEK_CUR)                           = 46440
1282                    _exit(0)
1283                 */
1284
1285                 // Should probably have some more error checking here.
1286                 // Doing it this way, also makes the inodes stay the same.
1287                 // This is still not a very good solution, in particular we
1288                 // might loose the owner of the backup.
1289                 FileInfo finfo(fileName());
1290                 if (finfo.exist()) {
1291                         mode_t fmode = finfo.getMode();
1292                         struct utimbuf times = {
1293                                 finfo.getAccessTime(),
1294                                 finfo.getModificationTime() };
1295
1296                         ifstream ifs(fileName().c_str());
1297                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1298                         if (ifs && ofs) {
1299                                 ofs << ifs.rdbuf();
1300                                 ifs.close();
1301                                 ofs.close();
1302                                 ::chmod(s.c_str(), fmode);
1303
1304                                 if (::utime(s.c_str(), &times)) {
1305                                         lyxerr << "utime error." << endl;
1306                                 }
1307                         } else {
1308                                 lyxerr << "LyX was not able to make "
1309                                         "backup copy. Beware." << endl;
1310                         }
1311                 }
1312         }
1313
1314         if (writeFile(fileName())) {
1315                 markClean();
1316                 removeAutosaveFile(fileName());
1317         } else {
1318                 // Saving failed, so backup is not backup
1319                 if (lyxrc.make_backup) {
1320                         lyx::rename(s, fileName());
1321                 }
1322                 return false;
1323         }
1324         return true;
1325 }
1326
1327
1328 bool Buffer::writeFile(string const & fname) const
1329 {
1330         if (read_only && (fname == fileName())) {
1331                 return false;
1332         }
1333
1334         FileInfo finfo(fname);
1335         if (finfo.exist() && !finfo.writable()) {
1336                 return false;
1337         }
1338
1339         ofstream ofs(fname.c_str());
1340         if (!ofs) {
1341                 return false;
1342         }
1343
1344 #ifdef HAVE_LOCALE
1345         // Use the standard "C" locale for file output.
1346         ofs.imbue(std::locale::classic());
1347 #endif
1348
1349         // The top of the file should not be written by params.
1350
1351         // write out a comment in the top of the file
1352         ofs << '#' << lyx_docversion
1353             << " created this file. For more info see http://www.lyx.org/\n"
1354             << "\\lyxformat " << LYX_FORMAT << "\n";
1355
1356         // now write out the buffer paramters.
1357         params.writeFile(ofs);
1358
1359         Paragraph::depth_type depth = 0;
1360
1361         // this will write out all the paragraphs
1362         // using recursive descent.
1363         ParagraphList::iterator pit = paragraphs.begin();
1364         ParagraphList::iterator pend = paragraphs.end();
1365         for (; pit != pend; ++pit)
1366                 pit->write(this, ofs, params, depth);
1367
1368         // Write marker that shows file is complete
1369         ofs << "\n\\the_end" << endl;
1370
1371         ofs.close();
1372
1373         // how to check if close went ok?
1374         // Following is an attempt... (BE 20001011)
1375
1376         // good() returns false if any error occured, including some
1377         //        formatting error.
1378         // bad()  returns true if something bad happened in the buffer,
1379         //        which should include file system full errors.
1380
1381         bool status = true;
1382         if (!ofs.good()) {
1383                 status = false;
1384 #if 0
1385                 if (ofs.bad()) {
1386                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1387                 } else {
1388                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1389                                << endl;
1390                 }
1391 #endif
1392         }
1393
1394         return status;
1395 }
1396
1397
1398 namespace {
1399
1400 pair<int, string> const addDepth(int depth, int ldepth)
1401 {
1402         int d = depth * 2;
1403         if (ldepth > depth)
1404                 d += (ldepth - depth) * 2;
1405         return make_pair(d, string(d, ' '));
1406 }
1407
1408 }
1409
1410
1411 string const Buffer::asciiParagraph(Paragraph const & par,
1412                                     unsigned int linelen,
1413                                     bool noparbreak) const
1414 {
1415         ostringstream buffer;
1416         Paragraph::depth_type depth = 0;
1417         int ltype = 0;
1418         Paragraph::depth_type ltype_depth = 0;
1419         bool ref_printed = false;
1420 //      if (!par->previous()) {
1421 #if 0
1422         // begins or ends a deeper area ?
1423         if (depth != par->params().depth()) {
1424                 if (par->params().depth() > depth) {
1425                         while (par->params().depth() > depth) {
1426                                 ++depth;
1427                         }
1428                 } else {
1429                         while (par->params().depth() < depth) {
1430                                 --depth;
1431                         }
1432                 }
1433         }
1434 #else
1435         depth = par.params().depth();
1436 #endif
1437
1438         // First write the layout
1439         string const & tmp = par.layout()->name();
1440         if (compare_no_case(tmp, "itemize") == 0) {
1441                 ltype = 1;
1442                 ltype_depth = depth + 1;
1443         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1444                 ltype = 2;
1445                 ltype_depth = depth + 1;
1446         } else if (contains(ascii_lowercase(tmp), "ection")) {
1447                 ltype = 3;
1448                 ltype_depth = depth + 1;
1449         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1450                 ltype = 4;
1451                 ltype_depth = depth + 1;
1452         } else if (compare_ascii_no_case(tmp, "description") == 0) {
1453                 ltype = 5;
1454                 ltype_depth = depth + 1;
1455         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1456                 ltype = 6;
1457                 ltype_depth = 0;
1458         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1459                 ltype = 7;
1460                 ltype_depth = 0;
1461         } else {
1462                 ltype = 0;
1463                 ltype_depth = 0;
1464         }
1465
1466         /* maybe some vertical spaces */
1467
1468         /* the labelwidthstring used in lists */
1469
1470         /* some lines? */
1471
1472         /* some pagebreaks? */
1473
1474         /* noindent ? */
1475
1476         /* what about the alignment */
1477 //      } else {
1478 //              lyxerr << "Should this ever happen?" << endl;
1479 //      }
1480
1481         // linelen <= 0 is special and means we don't have paragraph breaks
1482
1483         string::size_type currlinelen = 0;
1484
1485         if (!noparbreak) {
1486                 if (linelen > 0)
1487                         buffer << "\n\n";
1488
1489                 buffer << string(depth * 2, ' ');
1490                 currlinelen += depth * 2;
1491
1492                 //--
1493                 // we should probably change to the paragraph language in the
1494                 // gettext here (if possible) so that strings are outputted in
1495                 // the correct language! (20012712 Jug)
1496                 //--
1497                 switch (ltype) {
1498                 case 0: // Standard
1499                 case 4: // (Sub)Paragraph
1500                 case 5: // Description
1501                         break;
1502                 case 6: // Abstract
1503                         if (linelen > 0) {
1504                                 buffer << _("Abstract") << "\n\n";
1505                                 currlinelen = 0;
1506                         } else {
1507                                 string const abst = _("Abstract: ");
1508                                 buffer << abst;
1509                                 currlinelen += abst.length();
1510                         }
1511                         break;
1512                 case 7: // Bibliography
1513                         if (!ref_printed) {
1514                                 if (linelen > 0) {
1515                                         buffer << _("References") << "\n\n";
1516                                         currlinelen = 0;
1517                                 } else {
1518                                         string const refs = _("References: ");
1519                                         buffer << refs;
1520                                         currlinelen += refs.length();
1521                                 }
1522
1523                                 ref_printed = true;
1524                         }
1525                         break;
1526                 default:
1527                 {
1528                         string const parlab = par.params().labelString();
1529                         buffer << parlab << ' ';
1530                         currlinelen += parlab.length() + 1;
1531                 }
1532                 break;
1533
1534                 }
1535         }
1536
1537         if (!currlinelen) {
1538                 pair<int, string> p = addDepth(depth, ltype_depth);
1539                 buffer << p.second;
1540                 currlinelen += p.first;
1541         }
1542
1543         // this is to change the linebreak to do it by word a bit more
1544         // intelligent hopefully! (only in the case where we have a
1545         // max linelenght!) (Jug)
1546
1547         string word;
1548
1549         for (pos_type i = 0; i < par.size(); ++i) {
1550                 char c = par.getUChar(params, i);
1551                 switch (c) {
1552                 case Paragraph::META_INSET:
1553                 {
1554                         Inset const * inset = par.getInset(i);
1555                         if (inset) {
1556                                 if (linelen > 0) {
1557                                         buffer << word;
1558                                         currlinelen += word.length();
1559                                         word.erase();
1560                                 }
1561                                 if (inset->ascii(this, buffer, linelen)) {
1562                                         // to be sure it breaks paragraph
1563                                         currlinelen += linelen;
1564                                 }
1565                         }
1566                 }
1567                 break;
1568
1569                 case Paragraph::META_NEWLINE:
1570                         if (linelen > 0) {
1571                                 buffer << word << "\n";
1572                                 word.erase();
1573
1574                                 pair<int, string> p = addDepth(depth,
1575                                                                ltype_depth);
1576                                 buffer << p.second;
1577                                 currlinelen = p.first;
1578                         }
1579                         break;
1580
1581                 case Paragraph::META_HFILL:
1582                         buffer << word << "\t";
1583                         currlinelen += word.length() + 1;
1584                         word.erase();
1585                         break;
1586
1587                 default:
1588                         if (c == ' ') {
1589                                 if (linelen > 0 &&
1590                                     currlinelen + word.length() > linelen - 10) {
1591                                         buffer << "\n";
1592                                         pair<int, string> p =
1593                                                 addDepth(depth, ltype_depth);
1594                                         buffer << p.second;
1595                                         currlinelen = p.first;
1596                                 }
1597
1598                                 buffer << word << ' ';
1599                                 currlinelen += word.length() + 1;
1600                                 word.erase();
1601
1602                         } else {
1603                                 if (c != '\0') {
1604                                         word += c;
1605                                 } else {
1606                                         lyxerr[Debug::INFO] <<
1607                                                 "writeAsciiFile: NULL char in structure." << endl;
1608                                 }
1609                                 if ((linelen > 0) &&
1610                                         (currlinelen + word.length()) > linelen)
1611                                 {
1612                                         buffer << "\n";
1613
1614                                         pair<int, string> p =
1615                                                 addDepth(depth, ltype_depth);
1616                                         buffer << p.second;
1617                                         currlinelen = p.first;
1618                                 }
1619                         }
1620                         break;
1621                 }
1622         }
1623         buffer << word;
1624         return STRCONV(buffer.str());
1625 }
1626
1627
1628 void Buffer::writeFileAscii(string const & fname, int linelen)
1629 {
1630         ofstream ofs(fname.c_str());
1631         if (!ofs) {
1632                 Alert::err_alert(_("Error: Cannot write file:"), fname);
1633                 return;
1634         }
1635         writeFileAscii(ofs, linelen);
1636 }
1637
1638
1639 void Buffer::writeFileAscii(ostream & os, int linelen)
1640 {
1641         ParagraphList::iterator beg = paragraphs.begin();
1642         ParagraphList::iterator end = paragraphs.end();
1643         ParagraphList::iterator it = beg;
1644         for (; it != end; ++it) {
1645                 os << asciiParagraph(*it, linelen, it == beg);
1646         }
1647         os << "\n";
1648 }
1649
1650
1651 bool use_babel;
1652
1653
1654 void Buffer::makeLaTeXFile(string const & fname,
1655                            string const & original_path,
1656                            bool nice, bool only_body, bool only_preamble)
1657 {
1658         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1659
1660         ofstream ofs(fname.c_str());
1661         if (!ofs) {
1662                 Alert::err_alert(_("Error: Cannot open file: "), fname);
1663                 return;
1664         }
1665
1666         makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1667
1668         ofs.close();
1669         if (ofs.fail()) {
1670                 lyxerr << "File was not closed properly." << endl;
1671         }
1672 }
1673
1674
1675 void Buffer::makeLaTeXFile(ostream & os,
1676                            string const & original_path,
1677                            bool nice, bool only_body, bool only_preamble)
1678 {
1679         niceFile = nice; // this will be used by Insetincludes.
1680
1681         // validate the buffer.
1682         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1683         LaTeXFeatures features(params);
1684         validate(features);
1685         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1686
1687         texrow.reset();
1688         // The starting paragraph of the coming rows is the
1689         // first paragraph of the document. (Asger)
1690         texrow.start(&*(paragraphs.begin()), 0);
1691
1692         if (!only_body && nice) {
1693                 os << "%% " << lyx_docversion << " created this file.  "
1694                         "For more info, see http://www.lyx.org/.\n"
1695                         "%% Do not edit unless you really know what "
1696                         "you are doing.\n";
1697                 texrow.newline();
1698                 texrow.newline();
1699         }
1700         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1701         // There are a few differences between nice LaTeX and usual files:
1702         // usual is \batchmode and has a
1703         // special input@path to allow the including of figures
1704         // with either \input or \includegraphics (what figinsets do).
1705         // input@path is set when the actual parameter
1706         // original_path is set. This is done for usual tex-file, but not
1707         // for nice-latex-file. (Matthias 250696)
1708         if (!only_body) {
1709                 if (!nice) {
1710                         // code for usual, NOT nice-latex-file
1711                         os << "\\batchmode\n"; // changed
1712                         // from \nonstopmode
1713                         texrow.newline();
1714                 }
1715                 if (!original_path.empty()) {
1716                         string inputpath = os::external_path(original_path);
1717                         subst(inputpath, "~", "\\string~");
1718                         os << "\\makeatletter\n"
1719                             << "\\def\\input@path{{"
1720                             << inputpath << "/}}\n"
1721                             << "\\makeatother\n";
1722                         texrow.newline();
1723                         texrow.newline();
1724                         texrow.newline();
1725                 }
1726
1727                 os << "\\documentclass";
1728
1729                 LyXTextClass const & tclass = params.getLyXTextClass();
1730
1731                 ostringstream options; // the document class options.
1732
1733                 if (tokenPos(tclass.opt_fontsize(),
1734                              '|', params.fontsize) >= 0) {
1735                         // only write if existing in list (and not default)
1736                         options << params.fontsize << "pt,";
1737                 }
1738
1739
1740                 if (!params.use_geometry &&
1741                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1742                         switch (params.papersize) {
1743                         case BufferParams::PAPER_A4PAPER:
1744                                 options << "a4paper,";
1745                                 break;
1746                         case BufferParams::PAPER_USLETTER:
1747                                 options << "letterpaper,";
1748                                 break;
1749                         case BufferParams::PAPER_A5PAPER:
1750                                 options << "a5paper,";
1751                                 break;
1752                         case BufferParams::PAPER_B5PAPER:
1753                                 options << "b5paper,";
1754                                 break;
1755                         case BufferParams::PAPER_EXECUTIVEPAPER:
1756                                 options << "executivepaper,";
1757                                 break;
1758                         case BufferParams::PAPER_LEGALPAPER:
1759                                 options << "legalpaper,";
1760                                 break;
1761                         }
1762                 }
1763
1764                 // if needed
1765                 if (params.sides != tclass.sides()) {
1766                         switch (params.sides) {
1767                         case LyXTextClass::OneSide:
1768                                 options << "oneside,";
1769                                 break;
1770                         case LyXTextClass::TwoSides:
1771                                 options << "twoside,";
1772                                 break;
1773                         }
1774                 }
1775
1776                 // if needed
1777                 if (params.columns != tclass.columns()) {
1778                         if (params.columns == 2)
1779                                 options << "twocolumn,";
1780                         else
1781                                 options << "onecolumn,";
1782                 }
1783
1784                 if (!params.use_geometry
1785                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1786                         options << "landscape,";
1787
1788                 // language should be a parameter to \documentclass
1789                 use_babel = false;
1790                 ostringstream language_options;
1791                 if (params.language->babel() == "hebrew"
1792                     && default_language->babel() != "hebrew")
1793                          // This seems necessary
1794                         features.useLanguage(default_language);
1795
1796                 if (lyxrc.language_use_babel ||
1797                     params.language->lang() != lyxrc.default_language ||
1798                     features.hasLanguages()) {
1799                         use_babel = true;
1800                         language_options << features.getLanguages();
1801                         language_options << params.language->babel();
1802                         if (lyxrc.language_global_options)
1803                                 options << language_options.str() << ',';
1804                 }
1805
1806                 // the user-defined options
1807                 if (!params.options.empty()) {
1808                         options << params.options << ',';
1809                 }
1810
1811                 string strOptions(STRCONV(options.str()));
1812                 if (!strOptions.empty()) {
1813                         strOptions = rtrim(strOptions, ",");
1814                         os << '[' << strOptions << ']';
1815                 }
1816
1817                 os << '{' << tclass.latexname() << "}\n";
1818                 texrow.newline();
1819                 // end of \documentclass defs
1820
1821                 // font selection must be done before loading fontenc.sty
1822                 // The ae package is not needed when using OT1 font encoding.
1823                 if (params.fonts != "default" &&
1824                     (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1825                         os << "\\usepackage{" << params.fonts << "}\n";
1826                         texrow.newline();
1827                         if (params.fonts == "ae") {
1828                                 os << "\\usepackage{aecompl}\n";
1829                                 texrow.newline();
1830                         }
1831                 }
1832                 // this one is not per buffer
1833                 if (lyxrc.fontenc != "default") {
1834                         os << "\\usepackage[" << lyxrc.fontenc
1835                             << "]{fontenc}\n";
1836                         texrow.newline();
1837                 }
1838
1839                 if (params.inputenc == "auto") {
1840                         string const doc_encoding =
1841                                 params.language->encoding()->LatexName();
1842
1843                         // Create a list with all the input encodings used
1844                         // in the document
1845                         set<string> encodings = features.getEncodingSet(doc_encoding);
1846
1847                         os << "\\usepackage[";
1848                         std::copy(encodings.begin(), encodings.end(),
1849                                   std::ostream_iterator<string>(os, ","));
1850                         os << doc_encoding << "]{inputenc}\n";
1851                         texrow.newline();
1852                 } else if (params.inputenc != "default") {
1853                         os << "\\usepackage[" << params.inputenc
1854                             << "]{inputenc}\n";
1855                         texrow.newline();
1856                 }
1857
1858                 // At the very beginning the text parameters.
1859                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1860                         switch (params.paperpackage) {
1861                         case BufferParams::PACKAGE_A4:
1862                                 os << "\\usepackage{a4}\n";
1863                                 texrow.newline();
1864                                 break;
1865                         case BufferParams::PACKAGE_A4WIDE:
1866                                 os << "\\usepackage{a4wide}\n";
1867                                 texrow.newline();
1868                                 break;
1869                         case BufferParams::PACKAGE_WIDEMARGINSA4:
1870                                 os << "\\usepackage[widemargins]{a4}\n";
1871                                 texrow.newline();
1872                                 break;
1873                         }
1874                 }
1875                 if (params.use_geometry) {
1876                         os << "\\usepackage{geometry}\n";
1877                         texrow.newline();
1878                         os << "\\geometry{verbose";
1879                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1880                                 os << ",landscape";
1881                         switch (params.papersize2) {
1882                         case BufferParams::VM_PAPER_CUSTOM:
1883                                 if (!params.paperwidth.empty())
1884                                         os << ",paperwidth="
1885                                             << params.paperwidth;
1886                                 if (!params.paperheight.empty())
1887                                         os << ",paperheight="
1888                                             << params.paperheight;
1889                                 break;
1890                         case BufferParams::VM_PAPER_USLETTER:
1891                                 os << ",letterpaper";
1892                                 break;
1893                         case BufferParams::VM_PAPER_USLEGAL:
1894                                 os << ",legalpaper";
1895                                 break;
1896                         case BufferParams::VM_PAPER_USEXECUTIVE:
1897                                 os << ",executivepaper";
1898                                 break;
1899                         case BufferParams::VM_PAPER_A3:
1900                                 os << ",a3paper";
1901                                 break;
1902                         case BufferParams::VM_PAPER_A4:
1903                                 os << ",a4paper";
1904                                 break;
1905                         case BufferParams::VM_PAPER_A5:
1906                                 os << ",a5paper";
1907                                 break;
1908                         case BufferParams::VM_PAPER_B3:
1909                                 os << ",b3paper";
1910                                 break;
1911                         case BufferParams::VM_PAPER_B4:
1912                                 os << ",b4paper";
1913                                 break;
1914                         case BufferParams::VM_PAPER_B5:
1915                                 os << ",b5paper";
1916                                 break;
1917                         default:
1918                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1919                                 switch (lyxrc.default_papersize) {
1920                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1921                                 case BufferParams::PAPER_USLETTER:
1922                                         os << ",letterpaper";
1923                                         break;
1924                                 case BufferParams::PAPER_LEGALPAPER:
1925                                         os << ",legalpaper";
1926                                         break;
1927                                 case BufferParams::PAPER_EXECUTIVEPAPER:
1928                                         os << ",executivepaper";
1929                                         break;
1930                                 case BufferParams::PAPER_A3PAPER:
1931                                         os << ",a3paper";
1932                                         break;
1933                                 case BufferParams::PAPER_A4PAPER:
1934                                         os << ",a4paper";
1935                                         break;
1936                                 case BufferParams::PAPER_A5PAPER:
1937                                         os << ",a5paper";
1938                                         break;
1939                                 case BufferParams::PAPER_B5PAPER:
1940                                         os << ",b5paper";
1941                                         break;
1942                                 }
1943                         }
1944                         if (!params.topmargin.empty())
1945                                 os << ",tmargin=" << params.topmargin;
1946                         if (!params.bottommargin.empty())
1947                                 os << ",bmargin=" << params.bottommargin;
1948                         if (!params.leftmargin.empty())
1949                                 os << ",lmargin=" << params.leftmargin;
1950                         if (!params.rightmargin.empty())
1951                                 os << ",rmargin=" << params.rightmargin;
1952                         if (!params.headheight.empty())
1953                                 os << ",headheight=" << params.headheight;
1954                         if (!params.headsep.empty())
1955                                 os << ",headsep=" << params.headsep;
1956                         if (!params.footskip.empty())
1957                                 os << ",footskip=" << params.footskip;
1958                         os << "}\n";
1959                         texrow.newline();
1960                 }
1961
1962                 if (tokenPos(tclass.opt_pagestyle(),
1963                              '|', params.pagestyle) >= 0) {
1964                         if (params.pagestyle == "fancy") {
1965                                 os << "\\usepackage{fancyhdr}\n";
1966                                 texrow.newline();
1967                         }
1968                         os << "\\pagestyle{" << params.pagestyle << "}\n";
1969                         texrow.newline();
1970                 }
1971
1972                 if (params.secnumdepth != tclass.secnumdepth()) {
1973                         os << "\\setcounter{secnumdepth}{"
1974                             << params.secnumdepth
1975                             << "}\n";
1976                         texrow.newline();
1977                 }
1978                 if (params.tocdepth != tclass.tocdepth()) {
1979                         os << "\\setcounter{tocdepth}{"
1980                             << params.tocdepth
1981                             << "}\n";
1982                         texrow.newline();
1983                 }
1984
1985                 if (params.paragraph_separation) {
1986                         switch (params.defskip.kind()) {
1987                         case VSpace::SMALLSKIP:
1988                                 os << "\\setlength\\parskip{\\smallskipamount}\n";
1989                                 break;
1990                         case VSpace::MEDSKIP:
1991                                 os << "\\setlength\\parskip{\\medskipamount}\n";
1992                                 break;
1993                         case VSpace::BIGSKIP:
1994                                 os << "\\setlength\\parskip{\\bigskipamount}\n";
1995                                 break;
1996                         case VSpace::LENGTH:
1997                                 os << "\\setlength\\parskip{"
1998                                     << params.defskip.length().asLatexString()
1999                                     << "}\n";
2000                                 break;
2001                         default: // should never happen // Then delete it.
2002                                 os << "\\setlength\\parskip{\\medskipamount}\n";
2003                                 break;
2004                         }
2005                         texrow.newline();
2006
2007                         os << "\\setlength\\parindent{0pt}\n";
2008                         texrow.newline();
2009                 }
2010
2011                 // Now insert the LyX specific LaTeX commands...
2012
2013                 // The optional packages;
2014                 string preamble(features.getPackages());
2015
2016                 // this might be useful...
2017                 preamble += "\n\\makeatletter\n";
2018
2019                 // Some macros LyX will need
2020                 string tmppreamble(features.getMacros());
2021
2022                 if (!tmppreamble.empty()) {
2023                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2024                                 "LyX specific LaTeX commands.\n"
2025                                 + tmppreamble + '\n';
2026                 }
2027
2028                 // the text class specific preamble
2029                 tmppreamble = features.getTClassPreamble();
2030                 if (!tmppreamble.empty()) {
2031                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2032                                 "Textclass specific LaTeX commands.\n"
2033                                 + tmppreamble + '\n';
2034                 }
2035
2036                 /* the user-defined preamble */
2037                 if (!params.preamble.empty()) {
2038                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2039                                 "User specified LaTeX commands.\n"
2040                                 + params.preamble + '\n';
2041                 }
2042
2043                 // Itemize bullet settings need to be last in case the user
2044                 // defines their own bullets that use a package included
2045                 // in the user-defined preamble -- ARRae
2046                 // Actually it has to be done much later than that
2047                 // since some packages like frenchb make modifications
2048                 // at \begin{document} time -- JMarc
2049                 string bullets_def;
2050                 for (int i = 0; i < 4; ++i) {
2051                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2052                                 if (bullets_def.empty())
2053                                         bullets_def="\\AtBeginDocument{\n";
2054                                 bullets_def += "  \\renewcommand{\\labelitemi";
2055                                 switch (i) {
2056                                 // `i' is one less than the item to modify
2057                                 case 0:
2058                                         break;
2059                                 case 1:
2060                                         bullets_def += 'i';
2061                                         break;
2062                                 case 2:
2063                                         bullets_def += "ii";
2064                                         break;
2065                                 case 3:
2066                                         bullets_def += 'v';
2067                                         break;
2068                                 }
2069                                 bullets_def += "}{" +
2070                                   params.user_defined_bullets[i].getText()
2071                                   + "}\n";
2072                         }
2073                 }
2074
2075                 if (!bullets_def.empty())
2076                   preamble += bullets_def + "}\n\n";
2077
2078                 int const nlines =
2079                         int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2080                 for (int j = 0; j != nlines; ++j) {
2081                         texrow.newline();
2082                 }
2083
2084                 // We try to load babel late, in case it interferes
2085                 // with other packages.
2086                 if (use_babel) {
2087                         string tmp = lyxrc.language_package;
2088                         if (!lyxrc.language_global_options
2089                             && tmp == "\\usepackage{babel}")
2090                                 tmp = string("\\usepackage[") +
2091                                         STRCONV(language_options.str()) +
2092                                         "]{babel}";
2093                         preamble += tmp + "\n";
2094                         preamble += features.getBabelOptions();
2095                 }
2096
2097                 preamble += "\\makeatother\n";
2098
2099                 os << preamble;
2100
2101                 if (only_preamble)
2102                         return;
2103
2104                 // make the body.
2105                 os << "\\begin{document}\n";
2106                 texrow.newline();
2107         } // only_body
2108         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2109
2110         if (!lyxrc.language_auto_begin) {
2111                 os << subst(lyxrc.language_command_begin, "$$lang",
2112                              params.language->babel())
2113                     << endl;
2114                 texrow.newline();
2115         }
2116
2117         latexParagraphs(os, &*(paragraphs.begin()), 0, texrow);
2118
2119         // add this just in case after all the paragraphs
2120         os << endl;
2121         texrow.newline();
2122
2123         if (!lyxrc.language_auto_end) {
2124                 os << subst(lyxrc.language_command_end, "$$lang",
2125                              params.language->babel())
2126                     << endl;
2127                 texrow.newline();
2128         }
2129
2130         if (!only_body) {
2131                 os << "\\end{document}\n";
2132                 texrow.newline();
2133
2134                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2135         } else {
2136                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2137                                      << endl;
2138         }
2139
2140         // Just to be sure. (Asger)
2141         texrow.newline();
2142
2143         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
2144         lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
2145                             << '.' << endl;
2146
2147         // we want this to be true outside previews (for insetexternal)
2148         niceFile = true;
2149 }
2150
2151
2152 //
2153 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2154 //
2155 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2156                              Paragraph * endpar, TexRow & texrow,
2157                              bool moving_arg) const
2158 {
2159         bool was_title = false;
2160         bool already_title = false;
2161
2162         // if only_body
2163         while (par != endpar) {
2164                 Inset * in = par->inInset();
2165                 // well we have to check if we are in an inset with unlimited
2166                 // length (all in one row) if that is true then we don't allow
2167                 // any special options in the paragraph and also we don't allow
2168                 // any environment other then "Standard" to be valid!
2169                 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2170                         LyXLayout_ptr const & layout = par->layout();
2171
2172                         if (layout->intitle) {
2173                                 if (already_title) {
2174                                         lyxerr <<"Error in latexParagraphs: You"
2175                                                 " should not mix title layouts"
2176                                                 " with normal ones." << endl;
2177                                 } else
2178                                         was_title = true;
2179                         } else if (was_title && !already_title) {
2180                                 ofs << "\\maketitle\n";
2181                                 texrow.newline();
2182                                 already_title = true;
2183                                 was_title = false;
2184                         }
2185
2186                         if (layout->isEnvironment() ||
2187                                 !par->params().leftIndent().zero())
2188                         {
2189                                 par = par->TeXEnvironment(this, params, ofs, texrow);
2190                         } else {
2191                                 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2192                         }
2193                 } else {
2194                         par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2195                 }
2196         }
2197         // It might be that we only have a title in this document
2198         if (was_title && !already_title) {
2199                 ofs << "\\maketitle\n";
2200                 texrow.newline();
2201         }
2202 }
2203
2204
2205 bool Buffer::isLatex() const
2206 {
2207         return params.getLyXTextClass().outputType() == LATEX;
2208 }
2209
2210
2211 bool Buffer::isLinuxDoc() const
2212 {
2213         return params.getLyXTextClass().outputType() == LINUXDOC;
2214 }
2215
2216
2217 bool Buffer::isLiterate() const
2218 {
2219         return params.getLyXTextClass().outputType() == LITERATE;
2220 }
2221
2222
2223 bool Buffer::isDocBook() const
2224 {
2225         return params.getLyXTextClass().outputType() == DOCBOOK;
2226 }
2227
2228
2229 bool Buffer::isSGML() const
2230 {
2231         LyXTextClass const & tclass = params.getLyXTextClass();
2232
2233         return tclass.outputType() == LINUXDOC ||
2234                tclass.outputType() == DOCBOOK;
2235 }
2236
2237
2238 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2239 {
2240         ofstream ofs(fname.c_str());
2241
2242         if (!ofs) {
2243                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2244                 return;
2245         }
2246
2247         niceFile = nice; // this will be used by included files.
2248
2249         LaTeXFeatures features(params);
2250
2251         validate(features);
2252
2253         texrow.reset();
2254
2255         LyXTextClass const & tclass = params.getLyXTextClass();
2256
2257         string top_element = tclass.latexname();
2258
2259         if (!body_only) {
2260                 ofs << "<!doctype linuxdoc system";
2261
2262                 string preamble = params.preamble;
2263                 const string name = nice ? ChangeExtension(filename_, ".sgml")
2264                          : fname;
2265                 preamble += features.getIncludedFiles(name);
2266                 preamble += features.getLyXSGMLEntities();
2267
2268                 if (!preamble.empty()) {
2269                         ofs << " [ " << preamble << " ]";
2270                 }
2271                 ofs << ">\n\n";
2272
2273                 if (params.options.empty())
2274                         sgml::openTag(ofs, 0, false, top_element);
2275                 else {
2276                         string top = top_element;
2277                         top += ' ';
2278                         top += params.options;
2279                         sgml::openTag(ofs, 0, false, top);
2280                 }
2281         }
2282
2283         ofs << "<!-- "  << lyx_docversion
2284             << " created this file. For more info see http://www.lyx.org/"
2285             << " -->\n";
2286
2287         Paragraph::depth_type depth = 0; // paragraph depth
2288         Paragraph * par = &*(paragraphs.begin());
2289         string item_name;
2290         vector<string> environment_stack(5);
2291
2292         while (par) {
2293                 LyXLayout_ptr const & style = par->layout();
2294                 // treat <toc> as a special case for compatibility with old code
2295                 if (par->isInset(0)) {
2296                         Inset * inset = par->getInset(0);
2297                         Inset::Code lyx_code = inset->lyxCode();
2298                         if (lyx_code == Inset::TOC_CODE) {
2299                                 string const temp = "toc";
2300                                 sgml::openTag(ofs, depth, false, temp);
2301
2302                                 par = par->next();
2303                                 continue;
2304                         }
2305                 }
2306
2307                 // environment tag closing
2308                 for (; depth > par->params().depth(); --depth) {
2309                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2310                         environment_stack[depth].erase();
2311                 }
2312
2313                 // write opening SGML tags
2314                 switch (style->latextype) {
2315                 case LATEX_PARAGRAPH:
2316                         if (depth == par->params().depth()
2317                            && !environment_stack[depth].empty()) {
2318                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2319                                 environment_stack[depth].erase();
2320                                 if (depth)
2321                                         --depth;
2322                                 else
2323                                         ofs << "</p>";
2324                         }
2325                         sgml::openTag(ofs, depth, false, style->latexname());
2326                         break;
2327
2328                 case LATEX_COMMAND:
2329                         if (depth!= 0)
2330                                 sgmlError(par, 0,
2331                                           _("Error: Wrong depth for LatexType Command.\n"));
2332
2333                         if (!environment_stack[depth].empty()) {
2334                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2335                                 ofs << "</p>";
2336                         }
2337
2338                         environment_stack[depth].erase();
2339                         sgml::openTag(ofs, depth, false, style->latexname());
2340                         break;
2341
2342                 case LATEX_ENVIRONMENT:
2343                 case LATEX_ITEM_ENVIRONMENT:
2344                 {
2345                         string const & latexname = style->latexname();
2346
2347                         if (depth == par->params().depth()
2348                             && environment_stack[depth] != latexname) {
2349                                 sgml::closeTag(ofs, depth, false,
2350                                              environment_stack[depth]);
2351                                 environment_stack[depth].erase();
2352                         }
2353                         if (depth < par->params().depth()) {
2354                                depth = par->params().depth();
2355                                environment_stack[depth].erase();
2356                         }
2357                         if (environment_stack[depth] != latexname) {
2358                                 if (depth == 0) {
2359                                         sgml::openTag(ofs, depth, false, "p");
2360                                 }
2361                                 sgml::openTag(ofs, depth, false, latexname);
2362
2363                                 if (environment_stack.size() == depth + 1)
2364                                         environment_stack.push_back("!-- --");
2365                                 environment_stack[depth] = latexname;
2366                         }
2367
2368                         if (style->latexparam() == "CDATA")
2369                                 ofs << "<![CDATA[";
2370
2371                         if (style->latextype == LATEX_ENVIRONMENT) break;
2372
2373                         if (style->labeltype == LABEL_MANUAL)
2374                                 item_name = "tag";
2375                         else
2376                                 item_name = "item";
2377
2378                         sgml::openTag(ofs, depth + 1, false, item_name);
2379                 }
2380                 break;
2381
2382                 default:
2383                         sgml::openTag(ofs, depth, false, style->latexname());
2384                         break;
2385                 }
2386
2387                 simpleLinuxDocOnePar(ofs, par, depth);
2388
2389                 par = par->next();
2390
2391                 ofs << "\n";
2392                 // write closing SGML tags
2393                 switch (style->latextype) {
2394                 case LATEX_COMMAND:
2395                         break;
2396                 case LATEX_ENVIRONMENT:
2397                 case LATEX_ITEM_ENVIRONMENT:
2398                         if (style->latexparam() == "CDATA")
2399                                 ofs << "]]>";
2400                         break;
2401                 default:
2402                         sgml::closeTag(ofs, depth, false, style->latexname());
2403                         break;
2404                 }
2405         }
2406
2407         // Close open tags
2408         for (int i = depth; i >= 0; --i)
2409                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
2410
2411         if (!body_only) {
2412                 ofs << "\n\n";
2413                 sgml::closeTag(ofs, 0, false, top_element);
2414         }
2415
2416         ofs.close();
2417         // How to check for successful close
2418
2419         // we want this to be true outside previews (for insetexternal)
2420         niceFile = true;
2421 }
2422
2423
2424 // checks, if newcol chars should be put into this line
2425 // writes newline, if necessary.
2426 namespace {
2427
2428 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2429                           string::size_type newcol)
2430 {
2431         colcount += newcol;
2432         if (colcount > lyxrc.ascii_linelen) {
2433                 os << "\n";
2434                 colcount = newcol; // assume write after this call
2435         }
2436 }
2437
2438 enum PAR_TAG {
2439         NONE=0,
2440         TT = 1,
2441         SF = 2,
2442         BF = 4,
2443         IT = 8,
2444         SL = 16,
2445         EM = 32
2446 };
2447
2448
2449 string tag_name(PAR_TAG const & pt) {
2450         switch (pt) {
2451         case NONE: return "!-- --";
2452         case TT: return "tt";
2453         case SF: return "sf";
2454         case BF: return "bf";
2455         case IT: return "it";
2456         case SL: return "sl";
2457         case EM: return "em";
2458         }
2459         return "";
2460 }
2461
2462
2463 inline
2464 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2465 {
2466         p1 = static_cast<PAR_TAG>(p1 | p2);
2467 }
2468
2469
2470 inline
2471 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2472 {
2473         p1 = static_cast<PAR_TAG>(p1 & ~p2);
2474 }
2475
2476 } // anon
2477
2478
2479 // Handle internal paragraph parsing -- layout already processed.
2480 void Buffer::simpleLinuxDocOnePar(ostream & os,
2481         Paragraph * par,
2482         Paragraph::depth_type /*depth*/)
2483 {
2484         LyXLayout_ptr const & style = par->layout();
2485
2486         string::size_type char_line_count = 5;     // Heuristic choice ;-)
2487
2488         // gets paragraph main font
2489         LyXFont font_old;
2490         bool desc_on;
2491         if (style->labeltype == LABEL_MANUAL) {
2492                 font_old = style->labelfont;
2493                 desc_on = true;
2494         } else {
2495                 font_old = style->font;
2496                 desc_on = false;
2497         }
2498
2499         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2500         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2501         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
2502         bool is_em = false;
2503
2504         stack<PAR_TAG> tag_state;
2505         // parsing main loop
2506         for (pos_type i = 0; i < par->size(); ++i) {
2507
2508                 PAR_TAG tag_close = NONE;
2509                 list < PAR_TAG > tag_open;
2510
2511                 LyXFont const font = par->getFont(params, i);
2512
2513                 if (font_old.family() != font.family()) {
2514                         switch (family_type) {
2515                         case LyXFont::SANS_FAMILY:
2516                                 tag_close |= SF;
2517                                 break;
2518                         case LyXFont::TYPEWRITER_FAMILY:
2519                                 tag_close |= TT;
2520                                 break;
2521                         default:
2522                                 break;
2523                         }
2524
2525                         family_type = font.family();
2526
2527                         switch (family_type) {
2528                         case LyXFont::SANS_FAMILY:
2529                                 tag_open.push_back(SF);
2530                                 break;
2531                         case LyXFont::TYPEWRITER_FAMILY:
2532                                 tag_open.push_back(TT);
2533                                 break;
2534                         default:
2535                                 break;
2536                         }
2537                 }
2538
2539                 if (font_old.series() != font.series()) {
2540                         switch (series_type) {
2541                         case LyXFont::BOLD_SERIES:
2542                                 tag_close |= BF;
2543                                 break;
2544                         default:
2545                                 break;
2546                         }
2547
2548                         series_type = font.series();
2549
2550                         switch (series_type) {
2551                         case LyXFont::BOLD_SERIES:
2552                                 tag_open.push_back(BF);
2553                                 break;
2554                         default:
2555                                 break;
2556                         }
2557
2558                 }
2559
2560                 if (font_old.shape() != font.shape()) {
2561                         switch (shape_type) {
2562                         case LyXFont::ITALIC_SHAPE:
2563                                 tag_close |= IT;
2564                                 break;
2565                         case LyXFont::SLANTED_SHAPE:
2566                                 tag_close |= SL;
2567                                 break;
2568                         default:
2569                                 break;
2570                         }
2571
2572                         shape_type = font.shape();
2573
2574                         switch (shape_type) {
2575                         case LyXFont::ITALIC_SHAPE:
2576                                 tag_open.push_back(IT);
2577                                 break;
2578                         case LyXFont::SLANTED_SHAPE:
2579                                 tag_open.push_back(SL);
2580                                 break;
2581                         default:
2582                                 break;
2583                         }
2584                 }
2585                 // handle <em> tag
2586                 if (font_old.emph() != font.emph()) {
2587                         if (font.emph() == LyXFont::ON) {
2588                                 tag_open.push_back(EM);
2589                                 is_em = true;
2590                         }
2591                         else if (is_em) {
2592                                 tag_close |= EM;
2593                                 is_em = false;
2594                         }
2595                 }
2596
2597                 list < PAR_TAG > temp;
2598                 while (!tag_state.empty() && tag_close) {
2599                         PAR_TAG k =  tag_state.top();
2600                         tag_state.pop();
2601                         os << "</" << tag_name(k) << '>';
2602                         if (tag_close & k)
2603                                 reset(tag_close,k);
2604                         else
2605                                 temp.push_back(k);
2606                 }
2607
2608                 for(list< PAR_TAG >::const_iterator j = temp.begin();
2609                     j != temp.end(); ++j) {
2610                         tag_state.push(*j);
2611                         os << '<' << tag_name(*j) << '>';
2612                 }
2613
2614                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2615                     j != tag_open.end(); ++j) {
2616                         tag_state.push(*j);
2617                         os << '<' << tag_name(*j) << '>';
2618                 }
2619
2620                 char c = par->getChar(i);
2621
2622                 if (c == Paragraph::META_INSET) {
2623                         Inset * inset = par->getInset(i);
2624                         inset->linuxdoc(this, os);
2625                         font_old = font;
2626                         continue;
2627                 }
2628
2629                 if (style->latexparam() == "CDATA") {
2630                         // "TeX"-Mode on == > SGML-Mode on.
2631                         if (c != '\0')
2632                                 os << c;
2633                         ++char_line_count;
2634                 } else {
2635                         bool ws;
2636                         string str;
2637                         boost::tie(ws, str) = sgml::escapeChar(c);
2638                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2639                                 // in freespacing mode, spaces are
2640                                 // non-breaking characters
2641                                 if (desc_on) {// if char is ' ' then...
2642
2643                                         ++char_line_count;
2644                                         sgmlLineBreak(os, char_line_count, 6);
2645                                         os << "</tag>";
2646                                         desc_on = false;
2647                                 } else  {
2648                                         sgmlLineBreak(os, char_line_count, 1);
2649                                         os << c;
2650                                 }
2651                         } else {
2652                                 os << str;
2653                                 char_line_count += str.length();
2654                         }
2655                 }
2656                 font_old = font;
2657         }
2658
2659         while (!tag_state.empty()) {
2660                 os << "</" << tag_name(tag_state.top()) << '>';
2661                 tag_state.pop();
2662         }
2663
2664         // resets description flag correctly
2665         if (desc_on) {
2666                 // <tag> not closed...
2667                 sgmlLineBreak(os, char_line_count, 6);
2668                 os << "</tag>";
2669         }
2670 }
2671
2672
2673 // Print an error message.
2674 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2675         string const & /*message*/) const
2676 {
2677 #ifdef WITH_WARNINGS
2678 #warning This is wrong we cannot insert an inset like this!!!
2679         // I guess this was Jose' so I explain you more or less why this
2680         // is wrong. This way you insert something in the paragraph and
2681         // don't tell it to LyXText (row rebreaking and undo handling!!!)
2682         // I deactivate this code, have a look at BufferView::insertErrors
2683         // how you should do this correctly! (Jug 20020315)
2684 #endif
2685 #if 0
2686         // insert an error marker in text
2687         InsetError * new_inset = new InsetError(message);
2688         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2689                          params.language));
2690 #endif
2691 }
2692
2693
2694 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2695 {
2696         ofstream ofs(fname.c_str());
2697         if (!ofs) {
2698                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2699                 return;
2700         }
2701
2702         Paragraph * par = &*(paragraphs.begin());
2703
2704         niceFile = nice; // this will be used by Insetincludes.
2705
2706         LaTeXFeatures features(params);
2707         validate(features);
2708
2709         texrow.reset();
2710
2711         LyXTextClass const & tclass = params.getLyXTextClass();
2712         string top_element = tclass.latexname();
2713
2714         if (!only_body) {
2715                 ofs << "<!DOCTYPE " << top_element
2716                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2717
2718                 string preamble = params.preamble;
2719                 const string name = nice ? ChangeExtension(filename_, ".sgml")
2720                          : fname;
2721                 preamble += features.getIncludedFiles(name);
2722                 preamble += features.getLyXSGMLEntities();
2723
2724                 if (!preamble.empty()) {
2725                         ofs << "\n [ " << preamble << " ]";
2726                 }
2727                 ofs << ">\n\n";
2728         }
2729
2730         string top = top_element;
2731         top += " lang=\"";
2732         top += params.language->code();
2733         top += '"';
2734
2735         if (!params.options.empty()) {
2736                 top += ' ';
2737                 top += params.options;
2738         }
2739         sgml::openTag(ofs, 0, false, top);
2740
2741         ofs << "<!-- DocBook file was created by " << lyx_docversion
2742             << "\n  See http://www.lyx.org/ for more information -->\n";
2743
2744         vector<string> environment_stack(10);
2745         vector<string> environment_inner(10);
2746         vector<string> command_stack(10);
2747
2748         bool command_flag = false;
2749         Paragraph::depth_type command_depth = 0;
2750         Paragraph::depth_type command_base = 0;
2751         Paragraph::depth_type cmd_depth = 0;
2752         Paragraph::depth_type depth = 0; // paragraph depth
2753
2754         string item_name;
2755         string command_name;
2756
2757         while (par) {
2758                 string sgmlparam;
2759                 string c_depth;
2760                 string c_params;
2761                 int desc_on = 0; // description mode
2762
2763                 LyXLayout_ptr const & style = par->layout();
2764
2765                 // environment tag closing
2766                 for (; depth > par->params().depth(); --depth) {
2767                         if (environment_inner[depth] != "!-- --") {
2768                                 item_name = "listitem";
2769                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2770                                 if (environment_inner[depth] == "varlistentry")
2771                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
2772                         }
2773                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2774                         environment_stack[depth].erase();
2775                         environment_inner[depth].erase();
2776                 }
2777
2778                 if (depth == par->params().depth()
2779                    && environment_stack[depth] != style->latexname()
2780                    && !environment_stack[depth].empty()) {
2781                         if (environment_inner[depth] != "!-- --") {
2782                                 item_name= "listitem";
2783                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
2784                                 if (environment_inner[depth] == "varlistentry")
2785                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2786                         }
2787
2788                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2789
2790                         environment_stack[depth].erase();
2791                         environment_inner[depth].erase();
2792                 }
2793
2794                 // Write opening SGML tags.
2795                 switch (style->latextype) {
2796                 case LATEX_PARAGRAPH:
2797                         sgml::openTag(ofs, depth + command_depth,
2798                                     false, style->latexname());
2799                         break;
2800
2801                 case LATEX_COMMAND:
2802                         if (depth != 0)
2803                                 sgmlError(par, 0,
2804                                           _("Error: Wrong depth for 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 }