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