]> git.lyx.org Git - lyx.git/blobdiff - src/insets/InsetInclude.cpp
Make logic clearer, with help from Lars.
[lyx.git] / src / insets / InsetInclude.cpp
index 2ad17d30725b4eb08c518a49abd93db283ebaaa7..e8eb7adefecf4eabff86b3bfb50b49d911638060 100644 (file)
@@ -39,6 +39,7 @@
 #include "graphics/PreviewLoader.h"
 
 #include "insets/RenderPreview.h"
+#include "insets/InsetListingsParams.h"
 
 #include "support/filetools.h"
 #include "support/lstrings.h" // contains
@@ -61,6 +62,7 @@ using support::copy;
 using support::DocFileName;
 using support::FileName;
 using support::getFileContents;
+using support::getVectorFromString;
 using support::isFileReadable;
 using support::isLyXFilename;
 using support::latex_path;
@@ -69,6 +71,7 @@ using support::makeDisplayPath;
 using support::makeRelPath;
 using support::onlyFilename;
 using support::onlyPath;
+using support::prefixIs;
 using support::subst;
 using support::sum;
 
@@ -78,6 +81,7 @@ using std::auto_ptr;
 using std::istringstream;
 using std::ostream;
 using std::ostringstream;
+using std::vector;
 
 namespace Alert = frontend::Alert;
 namespace fs = boost::filesystem;
@@ -91,13 +95,19 @@ docstring const uniqueID()
        return "file" + convert<docstring>(++seed);
 }
 
+
+bool isListings(InsetCommandParams const & params)
+{
+       return params.getCmdName() == "lstinputlisting";
+}
+
 } // namespace anon
 
 
 InsetInclude::InsetInclude(InsetCommandParams const & p)
        : params_(p), include_label(uniqueID()),
          preview_(new RenderMonitoredPreview(this)),
-         set_label_(false)
+         set_label_(false), counter_(0)
 {
        preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
 }
@@ -108,7 +118,7 @@ InsetInclude::InsetInclude(InsetInclude const & other)
          params_(other.params_),
          include_label(other.include_label),
          preview_(new RenderMonitoredPreview(this)),
-         set_label_(false)
+         set_label_(false), counter_(0)
 {
        preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
 }
@@ -128,6 +138,17 @@ void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
                InsetCommandParams p("include");
                InsetIncludeMailer::string2params(to_utf8(cmd.argument()), p);
                if (!p.getCmdName().empty()) {
+                       if (isListings(p)){
+                               InsetListingsParams par_old(params().getOptions());
+                               InsetListingsParams par_new(p.getOptions());
+                               if (par_old.getParamValue("label") !=
+                                   par_new.getParamValue("label")
+                                   && !par_new.getParamValue("label").empty())
+                                       cur.bv().buffer()->changeRefsIfUnique(
+                                               from_utf8(par_old.getParamValue("label")),
+                                               from_utf8(par_new.getParamValue("label")),
+                                               Inset::REF_CODE);
+                       }
                        set(p, cur.buffer());
                        cur.buffer().updateBibfilesCache();
                } else
@@ -140,7 +161,8 @@ void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
                break;
 
        case LFUN_MOUSE_RELEASE:
-               InsetIncludeMailer(*this).showDialog(&cur.bv());
+               if (!cur.selection()) 
+                       InsetIncludeMailer(*this).showDialog(&cur.bv());
                break;
 
        default:
@@ -179,7 +201,8 @@ enum Types {
        INCLUDE = 0,
        VERB = 1,
        INPUT = 2,
-       VERBAST = 3
+       VERBAST = 3,
+       LISTINGS = 4,
 };
 
 
@@ -193,6 +216,8 @@ Types type(InsetCommandParams const & params)
                return VERB;
        if  (command_name == "verbatiminput*")
                return VERBAST;
+       if  (command_name == "lstinputlisting")
+               return LISTINGS;
        return INCLUDE;
 }
 
@@ -205,6 +230,13 @@ bool isVerbatim(InsetCommandParams const & params)
 }
 
 
+bool isInputOrInclude(InsetCommandParams const & params) 
+{
+       Types const t = type(params);
+       return (t == INPUT) || (t == INCLUDE);
+}
+
+
 string const masterFilename(Buffer const & buffer)
 {
        return buffer.getMasterBuffer()->fileName();
@@ -311,6 +343,13 @@ docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
                case INCLUDE:
                        temp += buf.B_("Include");
                        break;
+               case LISTINGS: {
+                       if (counter_ > 0)
+                               temp += buf.B_("Program Listing ") + convert<docstring>(counter_);
+                       else
+                               temp += buf.B_("Program Listing");
+                       break;
+               }
        }
 
        temp += ": ";
@@ -329,21 +368,27 @@ namespace {
 /// return the child buffer if the file is a LyX doc and is loaded
 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
 {
-       if (isVerbatim(params))
+       if (isVerbatim(params) || isListings(params))
                return 0;
 
        string const included_file = includedFilename(buffer, params).absFilename();
        if (!isLyXFilename(included_file))
                return 0;
 
-       return theBufferList().getBuffer(included_file);
+       Buffer * childBuffer = theBufferList().getBuffer(included_file);
+       
+       //FIXME RECURSIVE INCLUDES
+       if (childBuffer == & buffer)
+               return 0;
+       else
+               return childBuffer;
 }
 
 
 /// return true if the file is or got loaded.
 bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
 {
-       if (isVerbatim(params))
+       if (isVerbatim(params) || isListings(params))
                return false;
 
        FileName const included_file = includedFilename(buffer, params);
@@ -356,12 +401,14 @@ bool loadIfNeeded(Buffer const & buffer, InsetCommandParams const & params)
                if (!fs::exists(included_file.toFilesystemEncoding()))
                        return false;
                buf = theBufferList().newBuffer(included_file.absFilename());
-               if (!loadLyXFile(buf, included_file))
+               if (!loadLyXFile(buf, included_file)) {
+                       //close the buffer we just opened
+                       theBufferList().close(buf, false);
                        return false;
+               }
        }
-       if (buf)
-               buf->setParentName(parentFilename(buffer));
-       return buf != 0;
+       buf->setParentName(parentFilename(buffer));
+       return true;
 }
 
 
@@ -378,6 +425,20 @@ int InsetInclude::latex(Buffer const & buffer, odocstream & os,
                return 0;
 
        FileName const included_file(includedFilename(buffer, params_));
+       
+       //Check we're not trying to include ourselves.
+       //FIXME RECURSIVE INCLUDE
+       //This isn't sufficient, as the inclusion could be downstream.
+       //But it'll have to do for now.
+       if (isInputOrInclude(params_) &&
+               buffer.fileName() == included_file.toFilesystemEncoding()) 
+       {
+               Alert::error(_("Recursive input"), 
+                              bformat(_("Attempted to include file %1$s in itself! "
+                              "Ignoring inclusion."), from_utf8(incfile)));
+               return 0;
+       }
+
        Buffer const * const m_buffer = buffer.getMasterBuffer();
 
        // if incfile is relative, make it relative to the master
@@ -390,8 +451,9 @@ int InsetInclude::latex(Buffer const & buffer, odocstream & os,
 
        // write it to a file (so far the complete file)
        string const exportfile = changeExtension(incfile, ".tex");
-       string const mangled = DocFileName(changeExtension(included_file.absFilename(),
-                                                       ".tex")).mangledFilename();
+       string const mangled = 
+               DocFileName(changeExtension(included_file.absFilename(),".tex")).
+                       mangledFilename();
        FileName const writefile(makeAbsPath(mangled, m_buffer->temppath()));
 
        if (!runparams.nice)
@@ -400,10 +462,16 @@ int InsetInclude::latex(Buffer const & buffer, odocstream & os,
        LYXERR(Debug::LATEX) << "exportfile:" << exportfile << endl;
        LYXERR(Debug::LATEX) << "writefile:" << writefile << endl;
 
-       if (runparams.inComment || runparams.dryrun)
-               // Don't try to load or copy the file
-               ;
-       else if (loadIfNeeded(buffer, params_)) {
+       if (runparams.inComment || runparams.dryrun) {
+               //Don't try to load or copy the file if we're
+               //in a comment or doing a dryrun
+       } else if (isInputOrInclude(params_) && 
+                isLyXFilename(included_file.absFilename())) {
+               //if it's a LyX file and we're inputting or including,
+               //try to load it so we can write the associated latex
+               if (!loadIfNeeded(buffer, params_))
+                       return false;
+                       
                Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
 
                if (tmp->params().textclass != m_buffer->params().textclass) {
@@ -435,9 +503,10 @@ int InsetInclude::latex(Buffer const & buffer, odocstream & os,
                                   runparams, false);
                runparams.encoding = oldEnc;
        } else {
-               // Copy the file to the temp dir, so that .aux files etc.
-               // are not created in the original dir. Files included by
-               // this file will be found via input@path, see ../Buffer.cpp.
+               // In this case, it's not a LyX file, so we copy the file
+               // to the temp dir, so that .aux files etc. are not created 
+               // in the original dir. Files included by this file will be 
+               // found via input@path, see ../Buffer.cpp.
                unsigned long const checksum_in  = sum(included_file);
                unsigned long const checksum_out = sum(writefile);
 
@@ -478,6 +547,14 @@ int InsetInclude::latex(Buffer const & buffer, odocstream & os,
                        os << '\\' << from_ascii(params_.getCmdName())
                           << '{' << from_utf8(incfile) <<  '}';
                }
+       } else if (type(params_) == LISTINGS) {
+               os << '\\' << from_ascii(params_.getCmdName());
+               string opt = params_.getOptions();
+               // opt is set in QInclude dialog and should have passed validation.
+               InsetListingsParams params(opt);
+               if (!params.params().empty())
+                       os << "[" << from_utf8(params.params()) << "]";
+               os << '{'  << from_utf8(incfile) << '}';
        } else {
                runparams.exportdata->addExternalFile(tex_format, writefile,
                                                      exportfile);
@@ -498,7 +575,7 @@ int InsetInclude::latex(Buffer const & buffer, odocstream & os,
 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
                             OutputParams const &) const
 {
-       if (isVerbatim(params_)) {
+       if (isVerbatim(params_) || isListings(params_)) {
                os << '[' << getScreenLabel(buffer) << '\n';
                // FIXME: We don't know the encoding of the file
                docstring const str =
@@ -525,6 +602,17 @@ int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
 
        string const included_file = includedFilename(buffer, params_).absFilename();
 
+       //Check we're not trying to include ourselves.
+       //FIXME RECURSIVE INCLUDE
+       //This isn't sufficient, as the inclusion could be downstream.
+       //But it'll have to do for now.
+       if (buffer.fileName() == included_file) {
+               Alert::error(_("Recursive input"), 
+                              bformat(_("Attempted to include file %1$s in itself! "
+                              "Ignoring inclusion."), from_utf8(incfile)));
+               return 0;
+       }
+
        // write it to a file (so far the complete file)
        string const exportfile = changeExtension(incfile, ".sgml");
        DocFileName writefile(changeExtension(included_file, ".sgml"));
@@ -550,7 +638,7 @@ int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
        runparams.exportdata->addExternalFile("docbook-xml", writefile,
                                              exportfile);
 
-       if (isVerbatim(params_)) {
+       if (isVerbatim(params_) || isListings(params_)) {
                os << "<inlinegraphic fileref=\""
                   << '&' << include_label << ';'
                   << "\" format=\"linespecific\">";
@@ -575,7 +663,7 @@ void InsetInclude::validate(LaTeXFeatures & features) const
        else
                writefile = included_file;
 
-       if (!features.runparams().nice && !isVerbatim(params_)) {
+       if (!features.runparams().nice && !isVerbatim(params_) && !isListings(params_)) {
                incfile = DocFileName(writefile).mangledFilename();
                writefile = makeAbsPath(incfile,
                                        buffer.getMasterBuffer()->temppath()).absFilename();
@@ -585,6 +673,8 @@ void InsetInclude::validate(LaTeXFeatures & features) const
 
        if (isVerbatim(params_))
                features.require("verbatim");
+       else if (isListings(params_))
+               features.require("listings");
 
        // Here we must do the fun stuff...
        // Load the file in the include if it needs
@@ -592,7 +682,11 @@ void InsetInclude::validate(LaTeXFeatures & features) const
        if (loadIfNeeded(buffer, params_)) {
                // a file got loaded
                Buffer * const tmp = theBufferList().getBuffer(included_file);
-               if (tmp) {
+               // make sure the buffer isn't us
+               // FIXME RECURSIVE INCLUDES
+               // This is not sufficient, as recursive includes could be
+               // more than a file away. But it will do for now.
+               if (tmp && tmp != & buffer) {
                        // We must temporarily change features.buffer,
                        // otherwise it would always be the master buffer,
                        // and nested includes would not work.
@@ -607,7 +701,13 @@ void InsetInclude::validate(LaTeXFeatures & features) const
 void InsetInclude::getLabelList(Buffer const & buffer,
                                std::vector<docstring> & list) const
 {
-       if (loadIfNeeded(buffer, params_)) {
+       if (isListings(params_)) {
+               InsetListingsParams params(params_.getOptions());
+               string label = params.getParamValue("label");
+               if (!label.empty())
+                       list.push_back(from_utf8(label));
+       }
+       else if (loadIfNeeded(buffer, params_)) {
                string const included_file = includedFilename(buffer, params_).absFilename();
                Buffer * tmp = theBufferList().getBuffer(included_file);
                tmp->setParentName("");
@@ -706,9 +806,10 @@ void InsetInclude::draw(PainterInfo & pi, int x, int y) const
                button_.draw(pi, x, y);
 }
 
-bool InsetInclude::display() const
+
+Inset::DisplayType InsetInclude::display() const
 {
-       return type(params_) != INPUT;
+       return type(params_) == INPUT ? Inline : AlignCenter;
 }
 
 
@@ -805,6 +906,21 @@ void InsetInclude::updateLabels(Buffer const & buffer) const
 }
 
 
+void InsetInclude::updateCounter(Counters & counters)
+{
+       if (!isListings(params_))
+               return;
+
+       InsetListingsParams const par = params_.getOptions();
+       if (par.getParamValue("caption").empty())
+               counter_ = 0;
+       else {
+               counters.step(from_ascii("listing"));
+               counter_ = counters.value(from_ascii("listing"));
+       }
+}
+
+
 string const InsetIncludeMailer::name_("include");
 
 InsetIncludeMailer::InsetIncludeMailer(InsetInclude & inset)