]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
This is one of a series of patches that will merge the layout modules development...
[lyx.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
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
15 #include "Author.h"
16 #include "BiblioInfo.h"
17 #include "BranchList.h"
18 #include "buffer_funcs.h"
19 #include "BufferList.h"
20 #include "BufferParams.h"
21 #include "Counters.h"
22 #include "Bullet.h"
23 #include "Chktex.h"
24 #include "debug.h"
25 #include "DocIterator.h"
26 #include "Encoding.h"
27 #include "ErrorList.h"
28 #include "Exporter.h"
29 #include "Format.h"
30 #include "FuncRequest.h"
31 #include "gettext.h"
32 #include "InsetIterator.h"
33 #include "Language.h"
34 #include "LaTeX.h"
35 #include "LaTeXFeatures.h"
36 #include "LyXAction.h"
37 #include "Lexer.h"
38 #include "Text.h"
39 #include "LyX.h"
40 #include "LyXRC.h"
41 #include "LyXVC.h"
42 #include "Messages.h"
43 #include "output.h"
44 #include "output_docbook.h"
45 #include "output_latex.h"
46 #include "Paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "ParIterator.h"
50 #include "sgml.h"
51 #include "TexRow.h"
52 #include "TextClassList.h"
53 #include "TexStream.h"
54 #include "TocBackend.h"
55 #include "Undo.h"
56 #include "version.h"
57
58 #include "insets/InsetBibitem.h"
59 #include "insets/InsetBibtex.h"
60 #include "insets/InsetInclude.h"
61 #include "insets/InsetText.h"
62
63 #include "mathed/MathMacroTemplate.h"
64 #include "mathed/MacroTable.h"
65 #include "mathed/MathSupport.h"
66
67 #include "frontends/alert.h"
68
69 #include "graphics/Previews.h"
70
71 #include "support/types.h"
72 #include "support/lyxalgo.h"
73 #include "support/filetools.h"
74 #include "support/fs_extras.h"
75 #include "support/gzstream.h"
76 #include "support/lyxlib.h"
77 #include "support/os.h"
78 #include "support/Path.h"
79 #include "support/textutils.h"
80 #include "support/convert.h"
81
82 #include <boost/bind.hpp>
83 #include <boost/filesystem/exception.hpp>
84 #include <boost/filesystem/operations.hpp>
85
86 #include <algorithm>
87 #include <iomanip>
88 #include <stack>
89 #include <sstream>
90 #include <fstream>
91
92 using std::endl;
93 using std::for_each;
94 using std::make_pair;
95
96 using std::ios;
97 using std::map;
98 using std::ostream;
99 using std::ostringstream;
100 using std::ofstream;
101 using std::pair;
102 using std::stack;
103 using std::vector;
104 using std::string;
105 using std::time_t;
106
107
108 namespace lyx {
109
110 using support::addName;
111 using support::bformat;
112 using support::changeExtension;
113 using support::cmd_ret;
114 using support::createBufferTmpDir;
115 using support::destroyDir;
116 using support::FileName;
117 using support::getFormatFromContents;
118 using support::libFileSearch;
119 using support::latex_path;
120 using support::ltrim;
121 using support::makeAbsPath;
122 using support::makeDisplayPath;
123 using support::makeLatexName;
124 using support::onlyFilename;
125 using support::onlyPath;
126 using support::quoteName;
127 using support::removeAutosaveFile;
128 using support::rename;
129 using support::runCommand;
130 using support::split;
131 using support::subst;
132 using support::tempName;
133 using support::trim;
134 using support::sum;
135
136 namespace Alert = frontend::Alert;
137 namespace os = support::os;
138 namespace fs = boost::filesystem;
139
140 namespace {
141
142 int const LYX_FORMAT = 280;
143
144 } // namespace anon
145
146
147 typedef std::map<string, bool> DepClean;
148
149 class Buffer::Impl
150 {
151 public:
152         Impl(Buffer & parent, FileName const & file, bool readonly);
153
154         limited_stack<Undo> undostack;
155         limited_stack<Undo> redostack;
156         BufferParams params;
157         LyXVC lyxvc;
158         string temppath;
159         TexRow texrow;
160
161         /// need to regenerate .tex?
162         DepClean dep_clean;
163
164         /// is save needed?
165         mutable bool lyx_clean;
166
167         /// is autosave needed?
168         mutable bool bak_clean;
169
170         /// is this a unnamed file (New...)?
171         bool unnamed;
172
173         /// buffer is r/o
174         bool read_only;
175
176         /// name of the file the buffer is associated with.
177         FileName filename;
178
179         /** Set to true only when the file is fully loaded.
180          *  Used to prevent the premature generation of previews
181          *  and by the citation inset.
182          */
183         bool file_fully_loaded;
184
185         /// our Text that should be wrapped in an InsetText
186         InsetText inset;
187
188         ///
189         MacroTable macros;
190
191         ///
192         TocBackend toc_backend;
193
194         /// Container for all sort of Buffer dependant errors.
195         map<string, ErrorList> errorLists;
196
197         /// timestamp and checksum used to test if the file has been externally
198         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
199         time_t timestamp_;
200         unsigned long checksum_;
201 };
202
203
204 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
205         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
206           filename(file), file_fully_loaded(false), inset(params),
207           toc_backend(&parent), timestamp_(0), checksum_(0)
208 {
209         inset.setAutoBreakRows(true);
210         lyxvc.buffer(&parent);
211         temppath = createBufferTmpDir();
212         params.filepath = onlyPath(file.absFilename());
213         // FIXME: And now do something if temppath == string(), because we
214         // assume from now on that temppath points to a valid temp dir.
215         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
216 }
217
218
219 Buffer::Buffer(string const & file, bool readonly)
220         : pimpl_(new Impl(*this, FileName(file), readonly))
221 {
222         LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
223 }
224
225
226 Buffer::~Buffer()
227 {
228         LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
229         // here the buffer should take care that it is
230         // saved properly, before it goes into the void.
231
232         Buffer * master = getMasterBuffer();
233         if (master != this && use_gui)
234                 // We are closing buf which was a child document so we
235                 // must update the labels and section numbering of its master
236                 // Buffer.
237                 updateLabels(*master);
238
239         if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
240                 Alert::warning(_("Could not remove temporary directory"),
241                         bformat(_("Could not remove the temporary directory %1$s"),
242                         from_utf8(temppath())));
243         }
244
245         // Remove any previewed LaTeX snippets associated with this buffer.
246         graphics::Previews::get().removeLoader(*this);
247
248         closing(this);
249 }
250
251
252 Text & Buffer::text() const
253 {
254         return const_cast<Text &>(pimpl_->inset.text_);
255 }
256
257
258 Inset & Buffer::inset() const
259 {
260         return const_cast<InsetText &>(pimpl_->inset);
261 }
262
263
264 limited_stack<Undo> & Buffer::undostack()
265 {
266         return pimpl_->undostack;
267 }
268
269
270 limited_stack<Undo> const & Buffer::undostack() const
271 {
272         return pimpl_->undostack;
273 }
274
275
276 limited_stack<Undo> & Buffer::redostack()
277 {
278         return pimpl_->redostack;
279 }
280
281
282 limited_stack<Undo> const & Buffer::redostack() const
283 {
284         return pimpl_->redostack;
285 }
286
287
288 BufferParams & Buffer::params()
289 {
290         return pimpl_->params;
291 }
292
293
294 BufferParams const & Buffer::params() const
295 {
296         return pimpl_->params;
297 }
298
299
300 ParagraphList & Buffer::paragraphs()
301 {
302         return text().paragraphs();
303 }
304
305
306 ParagraphList const & Buffer::paragraphs() const
307 {
308         return text().paragraphs();
309 }
310
311
312 LyXVC & Buffer::lyxvc()
313 {
314         return pimpl_->lyxvc;
315 }
316
317
318 LyXVC const & Buffer::lyxvc() const
319 {
320         return pimpl_->lyxvc;
321 }
322
323
324 string const & Buffer::temppath() const
325 {
326         return pimpl_->temppath;
327 }
328
329
330 TexRow & Buffer::texrow()
331 {
332         return pimpl_->texrow;
333 }
334
335
336 TexRow const & Buffer::texrow() const
337 {
338         return pimpl_->texrow;
339 }
340
341
342 TocBackend & Buffer::tocBackend()
343 {
344         return pimpl_->toc_backend;
345 }
346
347
348 TocBackend const & Buffer::tocBackend() const
349 {
350         return pimpl_->toc_backend;
351 }
352
353
354 string const Buffer::getLatexName(bool const no_path) const
355 {
356         string const name = changeExtension(makeLatexName(fileName()), ".tex");
357         return no_path ? onlyFilename(name) : name;
358 }
359
360
361 pair<Buffer::LogType, string> const Buffer::getLogName() const
362 {
363         string const filename = getLatexName(false);
364
365         if (filename.empty())
366                 return make_pair(Buffer::latexlog, string());
367
368         string const path = temppath();
369
370         FileName const fname(addName(temppath(),
371                                      onlyFilename(changeExtension(filename,
372                                                                   ".log"))));
373         FileName const bname(
374                 addName(path, onlyFilename(
375                         changeExtension(filename,
376                                         formats.extension("literate") + ".out"))));
377
378         // If no Latex log or Build log is newer, show Build log
379
380         if (fs::exists(bname.toFilesystemEncoding()) &&
381             (!fs::exists(fname.toFilesystemEncoding()) ||
382              fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
383                 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
384                 return make_pair(Buffer::buildlog, bname.absFilename());
385         }
386         LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
387         return make_pair(Buffer::latexlog, fname.absFilename());
388 }
389
390
391 void Buffer::setReadonly(bool const flag)
392 {
393         if (pimpl_->read_only != flag) {
394                 pimpl_->read_only = flag;
395                 readonly(flag);
396         }
397 }
398
399
400 void Buffer::setFileName(string const & newfile)
401 {
402         pimpl_->filename = makeAbsPath(newfile);
403         params().filepath = onlyPath(pimpl_->filename.absFilename());
404         setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
405         updateTitles();
406 }
407
408
409 // We'll remove this later. (Lgb)
410 namespace {
411
412 void unknownClass(string const & unknown)
413 {
414         Alert::warning(_("Unknown document class"),
415                        bformat(_("Using the default document class, because the "
416                                               "class %1$s is unknown."), from_utf8(unknown)));
417 }
418
419 } // anon
420
421
422 int Buffer::readHeader(Lexer & lex)
423 {
424         int unknown_tokens = 0;
425         int line = -1;
426         int begin_header_line = -1;
427
428         // Initialize parameters that may be/go lacking in header:
429         params().branchlist().clear();
430         params().preamble.erase();
431         params().options.erase();
432         params().float_placement.erase();
433         params().paperwidth.erase();
434         params().paperheight.erase();
435         params().leftmargin.erase();
436         params().rightmargin.erase();
437         params().topmargin.erase();
438         params().bottommargin.erase();
439         params().headheight.erase();
440         params().headsep.erase();
441         params().footskip.erase();
442         params().listings_params.clear();
443         
444         for (int i = 0; i < 4; ++i) {
445                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
446                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
447         }
448
449         ErrorList & errorList = pimpl_->errorLists["Parse"];
450
451         while (lex.isOK()) {
452                 lex.next();
453                 string const token = lex.getString();
454
455                 if (token.empty())
456                         continue;
457
458                 if (token == "\\end_header")
459                         break;
460
461                 ++line;
462                 if (token == "\\begin_header") {
463                         begin_header_line = line;
464                         continue;
465                 }
466
467                 LYXERR(Debug::PARSER) << "Handling document header token: `"
468                                       << token << '\'' << endl;
469
470                 string unknown = params().readToken(lex, token);
471                 if (!unknown.empty()) {
472                         if (unknown[0] != '\\' && token == "\\textclass") {
473                                 unknownClass(unknown);
474                         } else {
475                                 ++unknown_tokens;
476                                 docstring const s = bformat(_("Unknown token: "
477                                                                         "%1$s %2$s\n"),
478                                                          from_utf8(token),
479                                                          lex.getDocString());
480                                 errorList.push_back(ErrorItem(_("Document header error"),
481                                         s, -1, 0, 0));
482                         }
483                 }
484         }
485         if (begin_header_line) {
486                 docstring const s = _("\\begin_header is missing");
487                 errorList.push_back(ErrorItem(_("Document header error"),
488                         s, -1, 0, 0));
489         }
490
491         return unknown_tokens;
492 }
493
494
495 // Uwe C. Schroeder
496 // changed to be public and have one parameter
497 // Returns false if "\end_document" is not read (Asger)
498 bool Buffer::readDocument(Lexer & lex)
499 {
500         ErrorList & errorList = pimpl_->errorLists["Parse"];
501         errorList.clear();
502
503         lex.next();
504         string const token = lex.getString();
505         if (token != "\\begin_document") {
506                 docstring const s = _("\\begin_document is missing");
507                 errorList.push_back(ErrorItem(_("Document header error"),
508                         s, -1, 0, 0));
509         }
510
511         // we are reading in a brand new document
512         BOOST_ASSERT(paragraphs().empty());
513
514         readHeader(lex);
515         if (!params().getTextClass().load(filePath())) {
516                 string theclass = params().getTextClass().name();
517                 Alert::error(_("Can't load document class"), bformat(
518                         _("Using the default document class, because the "
519                                      "class %1$s could not be loaded."), from_utf8(theclass)));
520                 params().setBaseClass(defaultTextclass());
521         }
522
523         if (params().outputChanges) {
524                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
525                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
526                                   LaTeXFeatures::isAvailable("xcolor");
527
528                 if (!dvipost && !xcolorsoul) {
529                         Alert::warning(_("Changes not shown in LaTeX output"),
530                                        _("Changes will not be highlighted in LaTeX output, "
531                                          "because neither dvipost nor xcolor/soul are installed.\n"
532                                          "Please install these packages or redefine "
533                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
534                 } else if (!xcolorsoul) {
535                         Alert::warning(_("Changes not shown in LaTeX output"),
536                                        _("Changes will not be highlighted in LaTeX output "
537                                          "when using pdflatex, because xcolor and soul are not installed.\n"
538                                          "Please install both packages or redefine "
539                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
540                 }
541         }
542
543         bool const res = text().read(*this, lex, errorList);
544         for_each(text().paragraphs().begin(),
545                  text().paragraphs().end(),
546                  bind(&Paragraph::setInsetOwner, _1, &inset()));
547
548         return res;
549 }
550
551
552 // needed to insert the selection
553 void Buffer::insertStringAsLines(ParagraphList & pars,
554         pit_type & pit, pos_type & pos,
555         Font const & fn, docstring const & str, bool autobreakrows)
556 {
557         Font font = fn;
558
559         // insert the string, don't insert doublespace
560         bool space_inserted = true;
561         for (docstring::const_iterator cit = str.begin();
562             cit != str.end(); ++cit) {
563                 Paragraph & par = pars[pit];
564                 if (*cit == '\n') {
565                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
566                                 breakParagraph(params(), pars, pit, pos,
567                                                par.layout()->isEnvironment());
568                                 ++pit;
569                                 pos = 0;
570                                 space_inserted = true;
571                         } else {
572                                 continue;
573                         }
574                         // do not insert consecutive spaces if !free_spacing
575                 } else if ((*cit == ' ' || *cit == '\t') &&
576                            space_inserted && !par.isFreeSpacing()) {
577                         continue;
578                 } else if (*cit == '\t') {
579                         if (!par.isFreeSpacing()) {
580                                 // tabs are like spaces here
581                                 par.insertChar(pos, ' ', font, params().trackChanges);
582                                 ++pos;
583                                 space_inserted = true;
584                         } else {
585                                 const pos_type n = 8 - pos % 8;
586                                 for (pos_type i = 0; i < n; ++i) {
587                                         par.insertChar(pos, ' ', font, params().trackChanges);
588                                         ++pos;
589                                 }
590                                 space_inserted = true;
591                         }
592                 } else if (!isPrintable(*cit)) {
593                         // Ignore unprintables
594                         continue;
595                 } else {
596                         // just insert the character
597                         par.insertChar(pos, *cit, font, params().trackChanges);
598                         ++pos;
599                         space_inserted = (*cit == ' ');
600                 }
601
602         }
603 }
604
605
606 bool Buffer::readString(std::string const & s)
607 {
608         params().compressed = false;
609
610         // remove dummy empty par
611         paragraphs().clear();
612         Lexer lex(0, 0);
613         std::istringstream is(s);
614         lex.setStream(is);
615         FileName const name(tempName());
616         switch (readFile(lex, name, true)) {
617         case failure:
618                 return false;
619         case wrongversion: {
620                 // We need to call lyx2lyx, so write the input to a file
621                 std::ofstream os(name.toFilesystemEncoding().c_str());
622                 os << s;
623                 os.close();
624                 return readFile(name);
625         }
626         case success:
627                 break;
628         }
629
630         return true;
631 }
632
633
634 bool Buffer::readFile(FileName const & filename)
635 {
636         // Check if the file is compressed.
637         string const format = getFormatFromContents(filename);
638         if (format == "gzip" || format == "zip" || format == "compress") {
639                 params().compressed = true;
640         }
641
642         // remove dummy empty par
643         paragraphs().clear();
644         Lexer lex(0, 0);
645         lex.setFile(filename);
646         if (readFile(lex, filename) != success)
647                 return false;
648
649         return true;
650 }
651
652
653 bool Buffer::fully_loaded() const
654 {
655         return pimpl_->file_fully_loaded;
656 }
657
658
659 void Buffer::fully_loaded(bool const value)
660 {
661         pimpl_->file_fully_loaded = value;
662 }
663
664
665 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
666                 bool fromstring)
667 {
668         BOOST_ASSERT(!filename.empty());
669
670         if (!lex.isOK()) {
671                 Alert::error(_("Document could not be read"),
672                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
673                 return failure;
674         }
675
676         lex.next();
677         string const token(lex.getString());
678
679         if (!lex) {
680                 Alert::error(_("Document could not be read"),
681                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
682                 return failure;
683         }
684
685         // the first token _must_ be...
686         if (token != "\\lyxformat") {
687                 lyxerr << "Token: " << token << endl;
688
689                 Alert::error(_("Document format failure"),
690                              bformat(_("%1$s is not a LyX document."),
691                                        from_utf8(filename.absFilename())));
692                 return failure;
693         }
694
695         lex.next();
696         string tmp_format = lex.getString();
697         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
698         // if present remove ".," from string.
699         string::size_type dot = tmp_format.find_first_of(".,");
700         //lyxerr << "           dot found at " << dot << endl;
701         if (dot != string::npos)
702                         tmp_format.erase(dot, 1);
703         int const file_format = convert<int>(tmp_format);
704         //lyxerr << "format: " << file_format << endl;
705
706         if (file_format != LYX_FORMAT) {
707
708                 if (fromstring)
709                         // lyx2lyx would fail
710                         return wrongversion;
711
712                 FileName const tmpfile(tempName());
713                 if (tmpfile.empty()) {
714                         Alert::error(_("Conversion failed"),
715                                      bformat(_("%1$s is from a different"
716                                               " version of LyX, but a temporary"
717                                               " file for converting it could"
718                                                             " not be created."),
719                                               from_utf8(filename.absFilename())));
720                         return failure;
721                 }
722                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
723                 if (lyx2lyx.empty()) {
724                         Alert::error(_("Conversion script not found"),
725                                      bformat(_("%1$s is from a different"
726                                                " version of LyX, but the"
727                                                " conversion script lyx2lyx"
728                                                             " could not be found."),
729                                                from_utf8(filename.absFilename())));
730                         return failure;
731                 }
732                 ostringstream command;
733                 command << os::python()
734                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
735                         << " -t " << convert<string>(LYX_FORMAT)
736                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
737                         << ' ' << quoteName(filename.toFilesystemEncoding());
738                 string const command_str = command.str();
739
740                 LYXERR(Debug::INFO) << "Running '"
741                                     << command_str << '\''
742                                     << endl;
743
744                 cmd_ret const ret = runCommand(command_str);
745                 if (ret.first != 0) {
746                         Alert::error(_("Conversion script failed"),
747                                      bformat(_("%1$s is from a different version"
748                                               " of LyX, but the lyx2lyx script"
749                                                             " failed to convert it."),
750                                               from_utf8(filename.absFilename())));
751                         return failure;
752                 } else {
753                         bool const ret = readFile(tmpfile);
754                         // Do stuff with tmpfile name and buffer name here.
755                         return ret ? success : failure;
756                 }
757
758         }
759
760         if (readDocument(lex)) {
761                 Alert::error(_("Document format failure"),
762                              bformat(_("%1$s ended unexpectedly, which means"
763                                                     " that it is probably corrupted."),
764                                        from_utf8(filename.absFilename())));
765         }
766
767         //lyxerr << "removing " << MacroTable::localMacros().size()
768         //      << " temporary macro entries" << endl;
769         //MacroTable::localMacros().clear();
770
771         pimpl_->file_fully_loaded = true;
772         // save the timestamp and checksum of disk file
773         pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
774         pimpl_->checksum_ = sum(filename);
775         return success;
776 }
777
778
779 // Should probably be moved to somewhere else: BufferView? LyXView?
780 bool Buffer::save() const
781 {
782         // We don't need autosaves in the immediate future. (Asger)
783         resetAutosaveTimers();
784
785         string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
786
787         FileName backupName;
788         bool madeBackup = false;
789
790         // make a backup if the file already exists
791         if (lyxrc.make_backup && fs::exists(encodedFilename)) {
792                 backupName = FileName(fileName() + '~');
793                 if (!lyxrc.backupdir_path.empty())
794                         backupName = FileName(addName(lyxrc.backupdir_path,
795                                               subst(os::internal_path(backupName.absFilename()), '/', '!')));
796
797                 try {
798                         fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
799                         madeBackup = true;
800                 } catch (fs::filesystem_error const & fe) {
801                         Alert::error(_("Backup failure"),
802                                      bformat(_("Cannot create backup file %1$s.\n"
803                                                "Please check whether the directory exists and is writeable."),
804                                              from_utf8(backupName.absFilename())));
805                         LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
806                 }
807         }
808
809         // ask if the disk file has been externally modified (use checksum method)
810         if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
811                 docstring const file = makeDisplayPath(fileName(), 20);
812                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
813                                                              "you want to overwrite this file?"), file);
814                 int const ret = Alert::prompt(_("Overwrite modified file?"),
815                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
816                 if (ret == 1)
817                         return false;
818         }
819
820         if (writeFile(pimpl_->filename)) {
821                 markClean();
822                 removeAutosaveFile(fileName());
823                 pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
824                 pimpl_->checksum_ = sum(pimpl_->filename);
825                 return true;
826         } else {
827                 // Saving failed, so backup is not backup
828                 if (madeBackup)
829                         rename(backupName, pimpl_->filename);
830                 return false;
831         }
832 }
833
834
835 bool Buffer::writeFile(FileName const & fname) const
836 {
837         if (pimpl_->read_only && fname == pimpl_->filename)
838                 return false;
839
840         bool retval = false;
841
842         if (params().compressed) {
843                 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
844                 if (!ofs)
845                         return false;
846
847                 retval = write(ofs);
848         } else {
849                 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
850                 if (!ofs)
851                         return false;
852
853                 retval = write(ofs);
854         }
855
856         return retval;
857 }
858
859
860 bool Buffer::write(ostream & ofs) const
861 {
862 #ifdef HAVE_LOCALE
863         // Use the standard "C" locale for file output.
864         ofs.imbue(std::locale::classic());
865 #endif
866
867         // The top of the file should not be written by params().
868
869         // write out a comment in the top of the file
870         ofs << "#LyX " << lyx_version
871             << " created this file. For more info see http://www.lyx.org/\n"
872             << "\\lyxformat " << LYX_FORMAT << "\n"
873             << "\\begin_document\n";
874
875
876         /// For each author, set 'used' to true if there is a change
877         /// by this author in the document; otherwise set it to 'false'.
878         AuthorList::Authors::const_iterator a_it = params().authors().begin();
879         AuthorList::Authors::const_iterator a_end = params().authors().end();
880         for (; a_it != a_end; ++a_it)
881                 a_it->second.used(false);
882
883         ParIterator const end = par_iterator_end();
884         ParIterator it = par_iterator_begin();
885         for ( ; it != end; ++it)
886                 it->checkAuthors(params().authors());
887
888         // now write out the buffer parameters.
889         ofs << "\\begin_header\n";
890         params().writeFile(ofs);
891         ofs << "\\end_header\n";
892
893         // write the text
894         ofs << "\n\\begin_body\n";
895         text().write(*this, ofs);
896         ofs << "\n\\end_body\n";
897
898         // Write marker that shows file is complete
899         ofs << "\\end_document" << endl;
900
901         // Shouldn't really be needed....
902         //ofs.close();
903
904         // how to check if close went ok?
905         // Following is an attempt... (BE 20001011)
906
907         // good() returns false if any error occured, including some
908         //        formatting error.
909         // bad()  returns true if something bad happened in the buffer,
910         //        which should include file system full errors.
911
912         bool status = true;
913         if (!ofs) {
914                 status = false;
915                 lyxerr << "File was not closed properly." << endl;
916         }
917
918         return status;
919 }
920
921
922 bool Buffer::makeLaTeXFile(FileName const & fname,
923                            string const & original_path,
924                            OutputParams const & runparams,
925                            bool output_preamble, bool output_body)
926 {
927         string const encoding = runparams.encoding->iconvName();
928         LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
929                 << encoding << "..." << endl;
930
931         odocfstream ofs(encoding);
932         if (!openFileWrite(ofs, fname))
933                 return false;
934
935         //TexStream ts(ofs.rdbuf(), &texrow());
936
937         bool failed_export = false;
938         try {
939                 texrow().reset();
940                 writeLaTeXSource(ofs, original_path,
941                       runparams, output_preamble, output_body);
942         }
943         catch (iconv_codecvt_facet_exception & e) {
944                 lyxerr << "Caught iconv exception: " << e.what() << endl;
945                 failed_export = true;
946         }
947         catch (std::exception const & e) {
948                 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
949                 failed_export = true;
950         }
951         catch (...) {
952                 lyxerr << "Caught some really weird exception..." << endl;
953                 LyX::cref().emergencyCleanup();
954                 abort();
955         }
956
957         ofs.close();
958         if (ofs.fail()) {
959                 failed_export = true;
960                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
961         }
962
963         if (failed_export) {
964                 Alert::error(_("Encoding error"),
965                         _("Some characters of your document are probably not "
966                         "representable in the chosen encoding.\n"
967                         "Changing the document encoding to utf8 could help."));
968                 return false;
969         }
970         return true;
971 }
972
973
974 void Buffer::writeLaTeXSource(odocstream & os,
975                            string const & original_path,
976                            OutputParams const & runparams_in,
977                            bool const output_preamble, bool const output_body)
978 {
979         OutputParams runparams = runparams_in;
980
981         // validate the buffer.
982         LYXERR(Debug::LATEX) << "  Validating buffer..." << endl;
983         LaTeXFeatures features(*this, params(), runparams);
984         validate(features);
985         LYXERR(Debug::LATEX) << "  Buffer validation done." << endl;
986
987         // The starting paragraph of the coming rows is the
988         // first paragraph of the document. (Asger)
989         if (output_preamble && runparams.nice) {
990                 os << "%% LyX " << lyx_version << " created this file.  "
991                         "For more info, see http://www.lyx.org/.\n"
992                         "%% Do not edit unless you really know what "
993                         "you are doing.\n";
994                 texrow().newline();
995                 texrow().newline();
996         }
997         LYXERR(Debug::INFO) << "lyx document header finished" << endl;
998         // There are a few differences between nice LaTeX and usual files:
999         // usual is \batchmode and has a
1000         // special input@path to allow the including of figures
1001         // with either \input or \includegraphics (what figinsets do).
1002         // input@path is set when the actual parameter
1003         // original_path is set. This is done for usual tex-file, but not
1004         // for nice-latex-file. (Matthias 250696)
1005         // Note that input@path is only needed for something the user does
1006         // in the preamble, included .tex files or ERT, files included by
1007         // LyX work without it.
1008         if (output_preamble) {
1009                 if (!runparams.nice) {
1010                         // code for usual, NOT nice-latex-file
1011                         os << "\\batchmode\n"; // changed
1012                         // from \nonstopmode
1013                         texrow().newline();
1014                 }
1015                 if (!original_path.empty()) {
1016                         // FIXME UNICODE
1017                         // We don't know the encoding of inputpath
1018                         docstring const inputpath = from_utf8(latex_path(original_path));
1019                         os << "\\makeatletter\n"
1020                            << "\\def\\input@path{{"
1021                            << inputpath << "/}}\n"
1022                            << "\\makeatother\n";
1023                         texrow().newline();
1024                         texrow().newline();
1025                         texrow().newline();
1026                 }
1027
1028                 // Write the preamble
1029                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1030
1031                 if (!output_body)
1032                         return;
1033
1034                 // make the body.
1035                 os << "\\begin{document}\n";
1036                 texrow().newline();
1037         } // output_preamble
1038
1039         texrow().start(paragraphs().begin()->id(), 0);
1040         
1041         LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1042
1043         if (!lyxrc.language_auto_begin &&
1044             !params().language->babel().empty()) {
1045                 // FIXME UNICODE
1046                 os << from_utf8(subst(lyxrc.language_command_begin,
1047                                            "$$lang",
1048                                            params().language->babel()))
1049                    << '\n';
1050                 texrow().newline();
1051         }
1052
1053         Encoding const & encoding = params().encoding();
1054         if (encoding.package() == Encoding::CJK) {
1055                 // Open a CJK environment, since in contrast to the encodings
1056                 // handled by inputenc the document encoding is not set in
1057                 // the preamble if it is handled by CJK.sty.
1058                 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1059                    << "}{}\n";
1060                 texrow().newline();
1061         }
1062
1063         // if we are doing a real file with body, even if this is the
1064         // child of some other buffer, let's cut the link here.
1065         // This happens for example if only a child document is printed.
1066         string save_parentname;
1067         if (output_preamble) {
1068                 save_parentname = params().parentname;
1069                 params().parentname.erase();
1070         }
1071
1072         loadChildDocuments(*this);
1073
1074         // the real stuff
1075         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1076
1077         // Restore the parenthood if needed
1078         if (output_preamble)
1079                 params().parentname = save_parentname;
1080
1081         // add this just in case after all the paragraphs
1082         os << endl;
1083         texrow().newline();
1084
1085         if (encoding.package() == Encoding::CJK) {
1086                 // Close the open CJK environment.
1087                 // latexParagraphs will have opened one even if the last text
1088                 // was not CJK.
1089                 os << "\\end{CJK}\n";
1090                 texrow().newline();
1091         }
1092
1093         if (!lyxrc.language_auto_end &&
1094             !params().language->babel().empty()) {
1095                 os << from_utf8(subst(lyxrc.language_command_end,
1096                                            "$$lang",
1097                                            params().language->babel()))
1098                    << '\n';
1099                 texrow().newline();
1100         }
1101
1102         if (output_preamble) {
1103                 os << "\\end{document}\n";
1104                 texrow().newline();
1105
1106                 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1107         } else {
1108                 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1109                                      << endl;
1110         }
1111         runparams_in.encoding = runparams.encoding;
1112
1113         // Just to be sure. (Asger)
1114         texrow().newline();
1115
1116         LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1117         LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1118                             << '.' << endl;
1119 }
1120
1121
1122 bool Buffer::isLatex() const
1123 {
1124         return params().getTextClass().outputType() == LATEX;
1125 }
1126
1127
1128 bool Buffer::isLiterate() const
1129 {
1130         return params().getTextClass().outputType() == LITERATE;
1131 }
1132
1133
1134 bool Buffer::isDocBook() const
1135 {
1136         return params().getTextClass().outputType() == DOCBOOK;
1137 }
1138
1139
1140 void Buffer::makeDocBookFile(FileName const & fname,
1141                               OutputParams const & runparams,
1142                               bool const body_only)
1143 {
1144         LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1145
1146         //ofstream ofs;
1147         odocfstream ofs;
1148         if (!openFileWrite(ofs, fname))
1149                 return;
1150
1151         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1152
1153         ofs.close();
1154         if (ofs.fail())
1155                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1156 }
1157
1158
1159 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1160                              OutputParams const & runparams,
1161                              bool const only_body)
1162 {
1163         LaTeXFeatures features(*this, params(), runparams);
1164         validate(features);
1165
1166         texrow().reset();
1167
1168         TextClass const & tclass = params().getTextClass();
1169         string const top_element = tclass.latexname();
1170
1171         if (!only_body) {
1172                 if (runparams.flavor == OutputParams::XML)
1173                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1174
1175                 // FIXME UNICODE
1176                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1177
1178                 // FIXME UNICODE
1179                 if (! tclass.class_header().empty())
1180                         os << from_ascii(tclass.class_header());
1181                 else if (runparams.flavor == OutputParams::XML)
1182                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1183                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1184                 else
1185                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1186
1187                 docstring preamble = from_utf8(params().preamble);
1188                 if (runparams.flavor != OutputParams::XML ) {
1189                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1190                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1191                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1192                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1193                 }
1194
1195                 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1196                          : fname;
1197                 preamble += features.getIncludedFiles(name);
1198                 preamble += features.getLyXSGMLEntities();
1199
1200                 if (!preamble.empty()) {
1201                         os << "\n [ " << preamble << " ]";
1202                 }
1203                 os << ">\n\n";
1204         }
1205
1206         string top = top_element;
1207         top += " lang=\"";
1208         if (runparams.flavor == OutputParams::XML)
1209                 top += params().language->code();
1210         else
1211                 top += params().language->code().substr(0,2);
1212         top += '"';
1213
1214         if (!params().options.empty()) {
1215                 top += ' ';
1216                 top += params().options;
1217         }
1218
1219         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1220             << " file was created by LyX " << lyx_version
1221             << "\n  See http://www.lyx.org/ for more information -->\n";
1222
1223         params().getTextClass().counters().reset();
1224
1225         loadChildDocuments(*this);
1226
1227         sgml::openTag(os, top);
1228         os << '\n';
1229         docbookParagraphs(paragraphs(), *this, os, runparams);
1230         sgml::closeTag(os, top_element);
1231 }
1232
1233
1234 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1235 // Other flags: -wall -v0 -x
1236 int Buffer::runChktex()
1237 {
1238         busy(true);
1239
1240         // get LaTeX-Filename
1241         FileName const path(temppath());
1242         string const name = addName(path.absFilename(), getLatexName());
1243         string const org_path = filePath();
1244
1245         support::Path p(path); // path to LaTeX file
1246         message(_("Running chktex..."));
1247
1248         // Generate the LaTeX file if neccessary
1249         OutputParams runparams(&params().encoding());
1250         runparams.flavor = OutputParams::LATEX;
1251         runparams.nice = false;
1252         makeLaTeXFile(FileName(name), org_path, runparams);
1253
1254         TeXErrors terr;
1255         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1256         int const res = chktex.run(terr); // run chktex
1257
1258         if (res == -1) {
1259                 Alert::error(_("chktex failure"),
1260                              _("Could not run chktex successfully."));
1261         } else if (res > 0) {
1262                 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1263                 // Clear out old errors
1264                 errorList.clear();
1265                 // Fill-in the error list with the TeX errors
1266                 bufferErrors(*this, terr, errorList);
1267         }
1268
1269         busy(false);
1270
1271         errors("ChkTeX");
1272
1273         return res;
1274 }
1275
1276
1277 void Buffer::validate(LaTeXFeatures & features) const
1278 {
1279         TextClass const & tclass = params().getTextClass();
1280
1281         if (params().outputChanges) {
1282                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1283                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1284                                   LaTeXFeatures::isAvailable("xcolor");
1285
1286                 if (features.runparams().flavor == OutputParams::LATEX) {
1287                         if (dvipost) {
1288                                 features.require("ct-dvipost");
1289                                 features.require("dvipost");
1290                         } else if (xcolorsoul) {
1291                                 features.require("ct-xcolor-soul");
1292                                 features.require("soul");
1293                                 features.require("xcolor");
1294                         } else {
1295                                 features.require("ct-none");
1296                         }
1297                 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1298                         if (xcolorsoul) {
1299                                 features.require("ct-xcolor-soul");
1300                                 features.require("soul");
1301                                 features.require("xcolor");
1302                                 features.require("pdfcolmk"); // improves color handling in PDF output
1303                         } else {
1304                                 features.require("ct-none");
1305                         }
1306                 }
1307         }
1308
1309         // AMS Style is at document level
1310         if (params().use_amsmath == BufferParams::package_on
1311             || tclass.provides("amsmath"))
1312                 features.require("amsmath");
1313         if (params().use_esint == BufferParams::package_on)
1314                 features.require("esint");
1315
1316         loadChildDocuments(*this);
1317
1318         for_each(paragraphs().begin(), paragraphs().end(),
1319                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1320
1321         // the bullet shapes are buffer level not paragraph level
1322         // so they are tested here
1323         for (int i = 0; i < 4; ++i) {
1324                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1325                         int const font = params().user_defined_bullet(i).getFont();
1326                         if (font == 0) {
1327                                 int const c = params()
1328                                         .user_defined_bullet(i)
1329                                         .getCharacter();
1330                                 if (c == 16
1331                                    || c == 17
1332                                    || c == 25
1333                                    || c == 26
1334                                    || c == 31) {
1335                                         features.require("latexsym");
1336                                 }
1337                         } else if (font == 1) {
1338                                 features.require("amssymb");
1339                         } else if ((font >= 2 && font <= 5)) {
1340                                 features.require("pifont");
1341                         }
1342                 }
1343         }
1344
1345         if (lyxerr.debugging(Debug::LATEX)) {
1346                 features.showStruct();
1347         }
1348 }
1349
1350
1351 void Buffer::getLabelList(vector<docstring> & list) const
1352 {
1353         /// if this is a child document and the parent is already loaded
1354         /// Use the parent's list instead  [ale990407]
1355         Buffer const * tmp = getMasterBuffer();
1356         if (!tmp) {
1357                 lyxerr << "getMasterBuffer() failed!" << endl;
1358                 BOOST_ASSERT(tmp);
1359         }
1360         if (tmp != this) {
1361                 tmp->getLabelList(list);
1362                 return;
1363         }
1364
1365         loadChildDocuments(*this);
1366
1367         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1368                 it.nextInset()->getLabelList(*this, list);
1369 }
1370
1371
1372 void Buffer::updateBibfilesCache()
1373 {
1374         // if this is a child document and the parent is already loaded
1375         // update the parent's cache instead
1376         Buffer * tmp = getMasterBuffer();
1377         BOOST_ASSERT(tmp);
1378         if (tmp != this) {
1379                 tmp->updateBibfilesCache();
1380                 return;
1381         }
1382
1383         bibfilesCache_.clear();
1384         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1385                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1386                         InsetBibtex const & inset =
1387                                 static_cast<InsetBibtex const &>(*it);
1388                         vector<FileName> const bibfiles = inset.getFiles(*this);
1389                         bibfilesCache_.insert(bibfilesCache_.end(),
1390                                 bibfiles.begin(),
1391                                 bibfiles.end());
1392                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1393                         InsetInclude & inset =
1394                                 static_cast<InsetInclude &>(*it);
1395                         inset.updateBibfilesCache(*this);
1396                         vector<FileName> const & bibfiles =
1397                                         inset.getBibfilesCache(*this);
1398                         bibfilesCache_.insert(bibfilesCache_.end(),
1399                                 bibfiles.begin(),
1400                                 bibfiles.end());
1401                 }
1402         }
1403 }
1404
1405
1406 vector<FileName> const & Buffer::getBibfilesCache() const
1407 {
1408         // if this is a child document and the parent is already loaded
1409         // use the parent's cache instead
1410         Buffer const * tmp = getMasterBuffer();
1411         BOOST_ASSERT(tmp);
1412         if (tmp != this)
1413                 return tmp->getBibfilesCache();
1414
1415         // We update the cache when first used instead of at loading time.
1416         if (bibfilesCache_.empty())
1417                 const_cast<Buffer *>(this)->updateBibfilesCache();
1418
1419         return bibfilesCache_;
1420 }
1421
1422
1423 bool Buffer::isDepClean(string const & name) const
1424 {
1425         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1426         if (it == pimpl_->dep_clean.end())
1427                 return true;
1428         return it->second;
1429 }
1430
1431
1432 void Buffer::markDepClean(string const & name)
1433 {
1434         pimpl_->dep_clean[name] = true;
1435 }
1436
1437
1438 bool Buffer::dispatch(string const & command, bool * result)
1439 {
1440         return dispatch(lyxaction.lookupFunc(command), result);
1441 }
1442
1443
1444 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1445 {
1446         bool dispatched = true;
1447
1448         switch (func.action) {
1449                 case LFUN_BUFFER_EXPORT: {
1450                         bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1451                         if (result)
1452                                 *result = tmp;
1453                         break;
1454                 }
1455
1456                 default:
1457                         dispatched = false;
1458         }
1459         return dispatched;
1460 }
1461
1462
1463 void Buffer::changeLanguage(Language const * from, Language const * to)
1464 {
1465         BOOST_ASSERT(from);
1466         BOOST_ASSERT(to);
1467
1468         for_each(par_iterator_begin(),
1469                  par_iterator_end(),
1470                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1471
1472         text().current_font.setLanguage(to);
1473         text().real_current_font.setLanguage(to);
1474 }
1475
1476
1477 bool Buffer::isMultiLingual() const
1478 {
1479         ParConstIterator end = par_iterator_end();
1480         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1481                 if (it->isMultiLingual(params()))
1482                         return true;
1483
1484         return false;
1485 }
1486
1487
1488 ParIterator Buffer::getParFromID(int const id) const
1489 {
1490         ParConstIterator it = par_iterator_begin();
1491         ParConstIterator const end = par_iterator_end();
1492
1493         if (id < 0) {
1494                 // John says this is called with id == -1 from undo
1495                 lyxerr << "getParFromID(), id: " << id << endl;
1496                 return end;
1497         }
1498
1499         for (; it != end; ++it)
1500                 if (it->id() == id)
1501                         return it;
1502
1503         return end;
1504 }
1505
1506
1507 bool Buffer::hasParWithID(int const id) const
1508 {
1509         ParConstIterator const it = getParFromID(id);
1510         return it != par_iterator_end();
1511 }
1512
1513
1514 ParIterator Buffer::par_iterator_begin()
1515 {
1516         return lyx::par_iterator_begin(inset());
1517 }
1518
1519
1520 ParIterator Buffer::par_iterator_end()
1521 {
1522         return lyx::par_iterator_end(inset());
1523 }
1524
1525
1526 ParConstIterator Buffer::par_iterator_begin() const
1527 {
1528         return lyx::par_const_iterator_begin(inset());
1529 }
1530
1531
1532 ParConstIterator Buffer::par_iterator_end() const
1533 {
1534         return lyx::par_const_iterator_end(inset());
1535 }
1536
1537
1538 Language const * Buffer::getLanguage() const
1539 {
1540         return params().language;
1541 }
1542
1543
1544 docstring const Buffer::B_(string const & l10n) const
1545 {
1546         return params().B_(l10n);
1547 }
1548
1549
1550 bool Buffer::isClean() const
1551 {
1552         return pimpl_->lyx_clean;
1553 }
1554
1555
1556 bool Buffer::isBakClean() const
1557 {
1558         return pimpl_->bak_clean;
1559 }
1560
1561
1562 bool Buffer::isExternallyModified(CheckMethod method) const
1563 {
1564         BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1565         // if method == timestamp, check timestamp before checksum
1566         return (method == checksum_method 
1567                 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1568                 && pimpl_->checksum_ != sum(pimpl_->filename);
1569 }
1570
1571
1572 void Buffer::markClean() const
1573 {
1574         if (!pimpl_->lyx_clean) {
1575                 pimpl_->lyx_clean = true;
1576                 updateTitles();
1577         }
1578         // if the .lyx file has been saved, we don't need an
1579         // autosave
1580         pimpl_->bak_clean = true;
1581 }
1582
1583
1584 void Buffer::markBakClean()
1585 {
1586         pimpl_->bak_clean = true;
1587 }
1588
1589
1590 void Buffer::setUnnamed(bool flag)
1591 {
1592         pimpl_->unnamed = flag;
1593 }
1594
1595
1596 bool Buffer::isUnnamed() const
1597 {
1598         return pimpl_->unnamed;
1599 }
1600
1601
1602 // FIXME: this function should be moved to buffer_pimpl.C
1603 void Buffer::markDirty()
1604 {
1605         if (pimpl_->lyx_clean) {
1606                 pimpl_->lyx_clean = false;
1607                 updateTitles();
1608         }
1609         pimpl_->bak_clean = false;
1610
1611         DepClean::iterator it = pimpl_->dep_clean.begin();
1612         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1613
1614         for (; it != end; ++it)
1615                 it->second = false;
1616 }
1617
1618
1619 string const Buffer::fileName() const
1620 {
1621         return pimpl_->filename.absFilename();
1622 }
1623
1624
1625 string const & Buffer::filePath() const
1626 {
1627         return params().filepath;
1628 }
1629
1630
1631 bool Buffer::isReadonly() const
1632 {
1633         return pimpl_->read_only;
1634 }
1635
1636
1637 void Buffer::setParentName(string const & name)
1638 {
1639         if (name == pimpl_->filename.absFilename())
1640                 // Avoids recursive include.
1641                 params().parentname.clear();
1642         else
1643                 params().parentname = name;
1644 }
1645
1646
1647 Buffer const * Buffer::getMasterBuffer() const
1648 {
1649         if (!params().parentname.empty()
1650             && theBufferList().exists(params().parentname)) {
1651                 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1652                 //We need to check if the parent is us...
1653                 //FIXME RECURSIVE INCLUDE
1654                 //This is not sufficient, since recursive includes could be downstream.
1655                 if (buf && buf != this)
1656                         return buf->getMasterBuffer();
1657         }
1658
1659         return this;
1660 }
1661
1662
1663 Buffer * Buffer::getMasterBuffer()
1664 {
1665         if (!params().parentname.empty()
1666             && theBufferList().exists(params().parentname)) {
1667                 Buffer * buf = theBufferList().getBuffer(params().parentname);
1668                 if (buf)
1669                         return buf->getMasterBuffer();
1670         }
1671
1672         return this;
1673 }
1674
1675
1676 MacroData const & Buffer::getMacro(docstring const & name) const
1677 {
1678         return pimpl_->macros.get(name);
1679 }
1680
1681
1682 bool Buffer::hasMacro(docstring const & name) const
1683 {
1684         return pimpl_->macros.has(name);
1685 }
1686
1687
1688 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1689 {
1690         MacroTable::globalMacros().insert(name, data);
1691         pimpl_->macros.insert(name, data);
1692 }
1693
1694
1695 void Buffer::buildMacros()
1696 {
1697         // Start with global table.
1698         pimpl_->macros = MacroTable::globalMacros();
1699
1700         // Now add our own.
1701         ParagraphList const & pars = text().paragraphs();
1702         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1703                 //lyxerr << "searching main par " << i
1704                 //      << " for macro definitions" << std::endl;
1705                 InsetList const & insets = pars[i].insetlist;
1706                 InsetList::const_iterator it = insets.begin();
1707                 InsetList::const_iterator end = insets.end();
1708                 for ( ; it != end; ++it) {
1709                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1710                         if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1711                                 MathMacroTemplate const & mac
1712                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1713                                 insertMacro(mac.name(), mac.asMacroData());
1714                         }
1715                 }
1716         }
1717 }
1718
1719
1720 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1721         Inset::Code code)
1722 {
1723         //FIXME: This does not work for child documents yet.
1724         BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1725         // Check if the label 'from' appears more than once
1726         vector<docstring> labels;
1727
1728         if (code == Inset::CITE_CODE) {
1729                 BiblioInfo keys;
1730                 keys.fillWithBibKeys(this);
1731                 BiblioInfo::const_iterator bit  = keys.begin();
1732                 BiblioInfo::const_iterator bend = keys.end();
1733
1734                 for (; bit != bend; ++bit)
1735                         // FIXME UNICODE
1736                         labels.push_back(bit->first);
1737         } else
1738                 getLabelList(labels);
1739
1740         if (std::count(labels.begin(), labels.end(), from) > 1)
1741                 return;
1742
1743         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1744                 if (it->lyxCode() == code) {
1745                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
1746                         inset.replaceContents(to_utf8(from), to_utf8(to));
1747                 }
1748         }
1749 }
1750
1751
1752 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1753         pit_type par_end, bool full_source)
1754 {
1755         OutputParams runparams(&params().encoding());
1756         runparams.nice = true;
1757         runparams.flavor = OutputParams::LATEX;
1758         runparams.linelen = lyxrc.plaintext_linelen;
1759         // No side effect of file copying and image conversion
1760         runparams.dryrun = true;
1761
1762         texrow().reset();
1763         if (full_source) {
1764                 os << "% " << _("Preview source code") << "\n\n";
1765                 texrow().newline();
1766                 texrow().newline();
1767                 if (isLatex())
1768                         writeLaTeXSource(os, filePath(), runparams, true, true);
1769                 else {
1770                         writeDocBookSource(os, fileName(), runparams, false);
1771                 }
1772         } else {
1773                 runparams.par_begin = par_begin;
1774                 runparams.par_end = par_end;
1775                 if (par_begin + 1 == par_end)
1776                         os << "% "
1777                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1778                            << "\n\n";
1779                 else
1780                         os << "% "
1781                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1782                                         convert<docstring>(par_begin),
1783                                         convert<docstring>(par_end - 1))
1784                            << "\n\n";
1785                 texrow().newline();
1786                 texrow().newline();
1787                 // output paragraphs
1788                 if (isLatex()) {
1789                         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1790                 } else {
1791                         // DocBook
1792                         docbookParagraphs(paragraphs(), *this, os, runparams);
1793                 }
1794         }
1795 }
1796
1797
1798 ErrorList const & Buffer::errorList(string const & type) const
1799 {
1800         static ErrorList const emptyErrorList;
1801         std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1802         if (I == pimpl_->errorLists.end())
1803                 return emptyErrorList;
1804
1805         return I->second;
1806 }
1807
1808
1809 ErrorList & Buffer::errorList(string const & type)
1810 {
1811         return pimpl_->errorLists[type];
1812 }
1813
1814
1815 } // namespace lyx