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