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