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