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