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