]> git.lyx.org Git - lyx.git/blobdiff - src/Buffer.cpp
Fulfill promise to Andre: TextClass_ptr --> TextClassPtr.
[lyx.git] / src / Buffer.cpp
index 2b0286a16ca699385143186f1bf335da1a6e0348..19d479cc9b2c8f1b1826723d22f479045b3dddfc 100644 (file)
@@ -13,7 +13,7 @@
 #include "Buffer.h"
 
 #include "Author.h"
-#include "Biblio.h"
+#include "BiblioInfo.h"
 #include "BranchList.h"
 #include "buffer_funcs.h"
 #include "BufferList.h"
@@ -22,6 +22,7 @@
 #include "Bullet.h"
 #include "Chktex.h"
 #include "debug.h"
+#include "DocIterator.h"
 #include "Encoding.h"
 #include "ErrorList.h"
 #include "Exporter.h"
 #include "ParIterator.h"
 #include "sgml.h"
 #include "TexRow.h"
+#include "TextClassList.h"
 #include "TexStream.h"
 #include "TocBackend.h"
 #include "Undo.h"
 #include "version.h"
+#include "EmbeddedFiles.h"
 
 #include "insets/InsetBibitem.h"
 #include "insets/InsetBibtex.h"
@@ -96,6 +99,7 @@ using std::map;
 using std::ostream;
 using std::ostringstream;
 using std::ofstream;
+using std::ifstream;
 using std::pair;
 using std::stack;
 using std::vector;
@@ -130,6 +134,7 @@ using support::subst;
 using support::tempName;
 using support::trim;
 using support::sum;
+using support::suffixIs;
 
 namespace Alert = frontend::Alert;
 namespace os = support::os;
@@ -137,7 +142,7 @@ namespace fs = boost::filesystem;
 
 namespace {
 
-int const LYX_FORMAT = 279;
+int const LYX_FORMAT = 285;
 
 } // namespace anon
 
@@ -192,6 +197,9 @@ public:
        /// Container for all sort of Buffer dependant errors.
        map<string, ErrorList> errorLists;
 
+       /// all embedded files of this buffer
+       EmbeddedFiles embedded_files;
+
        /// 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_;
@@ -202,7 +210,7 @@ public:
 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), timestamp_(0), checksum_(0)
+         toc_backend(&parent), embedded_files(&parent), timestamp_(0), checksum_(0)
 {
        inset.setAutoBreakRows(true);
        lyxvc.buffer(&parent);
@@ -227,7 +235,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 +250,8 @@ Buffer::~Buffer()
 
        // Remove any previewed LaTeX snippets associated with this buffer.
        graphics::Previews::get().removeLoader(*this);
+
+       closing(this);
 }
 
 
@@ -342,6 +357,18 @@ TocBackend const & Buffer::tocBackend() const
 }
 
 
+EmbeddedFiles & Buffer::embeddedFiles()
+{
+       return pimpl_->embedded_files;
+}
+
+
+EmbeddedFiles const & Buffer::embeddedFiles() const
+{
+       return pimpl_->embedded_files;
+}
+
+
 string const Buffer::getLatexName(bool const no_path) const
 {
        string const name = changeExtension(makeLatexName(fileName()), ".tex");
@@ -431,6 +458,8 @@ int Buffer::readHeader(Lexer & lex)
        params().headsep.erase();
        params().footskip.erase();
        params().listings_params.clear();
+       params().clearLayoutModules();
+       
        for (int i = 0; i < 4; ++i) {
                params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
                params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
@@ -502,12 +531,13 @@ bool Buffer::readDocument(Lexer & lex)
        BOOST_ASSERT(paragraphs().empty());
 
        readHeader(lex);
-       if (!params().getTextClass().load(filePath())) {
-               string theclass = params().getTextClass().name();
+       TextClass const & baseClass = textclasslist[params().getBaseClass()];
+       if (!baseClass.load(filePath())) {
+               string theclass = baseClass.name();
                Alert::error(_("Can't load document class"), bformat(
                        _("Using the default document class, because the "
                                     "class %1$s could not be loaded."), from_utf8(theclass)));
-               params().textclass = 0;
+               params().setBaseClass(defaultTextclass());
        }
 
        if (params().outputChanges) {
@@ -529,7 +559,10 @@ bool Buffer::readDocument(Lexer & lex)
                                         "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
                }
        }
+       // read manifest after header
+       embeddedFiles().readManifest(lex, errorList);   
 
+       // read main text
        bool const res = text().read(*this, lex, errorList);
        for_each(text().paragraphs().begin(),
                 text().paragraphs().end(),
@@ -623,8 +656,23 @@ bool Buffer::readString(std::string const & s)
 
 bool Buffer::readFile(FileName const & filename)
 {
+       FileName fname(filename);
        // Check if the file is compressed.
-       string const format = getFormatFromContents(filename);
+       string format = getFormatFromContents(filename);
+       if (format == "zip") {
+               // decompress to a temp directory
+               LYXERR(Debug::FILES) << filename << " is in zip format. Unzip to " << temppath() << endl;
+               ::unzipToDir(filename.toFilesystemEncoding(), temppath());
+               //
+               FileName lyxfile(addName(temppath(), "content.lyx"));
+               // if both manifest.txt and file.lyx exist, this is am embedded file
+               if (fs::exists(lyxfile.toFilesystemEncoding())) {
+                       params().embedded = true;
+                       fname = lyxfile;
+               }
+       }
+       // The embedded lyx file can also be compressed, for backward compatibility
+       format = getFormatFromContents(fname);
        if (format == "gzip" || format == "zip" || format == "compress") {
                params().compressed = true;
        }
@@ -632,8 +680,8 @@ bool Buffer::readFile(FileName const & filename)
        // remove dummy empty par
        paragraphs().clear();
        Lexer lex(0, 0);
-       lex.setFile(filename);
-       if (readFile(lex, filename) != success)
+       lex.setFile(fname);
+       if (readFile(lex, fname) != success)
                return false;
 
        return true;
@@ -693,6 +741,19 @@ Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
        int const file_format = convert<int>(tmp_format);
        //lyxerr << "format: " << file_format << endl;
 
+       // save timestamp and checksum of the original disk file, making sure
+       // to not overwrite them with those of the file created in the tempdir
+       // when it has to be converted to the current format.
+       if (!pimpl_->checksum_) {
+               // Save the timestamp and checksum of disk file. If filename is an
+               // emergency file, save the timestamp and sum of the original lyx file
+               // because isExternallyModified will check for this file. (BUG4193)
+               string diskfile = filename.toFilesystemEncoding();
+               if (suffixIs(diskfile, ".emergency"))
+                       diskfile = diskfile.substr(0, diskfile.size() - 10);
+               saveCheckSum(diskfile);
+       }
+
        if (file_format != LYX_FORMAT) {
 
                if (fromstring)
@@ -759,9 +820,6 @@ 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;
 }
 
@@ -810,8 +868,7 @@ bool Buffer::save() const
        if (writeFile(pimpl_->filename)) {
                markClean();
                removeAutosaveFile(fileName());
-               pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
-               pimpl_->checksum_ = sum(pimpl_->filename);
+               saveCheckSum(pimpl_->filename.toFilesystemEncoding());
                return true;
        } else {
                // Saving failed, so backup is not backup
@@ -829,20 +886,32 @@ bool Buffer::writeFile(FileName const & fname) const
 
        bool retval = false;
 
+       FileName content;
+       if (params().embedded)
+               // first write the .lyx file to the temporary directory
+               content = FileName(addName(temppath(), "content.lyx"));
+       else
+               content = fname;
+       
        if (params().compressed) {
-               gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
+               gz::ogzstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
                if (!ofs)
                        return false;
 
                retval = write(ofs);
        } else {
-               ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
+               ofstream ofs(content.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
                if (!ofs)
                        return false;
 
                retval = write(ofs);
        }
 
+       if (retval && params().embedded) {
+               // write file.lyx and all the embedded files to the zip file fname
+               // if embedding is enabled
+               return pimpl_->embedded_files.writeFile(fname);
+       }
        return retval;
 }
 
@@ -880,6 +949,12 @@ bool Buffer::write(ostream & ofs) const
        params().writeFile(ofs);
        ofs << "\\end_header\n";
 
+       // write the manifest after header
+       ofs << "\n\\begin_manifest\n";
+       pimpl_->embedded_files.update();
+       embeddedFiles().writeManifest(ofs);
+       ofs << "\\end_manifest\n";
+
        // write the text
        ofs << "\n\\begin_body\n";
        text().write(*this, ofs);
@@ -1359,14 +1434,6 @@ void Buffer::getLabelList(vector<docstring> & list) const
 }
 
 
-// This is also a buffer property (ale)
-void Buffer::fillWithBibKeys(biblio::BibKeyList & keys)
-       const
-{
-       biblio::fillWithBibKeys(this, keys);
-}
-
-
 void Buffer::updateBibfilesCache()
 {
        // if this is a child document and the parent is already loaded
@@ -1466,9 +1533,6 @@ void Buffer::changeLanguage(Language const * from, Language const * to)
        for_each(par_iterator_begin(),
                 par_iterator_end(),
                 bind(&Paragraph::changeLanguage, _1, params(), from, to));
-
-       text().current_font.setLanguage(to);
-       text().real_current_font.setLanguage(to);
 }
 
 
@@ -1567,6 +1631,19 @@ bool Buffer::isExternallyModified(CheckMethod method) const
 }
 
 
+void Buffer::saveCheckSum(string const & file) const
+{
+       if (fs::exists(file)) {
+               pimpl_->timestamp_ = fs::last_write_time(file);
+               pimpl_->checksum_ = sum(FileName(file));
+       } else {
+               // in the case of save to a new file.
+               pimpl_->timestamp_ = 0;
+               pimpl_->checksum_ = 0;
+       }
+}
+
+
 void Buffer::markClean() const
 {
        if (!pimpl_->lyx_clean) {
@@ -1663,7 +1740,10 @@ Buffer * Buffer::getMasterBuffer()
        if (!params().parentname.empty()
            && theBufferList().exists(params().parentname)) {
                Buffer * buf = theBufferList().getBuffer(params().parentname);
-               if (buf)
+               //We need to check if the parent is us...
+               //FIXME RECURSIVE INCLUDE
+               //This is not sufficient, since recursive includes could be downstream.
+               if (buf && buf != this)
                        return buf->getMasterBuffer();
        }
 
@@ -1715,13 +1795,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)
 {
@@ -1731,14 +1804,14 @@ void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
        vector<docstring> labels;
 
        if (code == Inset::CITE_CODE) {
-               biblio::BibKeyList keys;
-               fillWithBibKeys(keys);
-               biblio::BibKeyList::const_iterator bit  = keys.begin();
-               biblio::BibKeyList::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);