]> git.lyx.org Git - lyx.git/blob - src/buffer.C
Remove the XOpenIM test as lyxlookup.C has been buried.
[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                                 _("LyX will not be able to produce output correctly."));
625 #else
626                         Alert::alert(
627                                 _("Textclass error"),
628                                 _("The document uses an unknown textclass ")
629                                 + lex.getString(),
630                                 _("LyX will not be able to produce output correctly."));
631 #endif
632                         params.textclass = 0;
633                 }
634                 if (!params.getLyXTextClass().load()) {
635                         // if the textclass wasn't loaded properly
636                         // we need to either substitute another
637                         // or stop loading the file.
638                         // I can substitute but I don't see how I can
639                         // stop loading... ideas??  ARRae980418
640 #if USE_BOOST_FORMAT
641                         Alert::alert(_("Textclass Loading Error!"),
642                                    boost::io::str(boost::format(_("Can't load textclass %1$s")) %
643                                    params.getLyXTextClass().name()),
644                                    _("-- substituting default"));
645 #else
646                         Alert::alert(_("Textclass Loading Error!"),
647                                      _("Can't load textclass ")
648                                      + params.getLyXTextClass().name(),
649                                      _("-- substituting default"));
650 #endif
651                         params.textclass = 0;
652                 }
653         } else if (token == "\\options") {
654                 lex.eatLine();
655                 params.options = lex.getString();
656         } else if (token == "\\language") {
657                 params.readLanguage(lex);
658         } else if (token == "\\fontencoding") {
659                 lex.eatLine();
660         } else if (token == "\\inputencoding") {
661                 lex.eatLine();
662                 params.inputenc = lex.getString();
663         } else if (token == "\\graphics") {
664                 params.readGraphicsDriver(lex);
665         } else if (token == "\\fontscheme") {
666                 lex.eatLine();
667                 params.fonts = lex.getString();
668         } else if (token == "\\noindent") {
669                 par->params().noindent(true);
670         } else if (token == "\\leftindent") {
671                 lex.nextToken();
672                 LyXLength value(lex.getString());
673                 par->params().leftIndent(value);
674         } else if (token == "\\fill_top") {
675                 par->params().spaceTop(VSpace(VSpace::VFILL));
676         } else if (token == "\\fill_bottom") {
677                 par->params().spaceBottom(VSpace(VSpace::VFILL));
678         } else if (token == "\\line_top") {
679                 par->params().lineTop(true);
680         } else if (token == "\\line_bottom") {
681                 par->params().lineBottom(true);
682         } else if (token == "\\pagebreak_top") {
683                 par->params().pagebreakTop(true);
684         } else if (token == "\\pagebreak_bottom") {
685                 par->params().pagebreakBottom(true);
686         } else if (token == "\\start_of_appendix") {
687                 par->params().startOfAppendix(true);
688         } else if (token == "\\paragraph_separation") {
689                 int tmpret = lex.findToken(string_paragraph_separation);
690                 if (tmpret == -1)
691                         ++tmpret;
692                 params.paragraph_separation =
693                         static_cast<BufferParams::PARSEP>(tmpret);
694         } else if (token == "\\defskip") {
695                 lex.nextToken();
696                 params.defskip = VSpace(lex.getString());
697         } else if (token == "\\quotes_language") {
698                 int tmpret = lex.findToken(string_quotes_language);
699                 if (tmpret == -1)
700                         ++tmpret;
701                 InsetQuotes::quote_language tmpl =
702                         InsetQuotes::EnglishQ;
703                 switch (tmpret) {
704                 case 0:
705                         tmpl = InsetQuotes::EnglishQ;
706                         break;
707                 case 1:
708                         tmpl = InsetQuotes::SwedishQ;
709                         break;
710                 case 2:
711                         tmpl = InsetQuotes::GermanQ;
712                         break;
713                 case 3:
714                         tmpl = InsetQuotes::PolishQ;
715                         break;
716                 case 4:
717                         tmpl = InsetQuotes::FrenchQ;
718                         break;
719                 case 5:
720                         tmpl = InsetQuotes::DanishQ;
721                         break;
722                 }
723                 params.quotes_language = tmpl;
724         } else if (token == "\\quotes_times") {
725                 lex.nextToken();
726                 switch (lex.getInteger()) {
727                 case 1:
728                         params.quotes_times = InsetQuotes::SingleQ;
729                         break;
730                 case 2:
731                         params.quotes_times = InsetQuotes::DoubleQ;
732                         break;
733                 }
734         } else if (token == "\\papersize") {
735                 int tmpret = lex.findToken(string_papersize);
736                 if (tmpret == -1)
737                         ++tmpret;
738                 else
739                         params.papersize2 = tmpret;
740         } else if (token == "\\paperpackage") {
741                 int tmpret = lex.findToken(string_paperpackages);
742                 if (tmpret == -1) {
743                         ++tmpret;
744                         params.paperpackage = BufferParams::PACKAGE_NONE;
745                 } else
746                         params.paperpackage = tmpret;
747         } else if (token == "\\use_geometry") {
748                 lex.nextToken();
749                 params.use_geometry = lex.getInteger();
750         } else if (token == "\\use_amsmath") {
751                 lex.nextToken();
752                 params.use_amsmath = lex.getInteger();
753         } else if (token == "\\use_natbib") {
754                 lex.nextToken();
755                 params.use_natbib = lex.getInteger();
756         } else if (token == "\\use_numerical_citations") {
757                 lex.nextToken();
758                 params.use_numerical_citations = lex.getInteger();
759         } else if (token == "\\paperorientation") {
760                 int tmpret = lex.findToken(string_orientation);
761                 if (tmpret == -1)
762                         ++tmpret;
763                 params.orientation =
764                         static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
765         } else if (token == "\\paperwidth") {
766                 lex.next();
767                 params.paperwidth = lex.getString();
768         } else if (token == "\\paperheight") {
769                 lex.next();
770                 params.paperheight = lex.getString();
771         } else if (token == "\\leftmargin") {
772                 lex.next();
773                 params.leftmargin = lex.getString();
774         } else if (token == "\\topmargin") {
775                 lex.next();
776                 params.topmargin = lex.getString();
777         } else if (token == "\\rightmargin") {
778                 lex.next();
779                 params.rightmargin = lex.getString();
780         } else if (token == "\\bottommargin") {
781                 lex.next();
782                 params.bottommargin = lex.getString();
783         } else if (token == "\\headheight") {
784                 lex.next();
785                 params.headheight = lex.getString();
786         } else if (token == "\\headsep") {
787                 lex.next();
788                 params.headsep = lex.getString();
789         } else if (token == "\\footskip") {
790                 lex.next();
791                 params.footskip = lex.getString();
792         } else if (token == "\\paperfontsize") {
793                 lex.nextToken();
794                 params.fontsize = rtrim(lex.getString());
795         } else if (token == "\\papercolumns") {
796                 lex.nextToken();
797                 params.columns = lex.getInteger();
798         } else if (token == "\\papersides") {
799                 lex.nextToken();
800                 switch (lex.getInteger()) {
801                 default:
802                 case 1: params.sides = LyXTextClass::OneSide; break;
803                 case 2: params.sides = LyXTextClass::TwoSides; break;
804                 }
805         } else if (token == "\\paperpagestyle") {
806                 lex.nextToken();
807                 params.pagestyle = rtrim(lex.getString());
808         } else if (token == "\\bullet") {
809                 lex.nextToken();
810                 int const index = lex.getInteger();
811                 lex.nextToken();
812                 int temp_int = lex.getInteger();
813                 params.user_defined_bullets[index].setFont(temp_int);
814                 params.temp_bullets[index].setFont(temp_int);
815                 lex.nextToken();
816                 temp_int = lex.getInteger();
817                 params.user_defined_bullets[index].setCharacter(temp_int);
818                 params.temp_bullets[index].setCharacter(temp_int);
819                 lex.nextToken();
820                 temp_int = lex.getInteger();
821                 params.user_defined_bullets[index].setSize(temp_int);
822                 params.temp_bullets[index].setSize(temp_int);
823                 lex.nextToken();
824                 string const temp_str = lex.getString();
825                 if (temp_str != "\\end_bullet") {
826                                 // this element isn't really necessary for
827                                 // parsing but is easier for humans
828                                 // to understand bullets. Put it back and
829                                 // set a debug message?
830                         lex.printError("\\end_bullet expected, got" + temp_str);
831                                 //how can I put it back?
832                 }
833         } else if (token == "\\bulletLaTeX") {
834                 // The bullet class should be able to read this.
835                 lex.nextToken();
836                 int const index = lex.getInteger();
837                 lex.next();
838                 string temp_str = lex.getString();
839                 string sum_str;
840                 while (temp_str != "\\end_bullet") {
841                                 // this loop structure is needed when user
842                                 // enters an empty string since the first
843                                 // thing returned will be the \\end_bullet
844                                 // OR
845                                 // if the LaTeX entry has spaces. Each element
846                                 // therefore needs to be read in turn
847                         sum_str += temp_str;
848                         lex.next();
849                         temp_str = lex.getString();
850                 }
851
852                 params.user_defined_bullets[index].setText(sum_str);
853                 params.temp_bullets[index].setText(sum_str);
854         } else if (token == "\\secnumdepth") {
855                 lex.nextToken();
856                 params.secnumdepth = lex.getInteger();
857         } else if (token == "\\tocdepth") {
858                 lex.nextToken();
859                 params.tocdepth = lex.getInteger();
860         } else if (token == "\\spacing") {
861                 lex.next();
862                 string const tmp = rtrim(lex.getString());
863                 Spacing::Space tmp_space = Spacing::Default;
864                 float tmp_val = 0.0;
865                 if (tmp == "single") {
866                         tmp_space = Spacing::Single;
867                 } else if (tmp == "onehalf") {
868                         tmp_space = Spacing::Onehalf;
869                 } else if (tmp == "double") {
870                         tmp_space = Spacing::Double;
871                 } else if (tmp == "other") {
872                         lex.next();
873                         tmp_space = Spacing::Other;
874                         tmp_val = lex.getFloat();
875                 } else {
876                         lex.printError("Unknown spacing token: '$$Token'");
877                 }
878                 // Small hack so that files written with klyx will be
879                 // parsed correctly.
880                 if (first_par) {
881                         par->params().spacing(Spacing(tmp_space, tmp_val));
882                 } else {
883                         params.spacing.set(tmp_space, tmp_val);
884                 }
885         } else if (token == "\\paragraph_spacing") {
886                 lex.next();
887                 string const tmp = rtrim(lex.getString());
888                 if (tmp == "single") {
889                         par->params().spacing(Spacing(Spacing::Single));
890                 } else if (tmp == "onehalf") {
891                         par->params().spacing(Spacing(Spacing::Onehalf));
892                 } else if (tmp == "double") {
893                         par->params().spacing(Spacing(Spacing::Double));
894                 } else if (tmp == "other") {
895                         lex.next();
896                         par->params().spacing(Spacing(Spacing::Other,
897                                          lex.getFloat()));
898                 } else {
899                         lex.printError("Unknown spacing token: '$$Token'");
900                 }
901         } else if (token == "\\float_placement") {
902                 lex.nextToken();
903                 params.float_placement = lex.getString();
904         } else if (token == "\\align") {
905                 int tmpret = lex.findToken(string_align);
906                 if (tmpret == -1) ++tmpret;
907                 int const tmpret2 = int(pow(2.0, tmpret));
908                 par->params().align(LyXAlignment(tmpret2));
909         } else if (token == "\\added_space_top") {
910                 lex.nextToken();
911                 VSpace value = VSpace(lex.getString());
912                 // only add the length when value > 0 or
913                 // with option keep
914                 if ((value.length().len().value() != 0) ||
915                     value.keep() ||
916                     (value.kind() != VSpace::LENGTH))
917                         par->params().spaceTop(value);
918         } else if (token == "\\added_space_bottom") {
919                 lex.nextToken();
920                 VSpace value = VSpace(lex.getString());
921                 // only add the length when value > 0 or
922                 // with option keep
923                 if ((value.length().len().value() != 0) ||
924                    value.keep() ||
925                     (value.kind() != VSpace::LENGTH))
926                         par->params().spaceBottom(value);
927         } else if (token == "\\labelwidthstring") {
928                 lex.eatLine();
929                 par->params().labelWidthString(lex.getString());
930                 // do not delete this token, it is still needed!
931         } else if (token == "\\newline") {
932                 par->insertChar(pos, Paragraph::META_NEWLINE, font);
933                 ++pos;
934         } else if (token == "\\LyXTable") {
935                 Inset * inset = new InsetTabular(*this);
936                 inset->read(this, lex);
937                 par->insertInset(pos, inset, font);
938                 ++pos;
939         } else if (token == "\\hfill") {
940                 par->insertChar(pos, Paragraph::META_HFILL, font);
941                 ++pos;
942         } else if (token == "\\bibitem") {  // ale970302
943                 if (!par->bibkey) {
944                         InsetCommandParams p("bibitem", "dummy");
945                         par->bibkey = new InsetBibKey(p);
946                 }
947                 par->bibkey->read(this, lex);
948         } else if (token == "\\the_end") {
949                 the_end_read = true;
950         } else {
951                 // This should be insurance for the future: (Asger)
952                 ++unknown_tokens;
953                 lex.eatLine();
954 #if USE_BOOST_FORMAT
955                 boost::format fmt(_("Unknown token: %1$s %2$s\n"));
956                 fmt % token % lex.text();
957                 string const s = fmt.str();
958 #else
959                 string const s = _("Unknown token: ") + token
960                         + ' ' + lex.text() + '\n';
961 #endif
962                 // we can do this here this way because we're actually reading
963                 // the buffer and don't care about LyXText right now.
964                 InsetError * new_inset = new InsetError(s);
965                 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
966                                  params.language));
967
968         }
969
970         return the_end_read;
971 }
972
973
974 // needed to insert the selection
975 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
976                                  LyXFont const & fn,string const & str) const
977 {
978         LyXLayout_ptr const & layout = par->layout();
979
980         LyXFont font = fn;
981
982         par->checkInsertChar(font);
983         // insert the string, don't insert doublespace
984         bool space_inserted = true;
985         bool autobreakrows = !par->inInset() ||
986                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
987         for(string::const_iterator cit = str.begin();
988             cit != str.end(); ++cit) {
989                 if (*cit == '\n') {
990                         if (autobreakrows && (!par->empty() || layout->keepempty)) {
991                                 breakParagraph(params, par, pos,
992                                                layout->isEnvironment());
993                                 par = par->next();
994                                 pos = 0;
995                                 space_inserted = true;
996                         } else {
997                                 continue;
998                         }
999                         // do not insert consecutive spaces if !free_spacing
1000                 } else if ((*cit == ' ' || *cit == '\t') &&
1001                            space_inserted && !layout->free_spacing &&
1002                                    !par->isFreeSpacing())
1003                 {
1004                         continue;
1005                 } else if (*cit == '\t') {
1006                         if (!layout->free_spacing && !par->isFreeSpacing()) {
1007                                 // tabs are like spaces here
1008                                 par->insertChar(pos, ' ', font);
1009                                 ++pos;
1010                                 space_inserted = true;
1011                         } else {
1012                                 const pos_type nb = 8 - pos % 8;
1013                                 for (pos_type a = 0; a < nb ; ++a) {
1014                                         par->insertChar(pos, ' ', font);
1015                                         ++pos;
1016                                 }
1017                                 space_inserted = true;
1018                         }
1019                 } else if (!IsPrintable(*cit)) {
1020                         // Ignore unprintables
1021                         continue;
1022                 } else {
1023                         // just insert the character
1024                         par->insertChar(pos, *cit, font);
1025                         ++pos;
1026                         space_inserted = (*cit == ' ');
1027                 }
1028
1029         }
1030 }
1031
1032
1033 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1034                        int & pos, LyXFont & font)
1035 {
1036         // consistency check
1037         if (lex.getString() != "\\begin_inset") {
1038                 lyxerr << "Buffer::readInset: Consistency check failed."
1039                        << endl;
1040         }
1041
1042         Inset * inset = 0;
1043
1044         lex.next();
1045         string const tmptok = lex.getString();
1046         last_inset_read = tmptok;
1047
1048         // test the different insets
1049         if (tmptok == "LatexCommand") {
1050                 InsetCommandParams inscmd;
1051                 inscmd.read(lex);
1052
1053                 string const cmdName = inscmd.getCmdName();
1054
1055                 // This strange command allows LyX to recognize "natbib" style
1056                 // citations: citet, citep, Citet etc.
1057                 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
1058                         inset = new InsetCitation(inscmd);
1059                 } else if (cmdName == "bibitem") {
1060                         lex.printError("Wrong place for bibitem");
1061                         inset = new InsetBibKey(inscmd);
1062                 } else if (cmdName == "BibTeX") {
1063                         inset = new InsetBibtex(inscmd);
1064                 } else if (cmdName == "index") {
1065                         inset = new InsetIndex(inscmd);
1066                 } else if (cmdName == "include") {
1067                         inset = new InsetInclude(inscmd, *this);
1068                 } else if (cmdName == "label") {
1069                         inset = new InsetLabel(inscmd);
1070                 } else if (cmdName == "url"
1071                            || cmdName == "htmlurl") {
1072                         inset = new InsetUrl(inscmd);
1073                 } else if (cmdName == "ref"
1074                            || cmdName == "pageref"
1075                            || cmdName == "vref"
1076                            || cmdName == "vpageref"
1077                            || cmdName == "prettyref") {
1078                         if (!inscmd.getOptions().empty()
1079                             || !inscmd.getContents().empty()) {
1080                                 inset = new InsetRef(inscmd, *this);
1081                         }
1082                 } else if (cmdName == "tableofcontents") {
1083                         inset = new InsetTOC(inscmd);
1084                 } else if (cmdName == "listofalgorithms") {
1085                         inset = new InsetFloatList("algorithm");
1086                 } else if (cmdName == "listoffigures") {
1087                         inset = new InsetFloatList("figure");
1088                 } else if (cmdName == "listoftables") {
1089                         inset = new InsetFloatList("table");
1090                 } else if (cmdName == "printindex") {
1091                         inset = new InsetPrintIndex(inscmd);
1092                 } else if (cmdName == "lyxparent") {
1093                         inset = new InsetParent(inscmd, *this);
1094                 }
1095         } else {
1096                 bool alreadyread = false;
1097                 if (tmptok == "Quotes") {
1098                         inset = new InsetQuotes;
1099                 } else if (tmptok == "External") {
1100                         inset = new InsetExternal;
1101                 } else if (tmptok == "FormulaMacro") {
1102                         inset = new InsetFormulaMacro;
1103                 } else if (tmptok == "Formula") {
1104                         inset = new InsetFormula;
1105                 } else if (tmptok == "Figure") { // Backward compatibility
1106 //                      inset = new InsetFig(100, 100, *this);
1107                         inset = new InsetGraphics;
1108                 } else if (tmptok == "Graphics") {
1109                         inset = new InsetGraphics;
1110                 } else if (tmptok == "Info") {// backwards compatibility
1111                         inset = new InsetNote(this,
1112                                               lex.getLongString("\\end_inset"),
1113                                               true);
1114                         alreadyread = true;
1115                 } else if (tmptok == "Note") {
1116                         inset = new InsetNote(params);
1117                 } else if (tmptok == "Include") {
1118                         InsetCommandParams p("Include");
1119                         inset = new InsetInclude(p, *this);
1120                 } else if (tmptok == "ERT") {
1121                         inset = new InsetERT(params);
1122                 } else if (tmptok == "Tabular") {
1123                         inset = new InsetTabular(*this);
1124                 } else if (tmptok == "Text") {
1125                         inset = new InsetText(params);
1126                 } else if (tmptok == "Foot") {
1127                         inset = new InsetFoot(params);
1128                 } else if (tmptok == "Marginal") {
1129                         inset = new InsetMarginal(params);
1130                 } else if (tmptok == "OptArg") {
1131                         inset = new InsetOptArg(params);
1132                 } else if (tmptok == "Minipage") {
1133                         inset = new InsetMinipage(params);
1134                 } else if (tmptok == "Float") {
1135                         lex.next();
1136                         string tmptok = lex.getString();
1137                         inset = new InsetFloat(params, tmptok);
1138                 } else if (tmptok == "Wrap") {
1139                         lex.next();
1140                         string tmptok = lex.getString();
1141                         inset = new InsetWrap(params, tmptok);
1142 #if 0
1143                 } else if (tmptok == "List") {
1144                         inset = new InsetList;
1145                 } else if (tmptok == "Theorem") {
1146                         inset = new InsetList;
1147 #endif
1148                 } else if (tmptok == "Caption") {
1149                         inset = new InsetCaption(params);
1150                 } else if (tmptok == "FloatList") {
1151                         inset = new InsetFloatList;
1152                 }
1153
1154                 if (inset && !alreadyread) inset->read(this, lex);
1155         }
1156
1157         if (inset) {
1158                 par->insertInset(pos, inset, font);
1159                 ++pos;
1160         }
1161 }
1162
1163
1164 bool Buffer::readFile(LyXLex & lex, string const & filename, Paragraph * par)
1165 {
1166         if (lex.isOK()) {
1167                 lex.next();
1168                 string const token(lex.getString());
1169                 if (token == "\\lyxformat") { // the first token _must_ be...
1170                         lex.eatLine();
1171                         string tmp_format = lex.getString();
1172                         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
1173                         // if present remove ".," from string.
1174                         string::size_type dot = tmp_format.find_first_of(".,");
1175                         //lyxerr << "           dot found at " << dot << endl;
1176                         if (dot != string::npos)
1177                                 tmp_format.erase(dot, 1);
1178                         file_format = strToInt(tmp_format);
1179                         //lyxerr << "format: " << file_format << endl;
1180                         if (file_format == LYX_FORMAT) {
1181                                 // current format
1182                         } else if (file_format > LYX_FORMAT) {
1183                                 // future format
1184                                 Alert::alert(_("Warning!"),
1185                                         _("The file was created with a newer version of"
1186                                         "LyX. This is likely to cause problems."));
1187
1188                         } else if (file_format < LYX_FORMAT) {
1189                                 // old formats
1190                                 if (file_format < 200) {
1191                                         Alert::alert(_("ERROR!"),
1192                                                    _("Old LyX file format found. "
1193                                                      "Use LyX 0.10.x to read this!"));
1194                                         return false;
1195                                 } else if (!filename.empty()) {
1196                                         string command =
1197                                                 LibFileSearch("lyx2lyx", "lyx2lyx");
1198                                         if (command.empty()) {
1199                                                 Alert::alert(_("ERROR!"),
1200                                                              _("Can't find conversion script."));
1201                                                 return false;
1202                                         }
1203                                         command += " -t"
1204                                                 +tostr(LYX_FORMAT) + ' '
1205                                                 + QuoteName(filename);
1206                                         lyxerr[Debug::INFO] << "Running '"
1207                                                             << command << '\''
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());
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"
2332                                             " LatexType Command.\n"));
2333
2334                         if (!environment_stack[depth].empty()) {
2335                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
2336                                 ofs << "</p>";
2337                         }
2338
2339                         environment_stack[depth].erase();
2340                         sgml::openTag(ofs, depth, false, style->latexname());
2341                         break;
2342
2343                 case LATEX_ENVIRONMENT:
2344                 case LATEX_ITEM_ENVIRONMENT:
2345                 {
2346                         string const & latexname = style->latexname();
2347
2348                         if (depth == par->params().depth()
2349                             && environment_stack[depth] != latexname) {
2350                                 sgml::closeTag(ofs, depth, false,
2351                                              environment_stack[depth]);
2352                                 environment_stack[depth].erase();
2353                         }
2354                         if (depth < par->params().depth()) {
2355                                depth = par->params().depth();
2356                                environment_stack[depth].erase();
2357                         }
2358                         if (environment_stack[depth] != latexname) {
2359                                 if (depth == 0) {
2360                                         sgml::openTag(ofs, depth, false, "p");
2361                                 }
2362                                 sgml::openTag(ofs, depth, false, latexname);
2363
2364                                 if (environment_stack.size() == depth + 1)
2365                                         environment_stack.push_back("!-- --");
2366                                 environment_stack[depth] = latexname;
2367                         }
2368
2369                         if (style->latexparam() == "CDATA")
2370                                 ofs << "<![CDATA[";
2371
2372                         if (style->latextype == LATEX_ENVIRONMENT) break;
2373
2374                         if (style->labeltype == LABEL_MANUAL)
2375                                 item_name = "tag";
2376                         else
2377                                 item_name = "item";
2378
2379                         sgml::openTag(ofs, depth + 1, false, item_name);
2380                 }
2381                 break;
2382
2383                 default:
2384                         sgml::openTag(ofs, depth, false, style->latexname());
2385                         break;
2386                 }
2387
2388                 simpleLinuxDocOnePar(ofs, par, depth);
2389
2390                 par = par->next();
2391
2392                 ofs << "\n";
2393                 // write closing SGML tags
2394                 switch (style->latextype) {
2395                 case LATEX_COMMAND:
2396                         break;
2397                 case LATEX_ENVIRONMENT:
2398                 case LATEX_ITEM_ENVIRONMENT:
2399                         if (style->latexparam() == "CDATA")
2400                                 ofs << "]]>";
2401                         break;
2402                 default:
2403                         sgml::closeTag(ofs, depth, false, style->latexname());
2404                         break;
2405                 }
2406         }
2407
2408         // Close open tags
2409         for (int i = depth; i >= 0; --i)
2410                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
2411
2412         if (!body_only) {
2413                 ofs << "\n\n";
2414                 sgml::closeTag(ofs, 0, false, top_element);
2415         }
2416
2417         ofs.close();
2418         // How to check for successful close
2419
2420         // we want this to be true outside previews (for insetexternal)
2421         niceFile = true;
2422 }
2423
2424
2425 // checks, if newcol chars should be put into this line
2426 // writes newline, if necessary.
2427 namespace {
2428
2429 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2430                           string::size_type newcol)
2431 {
2432         colcount += newcol;
2433         if (colcount > lyxrc.ascii_linelen) {
2434                 os << "\n";
2435                 colcount = newcol; // assume write after this call
2436         }
2437 }
2438
2439 enum PAR_TAG {
2440         NONE=0,
2441         TT = 1,
2442         SF = 2,
2443         BF = 4,
2444         IT = 8,
2445         SL = 16,
2446         EM = 32
2447 };
2448
2449
2450 string tag_name(PAR_TAG const & pt) {
2451         switch (pt) {
2452         case NONE: return "!-- --";
2453         case TT: return "tt";
2454         case SF: return "sf";
2455         case BF: return "bf";
2456         case IT: return "it";
2457         case SL: return "sl";
2458         case EM: return "em";
2459         }
2460         return "";
2461 }
2462
2463
2464 inline
2465 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2466 {
2467         p1 = static_cast<PAR_TAG>(p1 | p2);
2468 }
2469
2470
2471 inline
2472 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2473 {
2474         p1 = static_cast<PAR_TAG>(p1 & ~p2);
2475 }
2476
2477 } // anon
2478
2479
2480 // Handle internal paragraph parsing -- layout already processed.
2481 void Buffer::simpleLinuxDocOnePar(ostream & os,
2482         Paragraph * par,
2483         Paragraph::depth_type /*depth*/)
2484 {
2485         LyXLayout_ptr const & style = par->layout();
2486
2487         string::size_type char_line_count = 5;     // Heuristic choice ;-)
2488
2489         // gets paragraph main font
2490         LyXFont font_old;
2491         bool desc_on;
2492         if (style->labeltype == LABEL_MANUAL) {
2493                 font_old = style->labelfont;
2494                 desc_on = true;
2495         } else {
2496                 font_old = style->font;
2497                 desc_on = false;
2498         }
2499
2500         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2501         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2502         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
2503         bool is_em = false;
2504
2505         stack<PAR_TAG> tag_state;
2506         // parsing main loop
2507         for (pos_type i = 0; i < par->size(); ++i) {
2508
2509                 PAR_TAG tag_close = NONE;
2510                 list < PAR_TAG > tag_open;
2511
2512                 LyXFont const font = par->getFont(params, i);
2513
2514                 if (font_old.family() != font.family()) {
2515                         switch (family_type) {
2516                         case LyXFont::SANS_FAMILY:
2517                                 tag_close |= SF;
2518                                 break;
2519                         case LyXFont::TYPEWRITER_FAMILY:
2520                                 tag_close |= TT;
2521                                 break;
2522                         default:
2523                                 break;
2524                         }
2525
2526                         family_type = font.family();
2527
2528                         switch (family_type) {
2529                         case LyXFont::SANS_FAMILY:
2530                                 tag_open.push_back(SF);
2531                                 break;
2532                         case LyXFont::TYPEWRITER_FAMILY:
2533                                 tag_open.push_back(TT);
2534                                 break;
2535                         default:
2536                                 break;
2537                         }
2538                 }
2539
2540                 if (font_old.series() != font.series()) {
2541                         switch (series_type) {
2542                         case LyXFont::BOLD_SERIES:
2543                                 tag_close |= BF;
2544                                 break;
2545                         default:
2546                                 break;
2547                         }
2548
2549                         series_type = font.series();
2550
2551                         switch (series_type) {
2552                         case LyXFont::BOLD_SERIES:
2553                                 tag_open.push_back(BF);
2554                                 break;
2555                         default:
2556                                 break;
2557                         }
2558
2559                 }
2560
2561                 if (font_old.shape() != font.shape()) {
2562                         switch (shape_type) {
2563                         case LyXFont::ITALIC_SHAPE:
2564                                 tag_close |= IT;
2565                                 break;
2566                         case LyXFont::SLANTED_SHAPE:
2567                                 tag_close |= SL;
2568                                 break;
2569                         default:
2570                                 break;
2571                         }
2572
2573                         shape_type = font.shape();
2574
2575                         switch (shape_type) {
2576                         case LyXFont::ITALIC_SHAPE:
2577                                 tag_open.push_back(IT);
2578                                 break;
2579                         case LyXFont::SLANTED_SHAPE:
2580                                 tag_open.push_back(SL);
2581                                 break;
2582                         default:
2583                                 break;
2584                         }
2585                 }
2586                 // handle <em> tag
2587                 if (font_old.emph() != font.emph()) {
2588                         if (font.emph() == LyXFont::ON) {
2589                                 tag_open.push_back(EM);
2590                                 is_em = true;
2591                         }
2592                         else if (is_em) {
2593                                 tag_close |= EM;
2594                                 is_em = false;
2595                         }
2596                 }
2597
2598                 list < PAR_TAG > temp;
2599                 while (!tag_state.empty() && tag_close) {
2600                         PAR_TAG k =  tag_state.top();
2601                         tag_state.pop();
2602                         os << "</" << tag_name(k) << '>';
2603                         if (tag_close & k)
2604                                 reset(tag_close,k);
2605                         else
2606                                 temp.push_back(k);
2607                 }
2608
2609                 for(list< PAR_TAG >::const_iterator j = temp.begin();
2610                     j != temp.end(); ++j) {
2611                         tag_state.push(*j);
2612                         os << '<' << tag_name(*j) << '>';
2613                 }
2614
2615                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2616                     j != tag_open.end(); ++j) {
2617                         tag_state.push(*j);
2618                         os << '<' << tag_name(*j) << '>';
2619                 }
2620
2621                 char c = par->getChar(i);
2622
2623                 if (c == Paragraph::META_INSET) {
2624                         Inset * inset = par->getInset(i);
2625                         inset->linuxdoc(this, os);
2626                         font_old = font;
2627                         continue;
2628                 }
2629
2630                 if (style->latexparam() == "CDATA") {
2631                         // "TeX"-Mode on == > SGML-Mode on.
2632                         if (c != '\0')
2633                                 os << c;
2634                         ++char_line_count;
2635                 } else {
2636                         bool ws;
2637                         string str;
2638                         boost::tie(ws, str) = sgml::escapeChar(c);
2639                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2640                                 // in freespacing mode, spaces are
2641                                 // non-breaking characters
2642                                 if (desc_on) {// if char is ' ' then...
2643
2644                                         ++char_line_count;
2645                                         sgmlLineBreak(os, char_line_count, 6);
2646                                         os << "</tag>";
2647                                         desc_on = false;
2648                                 } else  {
2649                                         sgmlLineBreak(os, char_line_count, 1);
2650                                         os << c;
2651                                 }
2652                         } else {
2653                                 os << str;
2654                                 char_line_count += str.length();
2655                         }
2656                 }
2657                 font_old = font;
2658         }
2659
2660         while (!tag_state.empty()) {
2661                 os << "</" << tag_name(tag_state.top()) << '>';
2662                 tag_state.pop();
2663         }
2664
2665         // resets description flag correctly
2666         if (desc_on) {
2667                 // <tag> not closed...
2668                 sgmlLineBreak(os, char_line_count, 6);
2669                 os << "</tag>";
2670         }
2671 }
2672
2673
2674 // Print an error message.
2675 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2676         string const & /*message*/) const
2677 {
2678 #ifdef WITH_WARNINGS
2679 #warning This is wrong we cannot insert an inset like this!!!
2680         // I guess this was Jose' so I explain you more or less why this
2681         // is wrong. This way you insert something in the paragraph and
2682         // don't tell it to LyXText (row rebreaking and undo handling!!!)
2683         // I deactivate this code, have a look at BufferView::insertErrors
2684         // how you should do this correctly! (Jug 20020315)
2685 #endif
2686 #if 0
2687         // insert an error marker in text
2688         InsetError * new_inset = new InsetError(message);
2689         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2690                          params.language));
2691 #endif
2692 }
2693
2694
2695 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2696 {
2697         ofstream ofs(fname.c_str());
2698         if (!ofs) {
2699                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2700                 return;
2701         }
2702
2703         Paragraph * par = &*(paragraphs.begin());
2704
2705         niceFile = nice; // this will be used by Insetincludes.
2706
2707         LaTeXFeatures features(params);
2708         validate(features);
2709
2710         texrow.reset();
2711
2712         LyXTextClass const & tclass = params.getLyXTextClass();
2713         string top_element = tclass.latexname();
2714
2715         if (!only_body) {
2716                 ofs << "<!DOCTYPE " << top_element
2717                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2718
2719                 string preamble = params.preamble;
2720                 const string name = nice ? ChangeExtension(filename_, ".sgml")
2721                          : fname;
2722                 preamble += features.getIncludedFiles(name);
2723                 preamble += features.getLyXSGMLEntities();
2724
2725                 if (!preamble.empty()) {
2726                         ofs << "\n [ " << preamble << " ]";
2727                 }
2728                 ofs << ">\n\n";
2729         }
2730
2731         string top = top_element;
2732         top += " lang=\"";
2733         top += params.language->code();
2734         top += '"';
2735
2736         if (!params.options.empty()) {
2737                 top += ' ';
2738                 top += params.options;
2739         }
2740         sgml::openTag(ofs, 0, false, top);
2741
2742         ofs << "<!-- DocBook file was created by " << lyx_docversion
2743             << "\n  See http://www.lyx.org/ for more information -->\n";
2744
2745         vector<string> environment_stack(10);
2746         vector<string> environment_inner(10);
2747         vector<string> command_stack(10);
2748
2749         bool command_flag = false;
2750         Paragraph::depth_type command_depth = 0;
2751         Paragraph::depth_type command_base = 0;
2752         Paragraph::depth_type cmd_depth = 0;
2753         Paragraph::depth_type depth = 0; // paragraph depth
2754
2755         string item_name;
2756         string command_name;
2757
2758         while (par) {
2759                 string sgmlparam;
2760                 string c_depth;
2761                 string c_params;
2762                 int desc_on = 0; // description mode
2763
2764                 LyXLayout_ptr const & style = par->layout();
2765
2766                 // environment tag closing
2767                 for (; depth > par->params().depth(); --depth) {
2768                         if (environment_inner[depth] != "!-- --") {
2769                                 item_name = "listitem";
2770                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2771                                 if (environment_inner[depth] == "varlistentry")
2772                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
2773                         }
2774                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2775                         environment_stack[depth].erase();
2776                         environment_inner[depth].erase();
2777                 }
2778
2779                 if (depth == par->params().depth()
2780                    && environment_stack[depth] != style->latexname()
2781                    && !environment_stack[depth].empty()) {
2782                         if (environment_inner[depth] != "!-- --") {
2783                                 item_name= "listitem";
2784                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
2785                                 if (environment_inner[depth] == "varlistentry")
2786                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2787                         }
2788
2789                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2790
2791                         environment_stack[depth].erase();
2792                         environment_inner[depth].erase();
2793                 }
2794
2795                 // Write opening SGML tags.
2796                 switch (style->latextype) {
2797                 case LATEX_PARAGRAPH:
2798                         sgml::openTag(ofs, depth + command_depth,
2799                                     false, style->latexname());
2800                         break;
2801
2802                 case LATEX_COMMAND:
2803                         if (depth != 0)
2804                                 sgmlError(par, 0,
2805                                           _("Error : Wrong depth for "
2806                                             "LatexType Command.\n"));
2807
2808                         command_name = style->latexname();
2809
2810                         sgmlparam = style->latexparam();
2811                         c_params = split(sgmlparam, c_depth,'|');
2812
2813                         cmd_depth = lyx::atoi(c_depth);
2814
2815                         if (command_flag) {
2816                                 if (cmd_depth < command_base) {
2817                                         for (Paragraph::depth_type j = command_depth;
2818                                              j >= command_base; --j) {
2819                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
2820                                                 ofs << endl;
2821                                         }
2822                                         command_depth = command_base = cmd_depth;
2823                                 } else if (cmd_depth <= command_depth) {
2824                                         for (int j = command_depth;
2825                                              j >= int(cmd_depth); --j) {
2826                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
2827                                                 ofs << endl;
2828                                         }
2829                                         command_depth = cmd_depth;
2830                                 } else
2831                                         command_depth = cmd_depth;
2832                         } else {
2833                                 command_depth = command_base = cmd_depth;
2834                                 command_flag = true;
2835                         }
2836                         if (command_stack.size() == command_depth + 1)
2837                                 command_stack.push_back(string());
2838                         command_stack[command_depth] = command_name;
2839
2840                         // treat label as a special case for
2841                         // more WYSIWYM handling.
2842                         // This is a hack while paragraphs can't have
2843                         // attributes, like id in this case.
2844                         if (par->isInset(0)) {
2845                                 Inset * inset = par->getInset(0);
2846                                 Inset::Code lyx_code = inset->lyxCode();
2847                                 if (lyx_code == Inset::LABEL_CODE) {
2848                                         command_name += " id=\"";
2849                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
2850                                         command_name += '"';
2851                                         desc_on = 3;
2852                                 }
2853                         }
2854
2855                         sgml::openTag(ofs, depth + command_depth, false, command_name);
2856
2857                         item_name = c_params.empty() ? "title" : c_params;
2858                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
2859                         break;
2860
2861                 case LATEX_ENVIRONMENT:
2862                 case LATEX_ITEM_ENVIRONMENT:
2863                         if (depth < par->params().depth()) {
2864                                 depth = par->params().depth();
2865                                 environment_stack[depth].erase();
2866                         }
2867
2868                         if (environment_stack[depth] != style->latexname()) {
2869                                 if (environment_stack.size() == depth + 1) {
2870                                         environment_stack.push_back("!-- --");
2871                                         environment_inner.push_back("!-- --");
2872                                 }
2873                                 environment_stack[depth] = style->latexname();
2874                                 environment_inner[depth] = "!-- --";
2875                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
2876                         } else {
2877                                 if (environment_inner[depth] != "!-- --") {
2878                                         item_name= "listitem";
2879                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
2880                                         if (environment_inner[depth] == "varlistentry")
2881                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2882                                 }
2883                         }
2884
2885                         if (style->latextype == LATEX_ENVIRONMENT) {
2886                                 if (!style->latexparam().empty()) {
2887                                         if (style->latexparam() == "CDATA")
2888                                                 ofs << "<![CDATA[";
2889                                         else
2890                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
2891                                 }
2892                                 break;
2893                         }
2894
2895                         desc_on = (style->labeltype == LABEL_MANUAL);
2896
2897                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2898                         sgml::openTag(ofs, depth + 1 + command_depth,
2899                                     false, environment_inner[depth]);
2900
2901                         item_name = desc_on ? "term" : "para";
2902                         sgml::openTag(ofs, depth + 1 + command_depth,
2903                                     false, item_name);
2904                         break;
2905                 default:
2906                         sgml::openTag(ofs, depth + command_depth,
2907                                     false, style->latexname());
2908                         break;
2909                 }
2910
2911                 simpleDocBookOnePar(ofs, par, desc_on,
2912                                     depth + 1 + command_depth);
2913                 par = par->next();
2914
2915                 string end_tag;
2916                 // write closing SGML tags
2917                 switch (style->latextype) {
2918                 case LATEX_COMMAND:
2919                         end_tag = c_params.empty() ? "title" : c_params;
2920                         sgml::closeTag(ofs, depth + command_depth,
2921                                      false, end_tag);
2922                         break;
2923                 case LATEX_ENVIRONMENT:
2924                         if (!style->latexparam().empty()) {
2925                                 if (style->latexparam() == "CDATA")
2926                                         ofs << "]]>";
2927                                 else
2928                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
2929                         }
2930                         break;
2931                 case LATEX_ITEM_ENVIRONMENT:
2932                         if (desc_on == 1) break;
2933                         end_tag = "para";
2934                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
2935                         break;
2936                 case LATEX_PARAGRAPH:
2937                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2938                         break;
2939                 default:
2940                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2941                         break;
2942                 }
2943         }
2944
2945         // Close open tags
2946         for (int d = depth; d >= 0; --d) {
2947                 if (!environment_stack[depth].empty()) {
2948                         if (environment_inner[depth] != "!-- --") {
2949                                 item_name = "listitem";
2950                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2951                                if (environment_inner[depth] == "varlistentry")
2952                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2953                         }
2954
2955                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2956                 }
2957         }
2958
2959         for (int j = command_depth; j >= 0 ; --j)
2960                 if (!command_stack[j].empty()) {
2961                         sgml::closeTag(ofs, j, false, command_stack[j]);
2962                         ofs << endl;
2963                 }
2964
2965         ofs << "\n\n";
2966         sgml::closeTag(ofs, 0, false, top_element);
2967
2968         ofs.close();
2969         // How to check for successful close
2970
2971         // we want this to be true outside previews (for insetexternal)
2972         niceFile = true;
2973 }
2974
2975
2976 void Buffer::simpleDocBookOnePar(ostream & os,
2977                                  Paragraph * par, int & desc_on,
2978                                  Paragraph::depth_type depth) const
2979 {
2980         bool emph_flag = false;
2981
2982         LyXLayout_ptr const & style = par->layout();
2983
2984         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2985
2986         int char_line_count = depth;
2987         //if (!style.free_spacing)
2988         //      os << string(depth,' ');
2989
2990         // parsing main loop
2991         for (pos_type i = 0; i < par->size(); ++i) {
2992                 LyXFont font = par->getFont(params, i);
2993
2994                 // handle <emphasis> tag
2995                 if (font_old.emph() != font.emph()) {
2996                         if (font.emph() == LyXFont::ON) {
2997                                 if (style->latexparam() == "CDATA")
2998                                         os << "]]>";
2999                                 os << "<emphasis>";
3000                                 if (style->latexparam() == "CDATA")
3001                                         os << "<![CDATA[";
3002                                 emph_flag = true;
3003                         } else if (i) {
3004                                 if (style->latexparam() == "CDATA")
3005                                         os << "]]>";
3006                                 os << "</emphasis>";
3007                                 if (style->latexparam() == "CDATA")
3008                                         os << "<![CDATA[";
3009                                 emph_flag = false;
3010                         }
3011                 }
3012
3013
3014                 if (par->isInset(i)) {
3015                         Inset * inset = par->getInset(i);
3016                         // don't print the inset in position 0 if desc_on == 3 (label)
3017                         if (i || desc_on != 3) {
3018                                 if (style->latexparam() == "CDATA")
3019                                         os << "]]>";
3020                                 inset->docbook(this, os, false);
3021                                 if (style->latexparam() == "CDATA")
3022                                         os << "<![CDATA[";
3023                         }
3024                 } else {
3025                         char c = par->getChar(i);
3026                         bool ws;
3027                         string str;
3028                         boost::tie(ws, str) = sgml::escapeChar(c);
3029
3030                         if (style->pass_thru) {
3031                                 os << c;
3032                         } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
3033                                         os << str;
3034                         } else if (desc_on ==1) {
3035                                 ++char_line_count;
3036                                 os << "\n</term><listitem><para>";
3037                                 desc_on = 2;
3038                         } else {
3039                                 os << ' ';
3040                         }
3041                 }
3042                 font_old = font;
3043         }
3044
3045         if (emph_flag) {
3046                 if (style->latexparam() == "CDATA")
3047                         os << "]]>";
3048                 os << "</emphasis>";
3049                 if (style->latexparam() == "CDATA")
3050                         os << "<![CDATA[";
3051         }
3052
3053         // resets description flag correctly
3054         if (desc_on == 1) {
3055                 // <term> not closed...
3056                 os << "</term>\n<listitem><para>&nbsp;</para>";
3057         }
3058         if (style->free_spacing)
3059                 os << '\n';
3060 }
3061
3062
3063 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3064 // Other flags: -wall -v0 -x
3065 int Buffer::runChktex()
3066 {
3067         if (!users->text) return 0;
3068
3069         users->owner()->prohibitInput();
3070
3071         // get LaTeX-Filename
3072         string const name = getLatexName();
3073         string path = filePath();
3074
3075         string const org_path = path;
3076         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3077                 path = tmppath;
3078         }
3079
3080         Path p(path); // path to LaTeX file
3081         users->owner()->message(_("Running chktex..."));
3082
3083         // Remove all error insets
3084         bool const removedErrorInsets = users->removeAutoInsets();
3085
3086         // Generate the LaTeX file if neccessary
3087         makeLaTeXFile(name, org_path, false);
3088
3089         TeXErrors terr;
3090         Chktex chktex(lyxrc.chktex_command, name, filePath());
3091         int res = chktex.run(terr); // run chktex
3092
3093         if (res == -1) {
3094                 Alert::alert(_("chktex did not work!"),
3095                            _("Could not run with file:"), name);
3096         } else if (res > 0) {
3097                 // Insert all errors as errors boxes
3098                 users->insertErrors(terr);
3099         }
3100
3101         // if we removed error insets before we ran chktex or if we inserted
3102         // error insets after we ran chktex, this must be run:
3103         if (removedErrorInsets || res) {
3104 #warning repaint needed here, or do you mean update() ?
3105                 users->repaint();
3106                 users->fitCursor();
3107         }
3108         users->owner()->allowInput();
3109
3110         return res;
3111 }
3112
3113
3114 void Buffer::validate(LaTeXFeatures & features) const
3115 {
3116         LyXTextClass const & tclass = params.getLyXTextClass();
3117
3118         // AMS Style is at document level
3119         if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3120                 features.require("amsmath");
3121
3122         for_each(paragraphs.begin(), paragraphs.end(),
3123                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
3124
3125         // the bullet shapes are buffer level not paragraph level
3126         // so they are tested here
3127         for (int i = 0; i < 4; ++i) {
3128                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3129                         int const font = params.user_defined_bullets[i].getFont();
3130                         if (font == 0) {
3131                                 int const c = params
3132                                         .user_defined_bullets[i]
3133                                         .getCharacter();
3134                                 if (c == 16
3135                                    || c == 17
3136                                    || c == 25
3137                                    || c == 26
3138                                    || c == 31) {
3139                                         features.require("latexsym");
3140                                 }
3141                         } else if (font == 1) {
3142                                 features.require("amssymb");
3143                         } else if ((font >= 2 && font <= 5)) {
3144                                 features.require("pifont");
3145                         }
3146                 }
3147         }
3148
3149         if (lyxerr.debugging(Debug::LATEX)) {
3150                 features.showStruct();
3151         }
3152 }
3153
3154
3155 vector<string> const Buffer::getLabelList() const
3156 {
3157         /// if this is a child document and the parent is already loaded
3158         /// Use the parent's list instead  [ale990407]
3159         if (!params.parentname.empty()
3160             && bufferlist.exists(params.parentname)) {
3161                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3162                 if (tmp)
3163                         return tmp->getLabelList();
3164         }
3165
3166         vector<string> label_list;
3167         for (inset_iterator it = inset_const_iterator_begin();
3168              it != inset_const_iterator_end(); ++it) {
3169                 vector<string> const l = it->getLabelList();
3170                 label_list.insert(label_list.end(), l.begin(), l.end());
3171         }
3172         return label_list;
3173 }
3174
3175
3176 // This is also a buffer property (ale)
3177 vector<pair<string, string> > const Buffer::getBibkeyList() const
3178 {
3179         typedef pair<string, string> StringPair;
3180         /// if this is a child document and the parent is already loaded
3181         /// Use the parent's list instead  [ale990412]
3182         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3183                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3184                 if (tmp)
3185                         return tmp->getBibkeyList();
3186         }
3187
3188         vector<StringPair> keys;
3189         ParagraphList::iterator pit = paragraphs.begin();
3190         ParagraphList::iterator pend = paragraphs.end();
3191         for (; pit != pend; ++pit) {
3192                 if (pit->bibkey) {
3193                         string const key = pit->bibkey->getContents();
3194                         string const opt = pit->bibkey->getOptions();
3195                         string const ref = pit->asString(this, false);
3196                         string const info = opt + "TheBibliographyRef" + ref;
3197
3198                         keys.push_back(StringPair(key, info));
3199                 }
3200         }
3201
3202         if (!keys.empty())
3203                 return keys;
3204
3205         // Might be either using bibtex or a child has bibliography
3206         for (inset_iterator it = inset_const_iterator_begin();
3207                 it != inset_const_iterator_end(); ++it) {
3208                 // Search for Bibtex or Include inset
3209                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
3210                         vector<StringPair> tmp =
3211                                 static_cast<InsetBibtex &>(*it).getKeys(this);
3212                         keys.insert(keys.end(), tmp.begin(), tmp.end());
3213                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
3214                         vector<StringPair> const tmp =
3215                                 static_cast<InsetInclude &>(*it).getKeys();
3216                         keys.insert(keys.end(), tmp.begin(), tmp.end());
3217                 }
3218         }
3219
3220         return keys;
3221 }
3222
3223
3224 bool Buffer::isDepClean(string const & name) const
3225 {
3226         DEPCLEAN * item = dep_clean;
3227         while (item && item->master != name)
3228                 item = item->next;
3229         if (!item) return true;
3230         return item->clean;
3231 }
3232
3233
3234 void Buffer::markDepClean(string const & name)
3235 {
3236         if (!dep_clean) {
3237                 dep_clean = new DEPCLEAN;
3238                 dep_clean->clean = true;
3239                 dep_clean->master = name;
3240                 dep_clean->next = 0;
3241         } else {
3242                 DEPCLEAN * item = dep_clean;
3243                 while (item && item->master != name)
3244                         item = item->next;
3245                 if (item) {
3246                         item->clean = true;
3247                 } else {
3248                         item = new DEPCLEAN;
3249                         item->clean = true;
3250                         item->master = name;
3251                         item->next = 0;
3252                 }
3253         }
3254 }
3255
3256
3257 bool Buffer::dispatch(string const & command, bool * result)
3258 {
3259         // Split command string into command and argument
3260         string cmd;
3261         string line = ltrim(command);
3262         string const arg = trim(split(line, cmd, ' '));
3263
3264         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
3265 }
3266
3267
3268 bool Buffer::dispatch(int action, string const & argument, bool * result)
3269 {
3270         bool dispatched = true;
3271
3272         switch (action) {
3273                 case LFUN_EXPORT: {
3274                         bool const tmp = Exporter::Export(this, argument, false);
3275                         if (result)
3276                                 *result = tmp;
3277                         break;
3278                 }
3279
3280                 default:
3281                         dispatched = false;
3282         }
3283         return dispatched;
3284 }
3285
3286
3287 void Buffer::resizeInsets(BufferView * bv)
3288 {
3289         /// then remove all LyXText in text-insets
3290         for_each(paragraphs.begin(), paragraphs.end(),
3291                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
3292 }
3293
3294
3295 void Buffer::redraw()
3296 {
3297 #warning repaint needed here, or do you mean update() ?
3298         users->repaint();
3299         users->fitCursor();
3300 }
3301
3302
3303 void Buffer::changeLanguage(Language const * from, Language const * to)
3304 {
3305
3306         ParIterator end = par_iterator_end();
3307         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3308                 (*it)->changeLanguage(params, from, to);
3309 }
3310
3311
3312 bool Buffer::isMultiLingual()
3313 {
3314         ParIterator end = par_iterator_end();
3315         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3316                 if ((*it)->isMultiLingual(params))
3317                         return true;
3318
3319         return false;
3320 }
3321
3322
3323 void Buffer::inset_iterator::setParagraph()
3324 {
3325         while (pit != pend) {
3326                 it = pit->insetlist.begin();
3327                 if (it != pit->insetlist.end())
3328                         return;
3329                 ++pit;
3330         }
3331 }
3332
3333
3334 Inset * Buffer::getInsetFromID(int id_arg) const
3335 {
3336         for (inset_iterator it = inset_const_iterator_begin();
3337                  it != inset_const_iterator_end(); ++it)
3338         {
3339                 if (it->id() == id_arg)
3340                         return &(*it);
3341                 Inset * in = it->getInsetFromID(id_arg);
3342                 if (in)
3343                         return in;
3344         }
3345         return 0;
3346 }
3347
3348
3349 Paragraph * Buffer::getParFromID(int id) const
3350 {
3351         if (id < 0)
3352                 return 0;
3353
3354         ParagraphList::iterator it = paragraphs.begin();
3355         ParagraphList::iterator end = paragraphs.end();
3356         for (; it != end; ++it) {
3357                 if (it->id() == id) {
3358                         return &*it;
3359                 }
3360                 Paragraph * tmp = it->getParFromID(id);
3361                 if (tmp) {
3362                         return tmp;
3363                 }
3364         }
3365         return 0;
3366 }
3367
3368
3369 ParIterator Buffer::par_iterator_begin()
3370 {
3371         return ParIterator(&*(paragraphs.begin()));
3372 }
3373
3374
3375 ParIterator Buffer::par_iterator_end()
3376 {
3377         return ParIterator();
3378 }
3379
3380 ParConstIterator Buffer::par_iterator_begin() const
3381 {
3382         return ParConstIterator(&*(paragraphs.begin()));
3383 }
3384
3385
3386 ParConstIterator Buffer::par_iterator_end() const
3387 {
3388         return ParConstIterator();
3389 }
3390
3391
3392
3393 void Buffer::addUser(BufferView * u)
3394 {
3395         users = u;
3396 }
3397
3398
3399 void Buffer::delUser(BufferView *)
3400 {
3401         users = 0;
3402 }
3403
3404
3405 Language const * Buffer::getLanguage() const
3406 {
3407         return params.language;
3408 }
3409
3410
3411 bool Buffer::isClean() const
3412 {
3413         return lyx_clean;
3414 }
3415
3416
3417 bool Buffer::isBakClean() const
3418 {
3419         return bak_clean;
3420 }
3421
3422
3423 void Buffer::markClean() const
3424 {
3425         if (!lyx_clean) {
3426                 lyx_clean = true;
3427                 updateTitles();
3428         }
3429         // if the .lyx file has been saved, we don't need an
3430         // autosave
3431         bak_clean = true;
3432 }
3433
3434
3435 void Buffer::markBakClean()
3436 {
3437         bak_clean = true;
3438 }
3439
3440
3441 void Buffer::setUnnamed(bool flag)
3442 {
3443         unnamed = flag;
3444 }
3445
3446
3447 bool Buffer::isUnnamed()
3448 {
3449         return unnamed;
3450 }
3451
3452
3453 void Buffer::markDirty()
3454 {
3455         if (lyx_clean) {
3456                 lyx_clean = false;
3457                 updateTitles();
3458         }
3459         bak_clean = false;
3460         DEPCLEAN * tmp = dep_clean;
3461         while (tmp) {
3462                 tmp->clean = false;
3463                 tmp = tmp->next;
3464         }
3465 }
3466
3467
3468 string const & Buffer::fileName() const
3469 {
3470         return filename_;
3471 }
3472
3473
3474 string const & Buffer::filePath() const
3475 {
3476         return filepath_;
3477 }
3478
3479
3480 bool Buffer::isReadonly() const
3481 {
3482         return read_only;
3483 }
3484
3485
3486 BufferView * Buffer::getUser() const
3487 {
3488         return users;
3489 }
3490
3491
3492 void Buffer::setParentName(string const & name)
3493 {
3494         params.parentname = name;
3495 }
3496
3497
3498 Buffer::inset_iterator::inset_iterator()
3499         : pit(0), pend(0)
3500 {}
3501
3502
3503 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
3504         : pit(p), pend(e)
3505 {
3506         setParagraph();
3507 }
3508
3509
3510 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
3511 {
3512         if (pit != pend) {
3513                 ++it;
3514                 if (it == pit->insetlist.end()) {
3515                         ++pit;
3516                         setParagraph();
3517                 }
3518         }
3519         return *this;
3520 }
3521
3522
3523 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
3524 {
3525         inset_iterator tmp = *this;
3526         ++*this;
3527         return tmp;
3528 }
3529
3530
3531 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
3532 {
3533         return *it.getInset();
3534 }
3535
3536
3537 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
3538 {
3539         return it.getInset();
3540 }
3541
3542
3543 Paragraph * Buffer::inset_iterator::getPar()
3544 {
3545         return &(*pit);
3546 }
3547
3548
3549 lyx::pos_type Buffer::inset_iterator::getPos() const
3550 {
3551         return it.getPos();
3552 }
3553
3554
3555 bool operator==(Buffer::inset_iterator const & iter1,
3556                 Buffer::inset_iterator const & iter2)
3557 {
3558         return iter1.pit == iter2.pit
3559                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
3560 }
3561
3562
3563 bool operator!=(Buffer::inset_iterator const & iter1,
3564                 Buffer::inset_iterator const & iter2)
3565 {
3566         return !(iter1 == iter2);
3567 }