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