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