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