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