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