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