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