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