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