]> git.lyx.org Git - lyx.git/blobdiff - src/Buffer.cpp
SCons: msvc does not need this /TP option any more after we rename .C => .cpp. Also...
[lyx.git] / src / Buffer.cpp
index 99f11ea31eb2b7cd71d8b63d1d356ac7f78d95ba..5f73e27f6bec1f9ce4eb07510839b996138d3ad4 100644 (file)
@@ -13,6 +13,7 @@
 #include "Buffer.h"
 
 #include "Author.h"
+#include "BiblioInfo.h"
 #include "BranchList.h"
 #include "buffer_funcs.h"
 #include "BufferList.h"
@@ -21,6 +22,7 @@
 #include "Bullet.h"
 #include "Chktex.h"
 #include "debug.h"
+#include "DocIterator.h"
 #include "Encoding.h"
 #include "ErrorList.h"
 #include "Exporter.h"
@@ -47,6 +49,7 @@
 #include "ParIterator.h"
 #include "sgml.h"
 #include "TexRow.h"
+#include "TexStream.h"
 #include "TocBackend.h"
 #include "Undo.h"
 #include "version.h"
 #include "support/lyxalgo.h"
 #include "support/filetools.h"
 #include "support/fs_extras.h"
+#include "support/gzstream.h"
 #include "support/lyxlib.h"
 #include "support/os.h"
 #include "support/Path.h"
 #include "support/textutils.h"
 #include "support/convert.h"
 
-#include <boost/iostreams/filtering_stream.hpp>
-#include <boost/iostreams/filter/gzip.hpp>
-#include <boost/iostreams/device/file.hpp>
 #include <boost/bind.hpp>
 #include <boost/filesystem/exception.hpp>
 #include <boost/filesystem/operations.hpp>
 
-#if defined (HAVE_UTIME_H)
-#include <utime.h>
-#elif defined (HAVE_SYS_UTIME_H)
-#include <sys/utime.h>
-#endif
-
+#include <algorithm>
 #include <iomanip>
 #include <stack>
 #include <sstream>
 #include <fstream>
 
+using std::endl;
+using std::for_each;
+using std::make_pair;
+
+using std::ios;
+using std::map;
+using std::ostream;
+using std::ostringstream;
+using std::ofstream;
+using std::pair;
+using std::stack;
+using std::vector;
+using std::string;
+using std::time_t;
+
 
 namespace lyx {
 
@@ -119,30 +130,15 @@ using support::split;
 using support::subst;
 using support::tempName;
 using support::trim;
+using support::sum;
 
 namespace Alert = frontend::Alert;
 namespace os = support::os;
 namespace fs = boost::filesystem;
-namespace io = boost::iostreams;
-
-using std::endl;
-using std::for_each;
-using std::make_pair;
-
-using std::ios;
-using std::map;
-using std::ostream;
-using std::ostringstream;
-using std::ofstream;
-using std::pair;
-using std::stack;
-using std::vector;
-using std::string;
-
 
 namespace {
 
-int const LYX_FORMAT = 276;
+int const LYX_FORMAT = 280;
 
 } // namespace anon
 
@@ -196,13 +192,18 @@ public:
 
        /// Container for all sort of Buffer dependant errors.
        map<string, ErrorList> errorLists;
+
+       /// timestamp and checksum used to test if the file has been externally
+       /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
+       time_t timestamp_;
+       unsigned long checksum_;
 };
 
 
 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
        : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
          filename(file), file_fully_loaded(false), inset(params),
-         toc_backend(&parent)
+         toc_backend(&parent), timestamp_(0), checksum_(0)
 {
        inset.setAutoBreakRows(true);
        lyxvc.buffer(&parent);
@@ -227,7 +228,12 @@ Buffer::~Buffer()
        // here the buffer should take care that it is
        // saved properly, before it goes into the void.
 
-       closing();
+       Buffer * master = getMasterBuffer();
+       if (master != this && use_gui)
+               // We are closing buf which was a child document so we
+               // must update the labels and section numbering of its master
+               // Buffer.
+               updateLabels(*master);
 
        if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
                Alert::warning(_("Could not remove temporary directory"),
@@ -237,6 +243,8 @@ Buffer::~Buffer()
 
        // Remove any previewed LaTeX snippets associated with this buffer.
        graphics::Previews::get().removeLoader(*this);
+
+       closing(this);
 }
 
 
@@ -759,6 +767,9 @@ Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
        //MacroTable::localMacros().clear();
 
        pimpl_->file_fully_loaded = true;
+       // save the timestamp and checksum of disk file
+       pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
+       pimpl_->checksum_ = sum(filename);
        return success;
 }
 
@@ -793,9 +804,22 @@ bool Buffer::save() const
                }
        }
 
+       // ask if the disk file has been externally modified (use checksum method)
+       if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
+               docstring const file = makeDisplayPath(fileName(), 20);
+               docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
+                                                            "you want to overwrite this file?"), file);
+               int const ret = Alert::prompt(_("Overwrite modified file?"),
+                       text, 1, 1, _("&Overwrite"), _("&Cancel"));
+               if (ret == 1)
+                       return false;
+       }
+
        if (writeFile(pimpl_->filename)) {
                markClean();
                removeAutosaveFile(fileName());
+               pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
+               pimpl_->checksum_ = sum(pimpl_->filename);
                return true;
        } else {
                // Saving failed, so backup is not backup
@@ -814,7 +838,7 @@ bool Buffer::writeFile(FileName const & fname) const
        bool retval = false;
 
        if (params().compressed) {
-               io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname.toFilesystemEncoding()));
+               gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
                if (!ofs)
                        return false;
 
@@ -846,6 +870,19 @@ bool Buffer::write(ostream & ofs) const
            << "\\lyxformat " << LYX_FORMAT << "\n"
            << "\\begin_document\n";
 
+
+       /// For each author, set 'used' to true if there is a change
+       /// by this author in the document; otherwise set it to 'false'.
+       AuthorList::Authors::const_iterator a_it = params().authors().begin();
+       AuthorList::Authors::const_iterator a_end = params().authors().end();
+       for (; a_it != a_end; ++a_it)
+               a_it->second.used(false);
+
+       ParIterator const end = par_iterator_end();
+       ParIterator it = par_iterator_begin();
+       for ( ; it != end; ++it)
+               it->checkAuthors(params().authors());
+
        // now write out the buffer parameters.
        ofs << "\\begin_header\n";
        params().writeFile(ofs);
@@ -893,8 +930,11 @@ bool Buffer::makeLaTeXFile(FileName const & fname,
        if (!openFileWrite(ofs, fname))
                return false;
 
+       //TexStream ts(ofs.rdbuf(), &texrow());
+
        bool failed_export = false;
        try {
+               texrow().reset();
                writeLaTeXSource(ofs, original_path,
                      runparams, output_preamble, output_body);
        }
@@ -902,7 +942,7 @@ bool Buffer::makeLaTeXFile(FileName const & fname,
                lyxerr << "Caught iconv exception: " << e.what() << endl;
                failed_export = true;
        }
-       catch (std::exception  const & e) {
+       catch (std::exception const & e) {
                lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
                failed_export = true;
        }
@@ -942,12 +982,8 @@ void Buffer::writeLaTeXSource(odocstream & os,
        validate(features);
        LYXERR(Debug::LATEX) << "  Buffer validation done." << endl;
 
-       texrow().reset();
-
        // The starting paragraph of the coming rows is the
        // first paragraph of the document. (Asger)
-       texrow().start(paragraphs().begin()->id(), 0);
-
        if (output_preamble && runparams.nice) {
                os << "%% LyX " << lyx_version << " created this file.  "
                        "For more info, see http://www.lyx.org/.\n"
@@ -997,6 +1033,9 @@ void Buffer::writeLaTeXSource(odocstream & os,
                os << "\\begin{document}\n";
                texrow().newline();
        } // output_preamble
+
+       texrow().start(paragraphs().begin()->id(), 0);
+       
        LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
 
        if (!lyxrc.language_auto_begin &&
@@ -1028,6 +1067,8 @@ void Buffer::writeLaTeXSource(odocstream & os,
                params().parentname.erase();
        }
 
+       loadChildDocuments(*this);
+
        // the real stuff
        latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
 
@@ -1179,6 +1220,8 @@ void Buffer::writeDocBookSource(odocstream & os, string const & fname,
 
        params().getTextClass().counters().reset();
 
+       loadChildDocuments(*this);
+
        sgml::openTag(os, top);
        os << '\n';
        docbookParagraphs(paragraphs(), *this, os, runparams);
@@ -1268,6 +1311,8 @@ void Buffer::validate(LaTeXFeatures & features) const
        if (params().use_esint == BufferParams::package_on)
                features.require("esint");
 
+       loadChildDocuments(*this);
+
        for_each(paragraphs().begin(), paragraphs().end(),
                 boost::bind(&Paragraph::validate, _1, boost::ref(features)));
 
@@ -1315,48 +1360,13 @@ void Buffer::getLabelList(vector<docstring> & list) const
                return;
        }
 
+       loadChildDocuments(*this);
+
        for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
                it.nextInset()->getLabelList(*this, list);
 }
 
 
-// This is also a buffer property (ale)
-void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
-       const
-{
-       /// if this is a child document and the parent is already loaded
-       /// use the parent's list instead  [ale990412]
-       Buffer const * tmp = getMasterBuffer();
-       BOOST_ASSERT(tmp);
-       if (tmp != this) {
-               tmp->fillWithBibKeys(keys);
-               return;
-       }
-
-       for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
-               if (it->lyxCode() == Inset::BIBTEX_CODE) {
-                       InsetBibtex const & inset =
-                               static_cast<InsetBibtex const &>(*it);
-                       inset.fillWithBibKeys(*this, keys);
-               } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
-                       InsetInclude const & inset =
-                               static_cast<InsetInclude const &>(*it);
-                       inset.fillWithBibKeys(*this, keys);
-               } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
-                       InsetBibitem const & inset =
-                               static_cast<InsetBibitem const &>(*it);
-                       // FIXME UNICODE
-                       string const key = to_utf8(inset.getParam("key"));
-                       docstring const label = inset.getParam("label");
-                       DocIterator doc_it(it); doc_it.forwardPos();
-                       docstring const ref = doc_it.paragraph().asString(*this, false);
-                       docstring const info = label + "TheBibliographyRef" + ref;
-                       keys.push_back(pair<string, docstring>(key, info));
-               }
-       }
-}
-
-
 void Buffer::updateBibfilesCache()
 {
        // if this is a child document and the parent is already loaded
@@ -1547,6 +1557,16 @@ bool Buffer::isBakClean() const
 }
 
 
+bool Buffer::isExternallyModified(CheckMethod method) const
+{
+       BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
+       // if method == timestamp, check timestamp before checksum
+       return (method == checksum_method 
+               || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
+               && pimpl_->checksum_ != sum(pimpl_->filename);
+}
+
+
 void Buffer::markClean() const
 {
        if (!pimpl_->lyx_clean) {
@@ -1577,9 +1597,7 @@ bool Buffer::isUnnamed() const
 }
 
 
-#ifdef WITH_WARNINGS
-#warning this function should be moved to buffer_pimpl.C
-#endif
+// FIXME: this function should be moved to buffer_pimpl.C
 void Buffer::markDirty()
 {
        if (pimpl_->lyx_clean) {
@@ -1697,13 +1715,6 @@ void Buffer::buildMacros()
 }
 
 
-void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
-{
-       cursor_ = cur;
-       anchor_ = anc;
-}
-
-
 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
        Inset::Code code)
 {
@@ -1713,18 +1724,18 @@ void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
        vector<docstring> labels;
 
        if (code == Inset::CITE_CODE) {
-               vector<pair<string, docstring> > keys;
-               fillWithBibKeys(keys);
-               vector<pair<string, docstring> >::const_iterator bit  = keys.begin();
-               vector<pair<string, docstring> >::const_iterator bend = keys.end();
+               BiblioInfo keys;
+               keys.fillWithBibKeys(this);
+               BiblioInfo::const_iterator bit  = keys.begin();
+               BiblioInfo::const_iterator bend = keys.end();
 
                for (; bit != bend; ++bit)
                        // FIXME UNICODE
-                       labels.push_back(from_utf8(bit->first));
+                       labels.push_back(bit->first);
        } else
                getLabelList(labels);
 
-       if (lyx::count(labels.begin(), labels.end(), from) > 1)
+       if (std::count(labels.begin(), labels.end(), from) > 1)
                return;
 
        for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
@@ -1746,8 +1757,11 @@ void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
        // No side effect of file copying and image conversion
        runparams.dryrun = true;
 
+       texrow().reset();
        if (full_source) {
                os << "% " << _("Preview source code") << "\n\n";
+               texrow().newline();
+               texrow().newline();
                if (isLatex())
                        writeLaTeXSource(os, filePath(), runparams, true, true);
                else {
@@ -1758,7 +1772,7 @@ void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
                runparams.par_end = par_end;
                if (par_begin + 1 == par_end)
                        os << "% "
-                          << bformat(_("Preview source code for paragraph %1$s"), par_begin)
+                          << bformat(_("Preview source code for paragraph %1$d"), par_begin)
                           << "\n\n";
                else
                        os << "% "
@@ -1766,9 +1780,10 @@ void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
                                        convert<docstring>(par_begin),
                                        convert<docstring>(par_end - 1))
                           << "\n\n";
+               texrow().newline();
+               texrow().newline();
                // output paragraphs
                if (isLatex()) {
-                       texrow().reset();
                        latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
                } else {
                        // DocBook