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