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