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