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