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