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