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