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