]> git.lyx.org Git - lyx.git/blob - src/buffer.C
zlib stuff
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14 #include "buffer_funcs.h"
15 #include "bufferlist.h"
16 #include "LyXAction.h"
17 #include "lyxrc.h"
18 #include "lyxlex.h"
19 #include "tex-strings.h"
20 #include "layout.h"
21 #include "bufferview_funcs.h"
22 #include "lyxfont.h"
23 #include "version.h"
24 #include "LaTeX.h"
25 #include "Chktex.h"
26 #include "debug.h"
27 #include "LaTeXFeatures.h"
28 #include "lyxtext.h"
29 #include "gettext.h"
30 #include "language.h"
31 #include "exporter.h"
32 #include "errorlist.h"
33 #include "Lsstream.h"
34 #include "format.h"
35 #include "ParagraphParameters.h"
36 #include "iterators.h"
37 #include "lyxtextclasslist.h"
38 #include "sgml.h"
39 #include "paragraph_funcs.h"
40 #include "messages.h"
41 #include "author.h"
42
43 #include "frontends/LyXView.h"
44
45 #include "mathed/formulamacro.h"
46 #include "mathed/formula.h"
47
48 #include "insets/insetbibitem.h"
49 #include "insets/insetbibtex.h"
50 #include "insets/insetinclude.h"
51 #include "insets/insettext.h"
52
53 #include "frontends/Dialogs.h"
54 #include "frontends/Alert.h"
55
56 #include "graphics/Previews.h"
57
58 #include "support/LAssert.h"
59 #include "support/textutils.h"
60 #include "support/filetools.h"
61 #include "support/path.h"
62 #include "support/os.h"
63 #include "support/tostr.h"
64 #include "support/lyxlib.h"
65 #include "support/FileInfo.h"
66 #include "support/lyxmanip.h"
67 #include "support/lyxtime.h"
68 #include "support/gzstream.h"
69
70 #include <boost/bind.hpp>
71 #include <boost/tuple/tuple.hpp>
72
73 #include <fstream>
74 #include <iomanip>
75 #include <map>
76 #include <stack>
77 #include <list>
78 #include <algorithm>
79
80 #include <cstdlib>
81 #include <cmath>
82 #include <unistd.h>
83 #include <sys/types.h>
84 #include <utime.h>
85
86 #ifdef HAVE_LOCALE
87 #include <locale>
88 #endif
89
90 using namespace lyx::support;
91
92 #ifndef CXX_GLOBAL_CSTD
93 using std::pow;
94 #endif
95
96 using std::ostream;
97 using std::ofstream;
98 using std::ifstream;
99 using std::fstream;
100 using std::ios;
101 using std::setw;
102 using std::endl;
103 using std::pair;
104 using std::make_pair;
105 using std::vector;
106 using std::map;
107 using std::stack;
108 using std::list;
109 using std::for_each;
110
111 using lyx::pos_type;
112 using lyx::textclass_type;
113
114 // all these externs should eventually be removed.
115 extern BufferList bufferlist;
116
117 namespace {
118
119 const int LYX_FORMAT = 225;
120
121 bool openFileWrite(ofstream & ofs, string const & fname)
122 {
123         ofs.open(fname.c_str());
124         if (!ofs) {
125                 string const file = MakeDisplayPath(fname, 50);
126                 string text = bformat(_("Could not open the specified "
127                                         "document\n%1$s."), file);
128                 Alert::error(_("Could not open file"), text);
129                 return false;
130         }
131         return true;
132 }
133
134
135 } // namespace anon
136
137 Buffer::Buffer(string const & file, bool ronly)
138         : niceFile(true), lyx_clean(true), bak_clean(true),
139           unnamed(false), read_only(ronly),
140           filename_(file)
141 {
142         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
143         filepath_ = OnlyPath(file);
144         lyxvc.buffer(this);
145         if (read_only || lyxrc.use_tempdir) {
146                 tmppath = CreateBufferTmpDir();
147         } else {
148                 tmppath.erase();
149         }
150
151         // set initial author
152         authors().record(Author(lyxrc.user_name, lyxrc.user_email));
153 }
154
155
156 Buffer::~Buffer()
157 {
158         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
159         // here the buffer should take care that it is
160         // saved properly, before it goes into the void.
161
162         closing();
163
164         if (!tmppath.empty() && destroyDir(tmppath) != 0) {
165                 Alert::warning(_("Could not remove temporary directory"),
166                         bformat(_("Could not remove the temporary directory %1$s"), tmppath));
167         }
168
169         paragraphs.clear();
170
171         // Remove any previewed LaTeX snippets assocoated with this buffer.
172         lyx::graphics::Previews::get().removeLoader(this);
173 }
174
175
176 string const Buffer::getLatexName(bool no_path) const
177 {
178         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
179         return no_path ? OnlyFilename(name) : name;
180 }
181
182
183 pair<Buffer::LogType, string> const Buffer::getLogName() const
184 {
185         string const filename = getLatexName(false);
186
187         if (filename.empty())
188                 return make_pair(Buffer::latexlog, string());
189
190         string path = OnlyPath(filename);
191
192         if (lyxrc.use_tempdir || !IsDirWriteable(path))
193                 path = tmppath;
194
195         string const fname = AddName(path,
196                                      OnlyFilename(ChangeExtension(filename,
197                                                                   ".log")));
198         string const bname =
199                 AddName(path, OnlyFilename(
200                         ChangeExtension(filename,
201                                         formats.extension("literate") + ".out")));
202
203         // If no Latex log or Build log is newer, show Build log
204
205         FileInfo const f_fi(fname);
206         FileInfo const b_fi(bname);
207
208         if (b_fi.exist() &&
209             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
210                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
211                 return make_pair(Buffer::buildlog, bname);
212         }
213         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
214         return make_pair(Buffer::latexlog, fname);
215 }
216
217
218 void Buffer::setReadonly(bool flag)
219 {
220         if (read_only != flag) {
221                 read_only = flag;
222                 readonly(flag);
223         }
224 }
225
226
227 AuthorList & Buffer::authors()
228 {
229         return params.authorlist;
230 }
231
232
233 void Buffer::setFileName(string const & newfile)
234 {
235         filename_ = MakeAbsPath(newfile);
236         filepath_ = OnlyPath(filename_);
237         setReadonly(IsFileWriteable(filename_) == 0);
238         updateTitles();
239 }
240
241
242 // We'll remove this later. (Lgb)
243 namespace {
244
245 void unknownClass(string const & unknown)
246 {
247         Alert::warning(_("Unknown document class"),
248                 bformat(_("Using the default document class, because the "
249                         " class %1$s is unknown."), unknown));
250 }
251
252 } // anon
253
254 int Buffer::readHeader(LyXLex & lex)
255 {
256         int unknown_tokens = 0;
257
258         while (lex.isOK()) {
259                 lex.nextToken();
260                 string const token = lex.getString();
261
262                 if (token.empty())
263                         continue;
264
265                 if (token == "\\end_header")
266                         break;
267
268                 lyxerr[Debug::PARSER] << "Handling header token: `"
269                                       << token << '\'' << endl;
270
271
272                 string unknown = params.readToken(lex, token);
273                 if (!unknown.empty()) {
274                         if (unknown[0] != '\\') {
275                                 unknownClass(unknown);
276                         } else {
277                                 ++unknown_tokens;
278                                 string const s = bformat(_("Unknown token: "
279                                                            "%1$s %2$s\n"),
280                                                          token,
281                                                          lex.getString());
282                                 error(ErrorItem(_("Header error"), s,
283                                                 -1, 0, 0));
284                         }
285                 }
286         }
287         return unknown_tokens;
288 }
289
290
291 // candidate for move to BufferView
292 // (at least some parts in the beginning of the func)
293 //
294 // Uwe C. Schroeder
295 // changed to be public and have one parameter
296 // if par = 0 normal behavior
297 // else insert behavior
298 // Returns false if "\the_end" is not read (Asger)
299 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
300 {
301         Paragraph::depth_type depth = 0;
302         bool the_end_read = false;
303
304         if (paragraphs.empty()) {
305                 readHeader(lex);
306                 if (!params.getLyXTextClass().load()) {
307                         string theclass = params.getLyXTextClass().name();
308                         Alert::error(_("Can't load document class"), bformat(
309                                         "Using the default document class, because the "
310                                         " class %1$s could not be loaded.", theclass));
311                         params.textclass = 0;
312                 }
313         } else {
314                 // We don't want to adopt the parameters from the
315                 // document we insert, so read them into a temporary buffer
316                 // and then discard it
317
318                 Buffer tmpbuf("", false);
319                 tmpbuf.readHeader(lex);
320         }
321
322         while (lex.isOK()) {
323                 lex.nextToken();
324                 string const token = lex.getString();
325
326                 if (token.empty())
327                         continue;
328
329                 lyxerr[Debug::PARSER] << "Handling token: `"
330                                       << token << '\'' << endl;
331
332                 if (token == "\\the_end") {
333                         the_end_read = true;
334                         continue;
335                 }
336
337                 readParagraph(lex, token, paragraphs, pit, depth);
338         }
339
340         return the_end_read;
341 }
342
343
344 int Buffer::readParagraph(LyXLex & lex, string const & token,
345                           ParagraphList & pars, ParagraphList::iterator & pit,
346                           Paragraph::depth_type & depth)
347 {
348         static Change current_change;
349         int unknown = 0;
350
351         if (token == "\\layout") {
352                 lex.pushToken(token);
353
354                 Paragraph par;
355                 par.params().depth(depth);
356                 if (params.tracking_changes)
357                         par.trackChanges();
358                 LyXFont f(LyXFont::ALL_INHERIT, params.language);
359                 par.setFont(0, f);
360
361                 // insert after
362                 if (pit != pars.end())
363                         ++pit;
364
365                 pit = pars.insert(pit, par);
366
367                 // FIXME: goddamn InsetTabular makes us pass a Buffer
368                 // not BufferParams
369                 ::readParagraph(*this, *pit, lex);
370
371         } else if (token == "\\begin_deeper") {
372                 ++depth;
373         } else if (token == "\\end_deeper") {
374                 if (!depth) {
375                         lex.printError("\\end_deeper: " "depth is already null");
376                 } else {
377                         --depth;
378                 }
379         } else {
380                 ++unknown;
381         }
382         return unknown;
383 }
384
385
386 // needed to insert the selection
387 void Buffer::insertStringAsLines(ParagraphList::iterator & par, pos_type & pos,
388                                  LyXFont const & fn,string const & str)
389 {
390         LyXLayout_ptr const & layout = par->layout();
391
392         LyXFont font = fn;
393
394         par->checkInsertChar(font);
395         // insert the string, don't insert doublespace
396         bool space_inserted = true;
397         bool autobreakrows = !par->inInset() ||
398                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
399         for(string::const_iterator cit = str.begin();
400             cit != str.end(); ++cit) {
401                 if (*cit == '\n') {
402                         if (autobreakrows && (!par->empty() || par->allowEmpty())) {
403                                 breakParagraph(params, paragraphs, par, pos,
404                                                layout->isEnvironment());
405                                 ++par;
406                                 pos = 0;
407                                 space_inserted = true;
408                         } else {
409                                 continue;
410                         }
411                         // do not insert consecutive spaces if !free_spacing
412                 } else if ((*cit == ' ' || *cit == '\t') &&
413                            space_inserted && !par->isFreeSpacing()) {
414                         continue;
415                 } else if (*cit == '\t') {
416                         if (!par->isFreeSpacing()) {
417                                 // tabs are like spaces here
418                                 par->insertChar(pos, ' ', font);
419                                 ++pos;
420                                 space_inserted = true;
421                         } else {
422                                 const pos_type nb = 8 - pos % 8;
423                                 for (pos_type a = 0; a < nb ; ++a) {
424                                         par->insertChar(pos, ' ', font);
425                                         ++pos;
426                                 }
427                                 space_inserted = true;
428                         }
429                 } else if (!IsPrintable(*cit)) {
430                         // Ignore unprintables
431                         continue;
432                 } else {
433                         // just insert the character
434                         par->insertChar(pos, *cit, font);
435                         ++pos;
436                         space_inserted = (*cit == ' ');
437                 }
438
439         }
440 }
441
442
443 bool Buffer::readFile(LyXLex & lex, string const & filename)
444 {
445         bool ret = readFile(lex, filename, paragraphs.begin());
446
447         // After we have read a file, we must ensure that the buffer
448         // language is set and used in the gui.
449         // If you know of a better place to put this, please tell me. (Lgb)
450         updateDocLang(params.language);
451
452         return ret;
453 }
454
455
456 // FIXME: all the below Alerts should give the filename..
457 bool Buffer::readFile(LyXLex & lex, string const & filename,
458                       ParagraphList::iterator pit)
459 {
460         if (!lex.isOK()) {
461                 Alert::error(_("Document could not be read"),
462                         _("The specified document could not be read."));
463                 return false;
464         }
465
466         lex.next();
467         string const token(lex.getString());
468
469         if (!lex.isOK()) {
470                 Alert::error(_("Document could not be read"),
471                         _("The specified document could not be read."));
472                 return false;
473         }
474
475         // the first token _must_ be...
476         if (token != "\\lyxformat") {
477                 Alert::error(_("Document format failure"),
478                         _("The specified document is not a LyX document."));
479                 return false;
480         }
481
482         lex.eatLine();
483         string tmp_format = lex.getString();
484         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
485         // if present remove ".," from string.
486         string::size_type dot = tmp_format.find_first_of(".,");
487         //lyxerr << "           dot found at " << dot << endl;
488         if (dot != string::npos)
489                         tmp_format.erase(dot, 1);
490         file_format = strToInt(tmp_format);
491         //lyxerr << "format: " << file_format << endl;
492         if (file_format == LYX_FORMAT) {
493                 // current format
494         } else if (file_format > LYX_FORMAT) {
495                 Alert::warning(_("Document format failure"),
496                         _("This document was created with a newer version of "
497                         "LyX. This is likely to cause problems."));
498         } else if (file_format < LYX_FORMAT) {
499                 // old formats
500                 if (file_format < 200) {
501                         Alert::error(_("Document format failure"),
502                                 _("This LyX document is too old to be read "
503                                 "by this version of LyX. Try LyX 0.10."));
504                         return false;
505                 } else if (!filename.empty()) {
506                         string command =
507                                 LibFileSearch("lyx2lyx", "lyx2lyx");
508                         if (command.empty()) {
509                                 Alert::error(_("Conversion script not found"),
510                                         _("The document is from an earlier version "
511                                           "of LyX, but the conversion script lyx2lyx "
512                                           "could not be found."));
513                                 return false;
514                         }
515                         command += " -t"
516                                 +tostr(LYX_FORMAT) + ' '
517                                 + QuoteName(filename);
518                         lyxerr[Debug::INFO] << "Running '"
519                                             << command << '\''
520                                             << endl;
521                         cmd_ret const ret = RunCommand(command);
522                         if (ret.first) {
523                                 Alert::error(_("Conversion script failed"),
524                                         _("The document is from an earlier version "
525                                           "of LyX, but the lyx2lyx script failed "
526                                           "to convert it."));
527                                 return false;
528                         }
529                         istringstream is(STRCONV(ret.second));
530                         LyXLex tmplex(0, 0);
531                         tmplex.setStream(is);
532                         return readFile(tmplex, string(), pit);
533                 } else {
534                         // This code is reached if lyx2lyx failed (for
535                         // some reason) to change the file format of
536                         // the file.
537                         Assert(false);
538                         return false;
539                 }
540         }
541         bool the_end = readBody(lex, pit);
542         params.setPaperStuff();
543
544         if (!the_end) {
545                 Alert::error(_("Document format failure"),
546                         _("The document ended unexpectedly, which means "
547                           "that it is probably corrupted."));
548         }
549         return true;
550 }
551
552
553 // Should probably be moved to somewhere else: BufferView? LyXView?
554 bool Buffer::save() const
555 {
556         // We don't need autosaves in the immediate future. (Asger)
557         resetAutosaveTimers();
558
559         // make a backup
560         string s;
561         if (lyxrc.make_backup) {
562                 s = fileName() + '~';
563                 if (!lyxrc.backupdir_path.empty())
564                         s = AddName(lyxrc.backupdir_path,
565                                     subst(os::slashify_path(s),'/','!'));
566
567                 // Rename is the wrong way of making a backup,
568                 // this is the correct way.
569                 /* truss cp fil fil2:
570                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
571                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
572                    open("LyXVC.lyx", O_RDONLY)                     = 3
573                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
574                    fstat(4, 0xEFFFF508)                            = 0
575                    fstat(3, 0xEFFFF508)                            = 0
576                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
577                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
578                    read(3, 0xEFFFD4A0, 8192)                       = 0
579                    close(4)                                        = 0
580                    close(3)                                        = 0
581                    chmod("LyXVC3.lyx", 0100644)                    = 0
582                    lseek(0, 0, SEEK_CUR)                           = 46440
583                    _exit(0)
584                 */
585
586                 // Should probably have some more error checking here.
587                 // Doing it this way, also makes the inodes stay the same.
588                 // This is still not a very good solution, in particular we
589                 // might loose the owner of the backup.
590                 FileInfo finfo(fileName());
591                 if (finfo.exist()) {
592                         mode_t fmode = finfo.getMode();
593                         struct utimbuf times = {
594                                 finfo.getAccessTime(),
595                                 finfo.getModificationTime() };
596
597                         ifstream ifs(fileName().c_str());
598                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
599                         if (ifs && ofs) {
600                                 ofs << ifs.rdbuf();
601                                 ifs.close();
602                                 ofs.close();
603                                 ::chmod(s.c_str(), fmode);
604
605                                 if (::utime(s.c_str(), &times)) {
606                                         lyxerr << "utime error." << endl;
607                                 }
608                         } else {
609                                 lyxerr << "LyX was not able to make "
610                                         "backup copy. Beware." << endl;
611                         }
612                 }
613         }
614
615         if (writeFile(fileName())) {
616                 markClean();
617                 removeAutosaveFile(fileName());
618         } else {
619                 // Saving failed, so backup is not backup
620                 if (lyxrc.make_backup) {
621                         rename(s, fileName());
622                 }
623                 return false;
624         }
625         return true;
626 }
627
628
629 bool Buffer::writeFile(string const & fname) const
630 {
631         if (read_only && (fname == fileName())) {
632                 return false;
633         }
634
635         FileInfo finfo(fname);
636         if (finfo.exist() && !finfo.writable()) {
637                 return false;
638         }
639
640         bool const compressed = (fname.substr(fname.size() - 3, 3) == ".gz");
641
642         if (compressed) {
643                 gz::ogzstream ofs(fname.c_str());
644
645                 if (!ofs)
646                         return false;
647
648                 return do_writeFile(ofs);
649
650         }
651
652         ofstream ofs(fname.c_str());
653         if (!ofs)
654                 return false;
655
656         return do_writeFile(ofs);
657 }
658
659
660 bool Buffer::do_writeFile(ostream & ofs) const
661 {
662
663 #ifdef HAVE_LOCALE
664         // Use the standard "C" locale for file output.
665         ofs.imbue(std::locale::classic());
666 #endif
667
668         // The top of the file should not be written by params.
669
670         // write out a comment in the top of the file
671         ofs << '#' << lyx_docversion
672             << " created this file. For more info see http://www.lyx.org/\n"
673             << "\\lyxformat " << LYX_FORMAT << "\n";
674
675         // now write out the buffer paramters.
676         params.writeFile(ofs);
677
678         ofs << "\\end_header\n";
679
680         Paragraph::depth_type depth = 0;
681
682         // this will write out all the paragraphs
683         // using recursive descent.
684         ParagraphList::const_iterator pit = paragraphs.begin();
685         ParagraphList::const_iterator pend = paragraphs.end();
686         for (; pit != pend; ++pit)
687                 pit->write(this, ofs, params, depth);
688
689         // Write marker that shows file is complete
690         ofs << "\n\\the_end" << endl;
691
692         // Shouldn't really be needed....
693         //ofs.close();
694
695         // how to check if close went ok?
696         // Following is an attempt... (BE 20001011)
697
698         // good() returns false if any error occured, including some
699         //        formatting error.
700         // bad()  returns true if something bad happened in the buffer,
701         //        which should include file system full errors.
702
703         bool status = true;
704         if (!ofs.good()) {
705                 status = false;
706 #if 0
707                 if (ofs.bad()) {
708                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
709                 } else {
710                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
711                                << endl;
712                 }
713 #endif
714         }
715
716         return status;
717 }
718
719
720 namespace {
721
722 pair<int, string> const addDepth(int depth, int ldepth)
723 {
724         int d = depth * 2;
725         if (ldepth > depth)
726                 d += (ldepth - depth) * 2;
727         return make_pair(d, string(d, ' '));
728 }
729
730 }
731
732
733 string const Buffer::asciiParagraph(Paragraph const & par,
734                                     unsigned int linelen,
735                                     bool noparbreak) const
736 {
737         ostringstream buffer;
738         int ltype = 0;
739         Paragraph::depth_type ltype_depth = 0;
740         bool ref_printed = false;
741         Paragraph::depth_type depth = par.params().depth();
742
743         // First write the layout
744         string const & tmp = par.layout()->name();
745         if (compare_no_case(tmp, "itemize") == 0) {
746                 ltype = 1;
747                 ltype_depth = depth + 1;
748         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
749                 ltype = 2;
750                 ltype_depth = depth + 1;
751         } else if (contains(ascii_lowercase(tmp), "ection")) {
752                 ltype = 3;
753                 ltype_depth = depth + 1;
754         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
755                 ltype = 4;
756                 ltype_depth = depth + 1;
757         } else if (compare_ascii_no_case(tmp, "description") == 0) {
758                 ltype = 5;
759                 ltype_depth = depth + 1;
760         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
761                 ltype = 6;
762                 ltype_depth = 0;
763         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
764                 ltype = 7;
765                 ltype_depth = 0;
766         } else {
767                 ltype = 0;
768                 ltype_depth = 0;
769         }
770
771         /* maybe some vertical spaces */
772
773         /* the labelwidthstring used in lists */
774
775         /* some lines? */
776
777         /* some pagebreaks? */
778
779         /* noindent ? */
780
781         /* what about the alignment */
782
783         // linelen <= 0 is special and means we don't have paragraph breaks
784
785         string::size_type currlinelen = 0;
786
787         if (!noparbreak) {
788                 if (linelen > 0)
789                         buffer << "\n\n";
790
791                 buffer << string(depth * 2, ' ');
792                 currlinelen += depth * 2;
793
794                 //--
795                 // we should probably change to the paragraph language in the
796                 // gettext here (if possible) so that strings are outputted in
797                 // the correct language! (20012712 Jug)
798                 //--
799                 switch (ltype) {
800                 case 0: // Standard
801                 case 4: // (Sub)Paragraph
802                 case 5: // Description
803                         break;
804                 case 6: // Abstract
805                         if (linelen > 0) {
806                                 buffer << _("Abstract") << "\n\n";
807                                 currlinelen = 0;
808                         } else {
809                                 string const abst = _("Abstract: ");
810                                 buffer << abst;
811                                 currlinelen += abst.length();
812                         }
813                         break;
814                 case 7: // Bibliography
815                         if (!ref_printed) {
816                                 if (linelen > 0) {
817                                         buffer << _("References") << "\n\n";
818                                         currlinelen = 0;
819                                 } else {
820                                         string const refs = _("References: ");
821                                         buffer << refs;
822                                         currlinelen += refs.length();
823                                 }
824
825                                 ref_printed = true;
826                         }
827                         break;
828                 default:
829                 {
830                         string const parlab = par.params().labelString();
831                         buffer << parlab << ' ';
832                         currlinelen += parlab.length() + 1;
833                 }
834                 break;
835
836                 }
837         }
838
839         if (!currlinelen) {
840                 pair<int, string> p = addDepth(depth, ltype_depth);
841                 buffer << p.second;
842                 currlinelen += p.first;
843         }
844
845         // this is to change the linebreak to do it by word a bit more
846         // intelligent hopefully! (only in the case where we have a
847         // max linelength!) (Jug)
848
849         string word;
850
851         for (pos_type i = 0; i < par.size(); ++i) {
852                 char c = par.getUChar(params, i);
853                 switch (c) {
854                 case Paragraph::META_INSET:
855                 {
856                         InsetOld const * inset = par.getInset(i);
857                         if (inset) {
858                                 if (linelen > 0) {
859                                         buffer << word;
860                                         currlinelen += word.length();
861                                         word.erase();
862                                 }
863                                 if (inset->ascii(this, buffer, linelen)) {
864                                         // to be sure it breaks paragraph
865                                         currlinelen += linelen;
866                                 }
867                         }
868                 }
869                 break;
870
871                 default:
872                         if (c == ' ') {
873                                 if (linelen > 0 &&
874                                     currlinelen + word.length() > linelen - 10) {
875                                         buffer << "\n";
876                                         pair<int, string> p = addDepth(depth, ltype_depth);
877                                         buffer << p.second;
878                                         currlinelen = p.first;
879                                 }
880
881                                 buffer << word << ' ';
882                                 currlinelen += word.length() + 1;
883                                 word.erase();
884
885                         } else {
886                                 if (c != '\0') {
887                                         word += c;
888                                 } else {
889                                         lyxerr[Debug::INFO] <<
890                                                 "writeAsciiFile: NULL char in structure." << endl;
891                                 }
892                                 if ((linelen > 0) &&
893                                         (currlinelen + word.length()) > linelen)
894                                 {
895                                         buffer << "\n";
896
897                                         pair<int, string> p =
898                                                 addDepth(depth, ltype_depth);
899                                         buffer << p.second;
900                                         currlinelen = p.first;
901                                 }
902                         }
903                         break;
904                 }
905         }
906         buffer << word;
907         return STRCONV(buffer.str());
908 }
909
910
911 void Buffer::writeFileAscii(string const & fname, int linelen)
912 {
913         ofstream ofs;
914         if (!::openFileWrite(ofs, fname))
915                 return;
916         writeFileAscii(ofs, linelen);
917 }
918
919
920 void Buffer::writeFileAscii(ostream & os, int linelen)
921 {
922         ParagraphList::iterator beg = paragraphs.begin();
923         ParagraphList::iterator end = paragraphs.end();
924         ParagraphList::iterator it = beg;
925         for (; it != end; ++it) {
926                 os << asciiParagraph(*it, linelen, it == beg);
927         }
928         os << "\n";
929 }
930
931
932 void Buffer::makeLaTeXFile(string const & fname,
933                            string const & original_path,
934                            LatexRunParams const & runparams,
935                            bool output_preamble, bool output_body)
936 {
937         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
938
939         ofstream ofs;
940         if (!::openFileWrite(ofs, fname))
941                 return;
942
943         makeLaTeXFile(ofs, original_path,
944                       runparams, output_preamble, output_body);
945
946         ofs.close();
947         if (ofs.fail()) {
948                 lyxerr << "File was not closed properly." << endl;
949         }
950 }
951
952
953 void Buffer::makeLaTeXFile(ostream & os,
954                            string const & original_path,
955                            LatexRunParams const & runparams_in,
956                            bool output_preamble, bool output_body)
957 {
958         LatexRunParams runparams = runparams_in;
959         niceFile = runparams.nice; // this will be used by Insetincludes.
960
961         // validate the buffer.
962         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
963         LaTeXFeatures features(params);
964         validate(features);
965         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
966
967         texrow.reset();
968         // The starting paragraph of the coming rows is the
969         // first paragraph of the document. (Asger)
970         texrow.start(paragraphs.begin()->id(), 0);
971
972         if (output_preamble && runparams.nice) {
973                 os << "%% " << lyx_docversion << " created this file.  "
974                         "For more info, see http://www.lyx.org/.\n"
975                         "%% Do not edit unless you really know what "
976                         "you are doing.\n";
977                 texrow.newline();
978                 texrow.newline();
979         }
980         lyxerr[Debug::INFO] << "lyx header finished" << endl;
981         // There are a few differences between nice LaTeX and usual files:
982         // usual is \batchmode and has a
983         // special input@path to allow the including of figures
984         // with either \input or \includegraphics (what figinsets do).
985         // input@path is set when the actual parameter
986         // original_path is set. This is done for usual tex-file, but not
987         // for nice-latex-file. (Matthias 250696)
988         if (output_preamble) {
989                 if (!runparams.nice) {
990                         // code for usual, NOT nice-latex-file
991                         os << "\\batchmode\n"; // changed
992                         // from \nonstopmode
993                         texrow.newline();
994                 }
995                 if (!original_path.empty()) {
996                         string inputpath = os::external_path(original_path);
997                         subst(inputpath, "~", "\\string~");
998                         os << "\\makeatletter\n"
999                             << "\\def\\input@path{{"
1000                             << inputpath << "/}}\n"
1001                             << "\\makeatother\n";
1002                         texrow.newline();
1003                         texrow.newline();
1004                         texrow.newline();
1005                 }
1006
1007                 // Write the preamble
1008                 runparams.use_babel = params.writeLaTeX(os, features, texrow);
1009
1010                 if (!output_body)
1011                         return;
1012
1013                 // make the body.
1014                 os << "\\begin{document}\n";
1015                 texrow.newline();
1016         } // output_preamble
1017         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1018
1019         if (!lyxrc.language_auto_begin) {
1020                 os << subst(lyxrc.language_command_begin, "$$lang",
1021                              params.language->babel())
1022                     << endl;
1023                 texrow.newline();
1024         }
1025
1026         latexParagraphs(this, paragraphs, os, texrow, runparams);
1027
1028         // add this just in case after all the paragraphs
1029         os << endl;
1030         texrow.newline();
1031
1032         if (!lyxrc.language_auto_end) {
1033                 os << subst(lyxrc.language_command_end, "$$lang",
1034                              params.language->babel())
1035                     << endl;
1036                 texrow.newline();
1037         }
1038
1039         if (output_preamble) {
1040                 os << "\\end{document}\n";
1041                 texrow.newline();
1042
1043                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1044         } else {
1045                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1046                                      << endl;
1047         }
1048
1049         // Just to be sure. (Asger)
1050         texrow.newline();
1051
1052         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1053         lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1054                             << '.' << endl;
1055
1056         // we want this to be true outside previews (for insetexternal)
1057         niceFile = true;
1058 }
1059
1060
1061 bool Buffer::isLatex() const
1062 {
1063         return params.getLyXTextClass().outputType() == LATEX;
1064 }
1065
1066
1067 bool Buffer::isLinuxDoc() const
1068 {
1069         return params.getLyXTextClass().outputType() == LINUXDOC;
1070 }
1071
1072
1073 bool Buffer::isLiterate() const
1074 {
1075         return params.getLyXTextClass().outputType() == LITERATE;
1076 }
1077
1078
1079 bool Buffer::isDocBook() const
1080 {
1081         return params.getLyXTextClass().outputType() == DOCBOOK;
1082 }
1083
1084
1085 bool Buffer::isSGML() const
1086 {
1087         LyXTextClass const & tclass = params.getLyXTextClass();
1088
1089         return tclass.outputType() == LINUXDOC ||
1090                tclass.outputType() == DOCBOOK;
1091 }
1092
1093
1094 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1095 {
1096         ofstream ofs;
1097         if (!::openFileWrite(ofs, fname))
1098                 return;
1099
1100         niceFile = nice; // this will be used by included files.
1101
1102         LaTeXFeatures features(params);
1103
1104         validate(features);
1105
1106         texrow.reset();
1107
1108         LyXTextClass const & tclass = params.getLyXTextClass();
1109
1110         string top_element = tclass.latexname();
1111
1112         if (!body_only) {
1113                 ofs << "<!doctype linuxdoc system";
1114
1115                 string preamble = params.preamble;
1116                 string const name = nice ? ChangeExtension(filename_, ".sgml")
1117                          : fname;
1118                 preamble += features.getIncludedFiles(name);
1119                 preamble += features.getLyXSGMLEntities();
1120
1121                 if (!preamble.empty()) {
1122                         ofs << " [ " << preamble << " ]";
1123                 }
1124                 ofs << ">\n\n";
1125
1126                 if (params.options.empty())
1127                         sgml::openTag(ofs, 0, false, top_element);
1128                 else {
1129                         string top = top_element;
1130                         top += ' ';
1131                         top += params.options;
1132                         sgml::openTag(ofs, 0, false, top);
1133                 }
1134         }
1135
1136         ofs << "<!-- "  << lyx_docversion
1137             << " created this file. For more info see http://www.lyx.org/"
1138             << " -->\n";
1139
1140         Paragraph::depth_type depth = 0; // paragraph depth
1141         string item_name;
1142         vector<string> environment_stack(5);
1143
1144         ParagraphList::iterator pit = paragraphs.begin();
1145         ParagraphList::iterator pend = paragraphs.end();
1146         for (; pit != pend; ++pit) {
1147                 LyXLayout_ptr const & style = pit->layout();
1148                 // treat <toc> as a special case for compatibility with old code
1149                 if (pit->isInset(0)) {
1150                         InsetOld * inset = pit->getInset(0);
1151                         InsetOld::Code lyx_code = inset->lyxCode();
1152                         if (lyx_code == InsetOld::TOC_CODE) {
1153                                 string const temp = "toc";
1154                                 sgml::openTag(ofs, depth, false, temp);
1155                                 continue;
1156                         }
1157                 }
1158
1159                 // environment tag closing
1160                 for (; depth > pit->params().depth(); --depth) {
1161                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1162                         environment_stack[depth].erase();
1163                 }
1164
1165                 // write opening SGML tags
1166                 switch (style->latextype) {
1167                 case LATEX_PARAGRAPH:
1168                         if (depth == pit->params().depth()
1169                            && !environment_stack[depth].empty()) {
1170                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1171                                 environment_stack[depth].erase();
1172                                 if (depth)
1173                                         --depth;
1174                                 else
1175                                         ofs << "</p>";
1176                         }
1177                         sgml::openTag(ofs, depth, false, style->latexname());
1178                         break;
1179
1180                 case LATEX_COMMAND:
1181                         if (depth != 0)
1182                                 error(ErrorItem(_("Error:"), _("Wrong depth for LatexType Command.\n"), pit->id(), 0, pit->size()));
1183
1184                         if (!environment_stack[depth].empty()) {
1185                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1186                                 ofs << "</p>";
1187                         }
1188
1189                         environment_stack[depth].erase();
1190                         sgml::openTag(ofs, depth, false, style->latexname());
1191                         break;
1192
1193                 case LATEX_ENVIRONMENT:
1194                 case LATEX_ITEM_ENVIRONMENT:
1195                 case LATEX_BIB_ENVIRONMENT:
1196                 {
1197                         string const & latexname = style->latexname();
1198
1199                         if (depth == pit->params().depth()
1200                             && environment_stack[depth] != latexname) {
1201                                 sgml::closeTag(ofs, depth, false,
1202                                              environment_stack[depth]);
1203                                 environment_stack[depth].erase();
1204                         }
1205                         if (depth < pit->params().depth()) {
1206                                depth = pit->params().depth();
1207                                environment_stack[depth].erase();
1208                         }
1209                         if (environment_stack[depth] != latexname) {
1210                                 if (depth == 0) {
1211                                         sgml::openTag(ofs, depth, false, "p");
1212                                 }
1213                                 sgml::openTag(ofs, depth, false, latexname);
1214
1215                                 if (environment_stack.size() == depth + 1)
1216                                         environment_stack.push_back("!-- --");
1217                                 environment_stack[depth] = latexname;
1218                         }
1219
1220                         if (style->latexparam() == "CDATA")
1221                                 ofs << "<![CDATA[";
1222
1223                         if (style->latextype == LATEX_ENVIRONMENT) break;
1224
1225                         if (style->labeltype == LABEL_MANUAL)
1226                                 item_name = "tag";
1227                         else
1228                                 item_name = "item";
1229
1230                         sgml::openTag(ofs, depth + 1, false, item_name);
1231                 }
1232                 break;
1233
1234                 default:
1235                         sgml::openTag(ofs, depth, false, style->latexname());
1236                         break;
1237                 }
1238
1239                 simpleLinuxDocOnePar(ofs, pit, depth);
1240
1241                 ofs << "\n";
1242                 // write closing SGML tags
1243                 switch (style->latextype) {
1244                 case LATEX_COMMAND:
1245                         break;
1246                 case LATEX_ENVIRONMENT:
1247                 case LATEX_ITEM_ENVIRONMENT:
1248                 case LATEX_BIB_ENVIRONMENT:
1249                         if (style->latexparam() == "CDATA")
1250                                 ofs << "]]>";
1251                         break;
1252                 default:
1253                         sgml::closeTag(ofs, depth, false, style->latexname());
1254                         break;
1255                 }
1256         }
1257
1258         // Close open tags
1259         for (int i = depth; i >= 0; --i)
1260                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1261
1262         if (!body_only) {
1263                 ofs << "\n\n";
1264                 sgml::closeTag(ofs, 0, false, top_element);
1265         }
1266
1267         ofs.close();
1268         // How to check for successful close
1269
1270         // we want this to be true outside previews (for insetexternal)
1271         niceFile = true;
1272 }
1273
1274
1275 // checks, if newcol chars should be put into this line
1276 // writes newline, if necessary.
1277 namespace {
1278
1279 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1280                           string::size_type newcol)
1281 {
1282         colcount += newcol;
1283         if (colcount > lyxrc.ascii_linelen) {
1284                 os << "\n";
1285                 colcount = newcol; // assume write after this call
1286         }
1287 }
1288
1289 enum PAR_TAG {
1290         NONE=0,
1291         TT = 1,
1292         SF = 2,
1293         BF = 4,
1294         IT = 8,
1295         SL = 16,
1296         EM = 32
1297 };
1298
1299
1300 string tag_name(PAR_TAG const & pt) {
1301         switch (pt) {
1302         case NONE: return "!-- --";
1303         case TT: return "tt";
1304         case SF: return "sf";
1305         case BF: return "bf";
1306         case IT: return "it";
1307         case SL: return "sl";
1308         case EM: return "em";
1309         }
1310         return "";
1311 }
1312
1313
1314 inline
1315 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1316 {
1317         p1 = static_cast<PAR_TAG>(p1 | p2);
1318 }
1319
1320
1321 inline
1322 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1323 {
1324         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1325 }
1326
1327 } // anon
1328
1329
1330 // Handle internal paragraph parsing -- layout already processed.
1331 void Buffer::simpleLinuxDocOnePar(ostream & os,
1332         ParagraphList::iterator par,
1333         Paragraph::depth_type /*depth*/) const
1334 {
1335         LyXLayout_ptr const & style = par->layout();
1336
1337         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1338
1339         // gets paragraph main font
1340         LyXFont font_old;
1341         bool desc_on;
1342         if (style->labeltype == LABEL_MANUAL) {
1343                 font_old = style->labelfont;
1344                 desc_on = true;
1345         } else {
1346                 font_old = style->font;
1347                 desc_on = false;
1348         }
1349
1350         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1351         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1352         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1353         bool is_em = false;
1354
1355         stack<PAR_TAG> tag_state;
1356         // parsing main loop
1357         for (pos_type i = 0; i < par->size(); ++i) {
1358
1359                 PAR_TAG tag_close = NONE;
1360                 list < PAR_TAG > tag_open;
1361
1362                 LyXFont const font = par->getFont(params, i, outerFont(par, paragraphs));
1363
1364                 if (font_old.family() != font.family()) {
1365                         switch (family_type) {
1366                         case LyXFont::SANS_FAMILY:
1367                                 tag_close |= SF;
1368                                 break;
1369                         case LyXFont::TYPEWRITER_FAMILY:
1370                                 tag_close |= TT;
1371                                 break;
1372                         default:
1373                                 break;
1374                         }
1375
1376                         family_type = font.family();
1377
1378                         switch (family_type) {
1379                         case LyXFont::SANS_FAMILY:
1380                                 tag_open.push_back(SF);
1381                                 break;
1382                         case LyXFont::TYPEWRITER_FAMILY:
1383                                 tag_open.push_back(TT);
1384                                 break;
1385                         default:
1386                                 break;
1387                         }
1388                 }
1389
1390                 if (font_old.series() != font.series()) {
1391                         switch (series_type) {
1392                         case LyXFont::BOLD_SERIES:
1393                                 tag_close |= BF;
1394                                 break;
1395                         default:
1396                                 break;
1397                         }
1398
1399                         series_type = font.series();
1400
1401                         switch (series_type) {
1402                         case LyXFont::BOLD_SERIES:
1403                                 tag_open.push_back(BF);
1404                                 break;
1405                         default:
1406                                 break;
1407                         }
1408
1409                 }
1410
1411                 if (font_old.shape() != font.shape()) {
1412                         switch (shape_type) {
1413                         case LyXFont::ITALIC_SHAPE:
1414                                 tag_close |= IT;
1415                                 break;
1416                         case LyXFont::SLANTED_SHAPE:
1417                                 tag_close |= SL;
1418                                 break;
1419                         default:
1420                                 break;
1421                         }
1422
1423                         shape_type = font.shape();
1424
1425                         switch (shape_type) {
1426                         case LyXFont::ITALIC_SHAPE:
1427                                 tag_open.push_back(IT);
1428                                 break;
1429                         case LyXFont::SLANTED_SHAPE:
1430                                 tag_open.push_back(SL);
1431                                 break;
1432                         default:
1433                                 break;
1434                         }
1435                 }
1436                 // handle <em> tag
1437                 if (font_old.emph() != font.emph()) {
1438                         if (font.emph() == LyXFont::ON) {
1439                                 tag_open.push_back(EM);
1440                                 is_em = true;
1441                         }
1442                         else if (is_em) {
1443                                 tag_close |= EM;
1444                                 is_em = false;
1445                         }
1446                 }
1447
1448                 list < PAR_TAG > temp;
1449                 while (!tag_state.empty() && tag_close) {
1450                         PAR_TAG k =  tag_state.top();
1451                         tag_state.pop();
1452                         os << "</" << tag_name(k) << '>';
1453                         if (tag_close & k)
1454                                 reset(tag_close,k);
1455                         else
1456                                 temp.push_back(k);
1457                 }
1458
1459                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1460                     j != temp.end(); ++j) {
1461                         tag_state.push(*j);
1462                         os << '<' << tag_name(*j) << '>';
1463                 }
1464
1465                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1466                     j != tag_open.end(); ++j) {
1467                         tag_state.push(*j);
1468                         os << '<' << tag_name(*j) << '>';
1469                 }
1470
1471                 char c = par->getChar(i);
1472
1473                 if (c == Paragraph::META_INSET) {
1474                         InsetOld * inset = par->getInset(i);
1475                         inset->linuxdoc(this, os);
1476                         font_old = font;
1477                         continue;
1478                 }
1479
1480                 if (style->latexparam() == "CDATA") {
1481                         // "TeX"-Mode on == > SGML-Mode on.
1482                         if (c != '\0')
1483                                 os << c;
1484                         ++char_line_count;
1485                 } else {
1486                         bool ws;
1487                         string str;
1488                         boost::tie(ws, str) = sgml::escapeChar(c);
1489                         if (ws && !par->isFreeSpacing()) {
1490                                 // in freespacing mode, spaces are
1491                                 // non-breaking characters
1492                                 if (desc_on) {// if char is ' ' then...
1493
1494                                         ++char_line_count;
1495                                         sgmlLineBreak(os, char_line_count, 6);
1496                                         os << "</tag>";
1497                                         desc_on = false;
1498                                 } else  {
1499                                         sgmlLineBreak(os, char_line_count, 1);
1500                                         os << c;
1501                                 }
1502                         } else {
1503                                 os << str;
1504                                 char_line_count += str.length();
1505                         }
1506                 }
1507                 font_old = font;
1508         }
1509
1510         while (!tag_state.empty()) {
1511                 os << "</" << tag_name(tag_state.top()) << '>';
1512                 tag_state.pop();
1513         }
1514
1515         // resets description flag correctly
1516         if (desc_on) {
1517                 // <tag> not closed...
1518                 sgmlLineBreak(os, char_line_count, 6);
1519                 os << "</tag>";
1520         }
1521 }
1522
1523
1524 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
1525 {
1526         ofstream ofs;
1527         if (!::openFileWrite(ofs, fname))
1528                 return;
1529
1530         niceFile = nice; // this will be used by Insetincludes.
1531
1532         LaTeXFeatures features(params);
1533         validate(features);
1534
1535         texrow.reset();
1536
1537         LyXTextClass const & tclass = params.getLyXTextClass();
1538         string top_element = tclass.latexname();
1539
1540         if (!only_body) {
1541                 ofs << "<!DOCTYPE " << top_element
1542                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
1543
1544                 string preamble = params.preamble;
1545                 string const name = nice ? ChangeExtension(filename_, ".sgml")
1546                          : fname;
1547                 preamble += features.getIncludedFiles(name);
1548                 preamble += features.getLyXSGMLEntities();
1549
1550                 if (!preamble.empty()) {
1551                         ofs << "\n [ " << preamble << " ]";
1552                 }
1553                 ofs << ">\n\n";
1554         }
1555
1556         string top = top_element;
1557         top += " lang=\"";
1558         top += params.language->code();
1559         top += '"';
1560
1561         if (!params.options.empty()) {
1562                 top += ' ';
1563                 top += params.options;
1564         }
1565         sgml::openTag(ofs, 0, false, top);
1566
1567         ofs << "<!-- DocBook file was created by " << lyx_docversion
1568             << "\n  See http://www.lyx.org/ for more information -->\n";
1569
1570         vector<string> environment_stack(10);
1571         vector<string> environment_inner(10);
1572         vector<string> command_stack(10);
1573
1574         bool command_flag = false;
1575         Paragraph::depth_type command_depth = 0;
1576         Paragraph::depth_type command_base = 0;
1577         Paragraph::depth_type cmd_depth = 0;
1578         Paragraph::depth_type depth = 0; // paragraph depth
1579
1580         string item_name;
1581         string command_name;
1582
1583         ParagraphList::iterator par = paragraphs.begin();
1584         ParagraphList::iterator pend = paragraphs.end();
1585
1586         for (; par != pend; ++par) {
1587                 string sgmlparam;
1588                 string c_depth;
1589                 string c_params;
1590                 int desc_on = 0; // description mode
1591
1592                 LyXLayout_ptr const & style = par->layout();
1593
1594                 // environment tag closing
1595                 for (; depth > par->params().depth(); --depth) {
1596                         if (environment_inner[depth] != "!-- --" && !environment_inner[depth].empty()) {
1597                                 item_name = "listitem";
1598                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1599                                 if (environment_inner[depth] == "varlistentry")
1600                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
1601                         }
1602                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1603                         environment_stack[depth].erase();
1604                         environment_inner[depth].erase();
1605                 }
1606
1607                 if (depth == par->params().depth()
1608                    && environment_stack[depth] != style->latexname()
1609                    && !environment_stack[depth].empty()) {
1610                         if (environment_inner[depth] != "!-- --") {
1611                                 item_name= "listitem";
1612                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
1613                                 if (environment_inner[depth] == "varlistentry")
1614                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1615                         }
1616
1617                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1618
1619                         environment_stack[depth].erase();
1620                         environment_inner[depth].erase();
1621                 }
1622
1623                 // Write opening SGML tags.
1624                 switch (style->latextype) {
1625                 case LATEX_PARAGRAPH:
1626                         sgml::openTag(ofs, depth + command_depth,
1627                                     false, style->latexname());
1628                         break;
1629
1630                 case LATEX_COMMAND:
1631                         if (depth != 0)
1632                                 error(ErrorItem(_("Error"), _("Wrong depth for LatexType Command."), par->id(), 0, par->size()));
1633
1634                         command_name = style->latexname();
1635
1636                         sgmlparam = style->latexparam();
1637                         c_params = split(sgmlparam, c_depth,'|');
1638
1639                         cmd_depth = atoi(c_depth);
1640
1641                         if (command_flag) {
1642                                 if (cmd_depth < command_base) {
1643                                         for (Paragraph::depth_type j = command_depth;
1644                                              j >= command_base; --j) {
1645                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1646                                                 ofs << endl;
1647                                         }
1648                                         command_depth = command_base = cmd_depth;
1649                                 } else if (cmd_depth <= command_depth) {
1650                                         for (int j = command_depth;
1651                                              j >= int(cmd_depth); --j) {
1652                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
1653                                                 ofs << endl;
1654                                         }
1655                                         command_depth = cmd_depth;
1656                                 } else
1657                                         command_depth = cmd_depth;
1658                         } else {
1659                                 command_depth = command_base = cmd_depth;
1660                                 command_flag = true;
1661                         }
1662                         if (command_stack.size() == command_depth + 1)
1663                                 command_stack.push_back(string());
1664                         command_stack[command_depth] = command_name;
1665
1666                         // treat label as a special case for
1667                         // more WYSIWYM handling.
1668                         // This is a hack while paragraphs can't have
1669                         // attributes, like id in this case.
1670                         if (par->isInset(0)) {
1671                                 InsetOld * inset = par->getInset(0);
1672                                 InsetOld::Code lyx_code = inset->lyxCode();
1673                                 if (lyx_code == InsetOld::LABEL_CODE) {
1674                                         command_name += " id=\"";
1675                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
1676                                         command_name += '"';
1677                                         desc_on = 3;
1678                                 }
1679                         }
1680
1681                         sgml::openTag(ofs, depth + command_depth, false, command_name);
1682
1683                         item_name = c_params.empty() ? "title" : c_params;
1684                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
1685                         break;
1686
1687                 case LATEX_ENVIRONMENT:
1688                 case LATEX_ITEM_ENVIRONMENT:
1689                         if (depth < par->params().depth()) {
1690                                 depth = par->params().depth();
1691                                 environment_stack[depth].erase();
1692                         }
1693
1694                         if (environment_stack[depth] != style->latexname()) {
1695                                 if (environment_stack.size() == depth + 1) {
1696                                         environment_stack.push_back("!-- --");
1697                                         environment_inner.push_back("!-- --");
1698                                 }
1699                                 environment_stack[depth] = style->latexname();
1700                                 environment_inner[depth] = "!-- --";
1701                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
1702                         } else {
1703                                 if (environment_inner[depth] != "!-- --") {
1704                                         item_name= "listitem";
1705                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
1706                                         if (environment_inner[depth] == "varlistentry")
1707                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1708                                 }
1709                         }
1710
1711                         if (style->latextype == LATEX_ENVIRONMENT) {
1712                                 if (!style->latexparam().empty()) {
1713                                         if (style->latexparam() == "CDATA")
1714                                                 ofs << "<![CDATA[";
1715                                         else
1716                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
1717                                 }
1718                                 break;
1719                         }
1720
1721                         desc_on = (style->labeltype == LABEL_MANUAL);
1722
1723                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1724                         sgml::openTag(ofs, depth + 1 + command_depth,
1725                                     false, environment_inner[depth]);
1726
1727                         item_name = desc_on ? "term" : "para";
1728                         sgml::openTag(ofs, depth + 1 + command_depth,
1729                                     false, item_name);
1730                         break;
1731                 default:
1732                         sgml::openTag(ofs, depth + command_depth,
1733                                     false, style->latexname());
1734                         break;
1735                 }
1736
1737                 simpleDocBookOnePar(ofs, par, desc_on,
1738                                     depth + 1 + command_depth);
1739
1740                 string end_tag;
1741                 // write closing SGML tags
1742                 switch (style->latextype) {
1743                 case LATEX_COMMAND:
1744                         end_tag = c_params.empty() ? "title" : c_params;
1745                         sgml::closeTag(ofs, depth + command_depth,
1746                                      false, end_tag);
1747                         break;
1748                 case LATEX_ENVIRONMENT:
1749                         if (!style->latexparam().empty()) {
1750                                 if (style->latexparam() == "CDATA")
1751                                         ofs << "]]>";
1752                                 else
1753                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
1754                         }
1755                         break;
1756                 case LATEX_ITEM_ENVIRONMENT:
1757                         if (desc_on == 1) break;
1758                         end_tag = "para";
1759                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
1760                         break;
1761                 case LATEX_PARAGRAPH:
1762                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1763                         break;
1764                 default:
1765                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
1766                         break;
1767                 }
1768         }
1769
1770         // Close open tags
1771         for (int d = depth; d >= 0; --d) {
1772                 if (!environment_stack[depth].empty()) {
1773                         if (environment_inner[depth] != "!-- --") {
1774                                 item_name = "listitem";
1775                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
1776                                if (environment_inner[depth] == "varlistentry")
1777                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
1778                         }
1779
1780                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
1781                 }
1782         }
1783
1784         for (int j = command_depth; j >= 0 ; --j)
1785                 if (!command_stack[j].empty()) {
1786                         sgml::closeTag(ofs, j, false, command_stack[j]);
1787                         ofs << endl;
1788                 }
1789
1790         ofs << "\n\n";
1791         sgml::closeTag(ofs, 0, false, top_element);
1792
1793         ofs.close();
1794         // How to check for successful close
1795
1796         // we want this to be true outside previews (for insetexternal)
1797         niceFile = true;
1798 }
1799
1800
1801 void Buffer::simpleDocBookOnePar(ostream & os,
1802                                  ParagraphList::iterator par, int & desc_on,
1803                                  Paragraph::depth_type depth) const
1804 {
1805         bool emph_flag = false;
1806
1807         LyXLayout_ptr const & style = par->layout();
1808
1809         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
1810
1811         int char_line_count = depth;
1812         //if (!style.free_spacing)
1813         //      os << string(depth,' ');
1814
1815         // parsing main loop
1816         for (pos_type i = 0; i < par->size(); ++i) {
1817                 LyXFont font = par->getFont(params, i, outerFont(par, paragraphs));
1818
1819                 // handle <emphasis> tag
1820                 if (font_old.emph() != font.emph()) {
1821                         if (font.emph() == LyXFont::ON) {
1822                                 if (style->latexparam() == "CDATA")
1823                                         os << "]]>";
1824                                 os << "<emphasis>";
1825                                 if (style->latexparam() == "CDATA")
1826                                         os << "<![CDATA[";
1827                                 emph_flag = true;
1828                         } else if (i) {
1829                                 if (style->latexparam() == "CDATA")
1830                                         os << "]]>";
1831                                 os << "</emphasis>";
1832                                 if (style->latexparam() == "CDATA")
1833                                         os << "<![CDATA[";
1834                                 emph_flag = false;
1835                         }
1836                 }
1837
1838
1839                 if (par->isInset(i)) {
1840                         InsetOld * inset = par->getInset(i);
1841                         // don't print the inset in position 0 if desc_on == 3 (label)
1842                         if (i || desc_on != 3) {
1843                                 if (style->latexparam() == "CDATA")
1844                                         os << "]]>";
1845                                 inset->docbook(this, os, false);
1846                                 if (style->latexparam() == "CDATA")
1847                                         os << "<![CDATA[";
1848                         }
1849                 } else {
1850                         char c = par->getChar(i);
1851                         bool ws;
1852                         string str;
1853                         boost::tie(ws, str) = sgml::escapeChar(c);
1854
1855                         if (style->pass_thru) {
1856                                 os << c;
1857                         } else if (par->isFreeSpacing() || c != ' ') {
1858                                         os << str;
1859                         } else if (desc_on == 1) {
1860                                 ++char_line_count;
1861                                 os << "\n</term><listitem><para>";
1862                                 desc_on = 2;
1863                         } else {
1864                                 os << ' ';
1865                         }
1866                 }
1867                 font_old = font;
1868         }
1869
1870         if (emph_flag) {
1871                 if (style->latexparam() == "CDATA")
1872                         os << "]]>";
1873                 os << "</emphasis>";
1874                 if (style->latexparam() == "CDATA")
1875                         os << "<![CDATA[";
1876         }
1877
1878         // resets description flag correctly
1879         if (desc_on == 1) {
1880                 // <term> not closed...
1881                 os << "</term>\n<listitem><para>&nbsp;</para>";
1882         }
1883         if (style->free_spacing)
1884                 os << '\n';
1885 }
1886
1887
1888 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1889 // Other flags: -wall -v0 -x
1890 int Buffer::runChktex()
1891 {
1892         busy(true);
1893
1894         // get LaTeX-Filename
1895         string const name = getLatexName();
1896         string path = filePath();
1897
1898         string const org_path = path;
1899         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
1900                 path = tmppath;
1901         }
1902
1903         Path p(path); // path to LaTeX file
1904         message(_("Running chktex..."));
1905
1906         // Generate the LaTeX file if neccessary
1907         LatexRunParams runparams;
1908         runparams.flavor = LatexRunParams::LATEX;
1909         runparams.nice = false;
1910         makeLaTeXFile(name, org_path, runparams);
1911
1912         TeXErrors terr;
1913         Chktex chktex(lyxrc.chktex_command, name, filePath());
1914         int res = chktex.run(terr); // run chktex
1915
1916         if (res == -1) {
1917                 Alert::error(_("chktex failure"),
1918                              _("Could not run chktex successfully."));
1919         } else if (res > 0) {
1920                 // Insert all errors as errors boxes
1921                 bufferErrors(*this, terr);
1922         }
1923
1924         busy(false);
1925
1926         return res;
1927 }
1928
1929
1930 void Buffer::validate(LaTeXFeatures & features) const
1931 {
1932         LyXTextClass const & tclass = params.getLyXTextClass();
1933
1934         if (params.tracking_changes) {
1935                 features.require("dvipost");
1936                 features.require("color");
1937         }
1938
1939         // AMS Style is at document level
1940         if (params.use_amsmath == BufferParams::AMS_ON
1941             || tclass.provides(LyXTextClass::amsmath))
1942                 features.require("amsmath");
1943
1944         for_each(paragraphs.begin(), paragraphs.end(),
1945                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1946
1947         // the bullet shapes are buffer level not paragraph level
1948         // so they are tested here
1949         for (int i = 0; i < 4; ++i) {
1950                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
1951                         int const font = params.user_defined_bullets[i].getFont();
1952                         if (font == 0) {
1953                                 int const c = params
1954                                         .user_defined_bullets[i]
1955                                         .getCharacter();
1956                                 if (c == 16
1957                                    || c == 17
1958                                    || c == 25
1959                                    || c == 26
1960                                    || c == 31) {
1961                                         features.require("latexsym");
1962                                 }
1963                         } else if (font == 1) {
1964                                 features.require("amssymb");
1965                         } else if ((font >= 2 && font <= 5)) {
1966                                 features.require("pifont");
1967                         }
1968                 }
1969         }
1970
1971         if (lyxerr.debugging(Debug::LATEX)) {
1972                 features.showStruct();
1973         }
1974 }
1975
1976
1977 void Buffer::getLabelList(std::vector<string> & list) const
1978 {
1979         /// if this is a child document and the parent is already loaded
1980         /// Use the parent's list instead  [ale990407]
1981         if (!params.parentname.empty()
1982             && bufferlist.exists(params.parentname)) {
1983                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
1984                 if (tmp) {
1985                         tmp->getLabelList(list);
1986                         return;
1987                 }
1988         }
1989
1990         for (inset_iterator it = inset_const_iterator_begin();
1991              it != inset_const_iterator_end(); ++it) {
1992                 it->getLabelList(list);
1993         }
1994 }
1995
1996
1997 // This is also a buffer property (ale)
1998 void Buffer::fillWithBibKeys(std::vector<std::pair<string, string> > & keys) const
1999 {
2000         /// if this is a child document and the parent is already loaded
2001         /// use the parent's list instead  [ale990412]
2002         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2003                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2004                 if (tmp) {
2005                         tmp->fillWithBibKeys(keys);
2006                         return;
2007                 }
2008         }
2009
2010         for (inset_iterator it = inset_const_iterator_begin();
2011                 it != inset_const_iterator_end(); ++it) {
2012                 if (it->lyxCode() == InsetOld::BIBTEX_CODE)
2013                         static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2014                 else if (it->lyxCode() == InsetOld::INCLUDE_CODE)
2015                         static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2016                 else if (it->lyxCode() == InsetOld::BIBITEM_CODE) {
2017                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2018                         string const key = bib.getContents();
2019                         string const opt = bib.getOptions();
2020                         string const ref; // = pit->asString(this, false);
2021                         string const info = opt + "TheBibliographyRef" + ref;
2022                         keys.push_back(pair<string, string>(key, info));
2023                 }
2024         }
2025 }
2026
2027
2028 bool Buffer::isDepClean(string const & name) const
2029 {
2030         DepClean::const_iterator it = dep_clean_.find(name);
2031         if (it == dep_clean_.end())
2032                 return true;
2033         return it->second;
2034 }
2035
2036
2037 void Buffer::markDepClean(string const & name)
2038 {
2039         dep_clean_[name] = true;
2040 }
2041
2042
2043 bool Buffer::dispatch(string const & command, bool * result)
2044 {
2045         // Split command string into command and argument
2046         string cmd;
2047         string line = ltrim(command);
2048         string const arg = trim(split(line, cmd, ' '));
2049
2050         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2051 }
2052
2053
2054 bool Buffer::dispatch(int action, string const & argument, bool * result)
2055 {
2056         bool dispatched = true;
2057
2058         switch (action) {
2059                 case LFUN_EXPORT: {
2060                         bool const tmp = Exporter::Export(this, argument, false);
2061                         if (result)
2062                                 *result = tmp;
2063                         break;
2064                 }
2065
2066                 default:
2067                         dispatched = false;
2068         }
2069         return dispatched;
2070 }
2071
2072
2073 void Buffer::changeLanguage(Language const * from, Language const * to)
2074 {
2075         lyxerr << "Changing Language!" << endl;
2076
2077         // Take care of l10n/i18n
2078         updateDocLang(to);
2079
2080         ParIterator end = par_iterator_end();
2081         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2082                 it->changeLanguage(params, from, to);
2083 }
2084
2085
2086 void Buffer::updateDocLang(Language const * nlang)
2087 {
2088         messages_.reset(new Messages(nlang->code()));
2089 }
2090
2091
2092 bool Buffer::isMultiLingual()
2093 {
2094         ParIterator end = par_iterator_end();
2095         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2096                 if (it->isMultiLingual(params))
2097                         return true;
2098
2099         return false;
2100 }
2101
2102
2103 void Buffer::inset_iterator::setParagraph()
2104 {
2105         while (pit != pend) {
2106                 it = pit->insetlist.begin();
2107                 if (it != pit->insetlist.end())
2108                         return;
2109                 ++pit;
2110         }
2111 }
2112
2113
2114 InsetOld * Buffer::getInsetFromID(int id_arg) const
2115 {
2116         for (inset_iterator it = inset_const_iterator_begin();
2117                  it != inset_const_iterator_end(); ++it)
2118         {
2119                 if (it->id() == id_arg)
2120                         return &(*it);
2121                 InsetOld * in = it->getInsetFromID(id_arg);
2122                 if (in)
2123                         return in;
2124         }
2125         return 0;
2126 }
2127
2128
2129 ParIterator Buffer::getParFromID(int id) const
2130 {
2131 #warning FIXME: const correctness! (Andre)
2132         ParIterator it = const_cast<Buffer*>(this)->par_iterator_begin();
2133         ParIterator end = const_cast<Buffer*>(this)->par_iterator_end();
2134
2135 #warning FIXME, perhaps this func should return a ParIterator? (Lgb)
2136         if (id < 0) {
2137                 // John says this is called with id == -1 from undo
2138                 lyxerr << "getParFromID(), id: " << id << endl;
2139                 return end;
2140         }
2141
2142         for (; it != end; ++it)
2143                 if (it->id() == id)
2144                         return it;
2145
2146         return end;
2147 }
2148
2149
2150 bool Buffer::hasParWithID(int id) const
2151 {
2152         ParConstIterator it = par_iterator_begin();
2153         ParConstIterator end = par_iterator_end();
2154
2155         if (id < 0) {
2156                 // John says this is called with id == -1 from undo
2157                 lyxerr << "hasParWithID(), id: " << id << endl;
2158                 return 0;
2159         }
2160
2161         for (; it != end; ++it)
2162                 if (it->id() == id)
2163                         return true;
2164
2165         return false;
2166 }
2167
2168
2169 ParIterator Buffer::par_iterator_begin()
2170 {
2171         return ParIterator(paragraphs.begin(), paragraphs);
2172 }
2173
2174
2175 ParIterator Buffer::par_iterator_end()
2176 {
2177         return ParIterator(paragraphs.end(), paragraphs);
2178 }
2179
2180 ParConstIterator Buffer::par_iterator_begin() const
2181 {
2182         return ParConstIterator(const_cast<ParagraphList&>(paragraphs).begin(), paragraphs);
2183 }
2184
2185
2186 ParConstIterator Buffer::par_iterator_end() const
2187 {
2188         return ParConstIterator(const_cast<ParagraphList&>(paragraphs).end(), paragraphs);
2189 }
2190
2191
2192 Language const * Buffer::getLanguage() const
2193 {
2194         return params.language;
2195 }
2196
2197
2198 string const Buffer::B_(string const & l10n) const
2199 {
2200         if (messages_.get()) {
2201                 return messages_->get(l10n);
2202         }
2203
2204         return _(l10n);
2205 }
2206
2207
2208 bool Buffer::isClean() const
2209 {
2210         return lyx_clean;
2211 }
2212
2213
2214 bool Buffer::isBakClean() const
2215 {
2216         return bak_clean;
2217 }
2218
2219
2220 void Buffer::markClean() const
2221 {
2222         if (!lyx_clean) {
2223                 lyx_clean = true;
2224                 updateTitles();
2225         }
2226         // if the .lyx file has been saved, we don't need an
2227         // autosave
2228         bak_clean = true;
2229 }
2230
2231
2232 void Buffer::markBakClean()
2233 {
2234         bak_clean = true;
2235 }
2236
2237
2238 void Buffer::setUnnamed(bool flag)
2239 {
2240         unnamed = flag;
2241 }
2242
2243
2244 bool Buffer::isUnnamed()
2245 {
2246         return unnamed;
2247 }
2248
2249
2250 void Buffer::markDirty()
2251 {
2252         if (lyx_clean) {
2253                 lyx_clean = false;
2254                 updateTitles();
2255         }
2256         bak_clean = false;
2257
2258         DepClean::iterator it = dep_clean_.begin();
2259         DepClean::const_iterator const end = dep_clean_.end();
2260
2261         for (; it != end; ++it) {
2262                 it->second = false;
2263         }
2264 }
2265
2266
2267 string const & Buffer::fileName() const
2268 {
2269         return filename_;
2270 }
2271
2272
2273 string const & Buffer::filePath() const
2274 {
2275         return filepath_;
2276 }
2277
2278
2279 bool Buffer::isReadonly() const
2280 {
2281         return read_only;
2282 }
2283
2284
2285 void Buffer::setParentName(string const & name)
2286 {
2287         params.parentname = name;
2288 }
2289
2290
2291 Buffer::inset_iterator::inset_iterator()
2292         : pit(), pend()
2293 {}
2294
2295
2296 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2297         : pit(p), pend(e)
2298 {
2299         setParagraph();
2300 }
2301
2302
2303 Buffer::inset_iterator Buffer::inset_iterator_begin()
2304 {
2305         return inset_iterator(paragraphs.begin(), paragraphs.end());
2306 }
2307
2308
2309 Buffer::inset_iterator Buffer::inset_iterator_end()
2310 {
2311         return inset_iterator(paragraphs.end(), paragraphs.end());
2312 }
2313
2314
2315 Buffer::inset_iterator Buffer::inset_const_iterator_begin() const
2316 {
2317         return inset_iterator(const_cast<ParagraphList&>(paragraphs).begin(),
2318                               const_cast<ParagraphList&>(paragraphs).end());
2319 }
2320
2321
2322 Buffer::inset_iterator Buffer::inset_const_iterator_end() const
2323 {
2324         return inset_iterator(const_cast<ParagraphList&>(paragraphs).end(),
2325                               const_cast<ParagraphList&>(paragraphs).end());
2326 }
2327
2328
2329 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2330 {
2331         if (pit != pend) {
2332                 ++it;
2333                 if (it == pit->insetlist.end()) {
2334                         ++pit;
2335                         setParagraph();
2336                 }
2337         }
2338         return *this;
2339 }
2340
2341
2342 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2343 {
2344         inset_iterator tmp = *this;
2345         ++*this;
2346         return tmp;
2347 }
2348
2349
2350 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2351 {
2352         return *it->inset;
2353 }
2354
2355
2356 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2357 {
2358         return it->inset;
2359 }
2360
2361
2362 ParagraphList::iterator Buffer::inset_iterator::getPar() const
2363 {
2364         return pit;
2365 }
2366
2367
2368 lyx::pos_type Buffer::inset_iterator::getPos() const
2369 {
2370         return it->pos;
2371 }
2372
2373
2374 bool operator==(Buffer::inset_iterator const & iter1,
2375                 Buffer::inset_iterator const & iter2)
2376 {
2377         return iter1.pit == iter2.pit
2378                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2379 }
2380
2381
2382 bool operator!=(Buffer::inset_iterator const & iter1,
2383                 Buffer::inset_iterator const & iter2)
2384 {
2385         return !(iter1 == iter2);
2386 }