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