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