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