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