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