2 * \file InsetInclude.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Richard Heck (conversion to InsetCommand)
9 * Full author contact details are available in file CREDITS.
14 #include "InsetInclude.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
22 #include "support/debug.h"
23 #include "DispatchResult.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.h"
27 #include "support/gettext.h"
28 #include "LaTeXFeatures.h"
32 #include "MetricsInfo.h"
33 #include "OutputParams.h"
34 #include "TocBackend.h"
35 #include "TextClass.h"
37 #include "frontends/alert.h"
38 #include "frontends/Painter.h"
40 #include "graphics/PreviewImage.h"
41 #include "graphics/PreviewLoader.h"
43 #include "insets/RenderPreview.h"
44 #include "insets/InsetListingsParams.h"
46 #include "support/docstream.h"
47 #include "support/FileNameList.h"
48 #include "support/filetools.h"
49 #include "support/lstrings.h" // contains
50 #include "support/lyxalgo.h"
51 #include "support/convert.h"
53 #include <boost/bind.hpp>
56 using namespace lyx::support;
60 namespace Alert = frontend::Alert;
65 docstring const uniqueID()
67 static unsigned int seed = 1000;
68 return "file" + convert<docstring>(++seed);
72 /// the type of inclusion
74 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
78 Types type(string const & s)
82 if (s == "verbatiminput")
84 if (s == "verbatiminput*")
86 if (s == "lstinputlisting")
94 Types type(InsetCommandParams const & params)
96 return type(params.getCmdName());
100 bool isListings(InsetCommandParams const & params)
102 return type(params) == LISTINGS;
106 bool isVerbatim(InsetCommandParams const & params)
108 Types const t = type(params);
109 return t == VERB || t == VERBAST;
113 bool isInputOrInclude(InsetCommandParams const & params)
115 Types const t = type(params);
116 return t == INPUT || t == INCLUDE;
122 InsetInclude::InsetInclude(InsetCommandParams const & p)
123 : InsetCommand(p, "include"), include_label(uniqueID()),
124 preview_(new RenderMonitoredPreview(this)), set_label_(false)
126 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
130 InsetInclude::InsetInclude(InsetInclude const & other)
131 : InsetCommand(other), include_label(other.include_label),
132 preview_(new RenderMonitoredPreview(this)), set_label_(false)
134 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
138 CommandInfo const * InsetInclude::findInfo(string const & /* cmdName */)
141 // This is only correct for the case of listings, but it'll do for now.
142 // In the other cases, this second parameter should just be empty.
143 static const char * const paramnames[] = {"filename", "lstparams", ""};
144 static const bool isoptional[] = {false, true};
145 static const CommandInfo info = {2, paramnames, isoptional};
150 bool InsetInclude::isCompatibleCommand(string const & s)
152 return type(s) != NONE;
156 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
158 switch (cmd.action) {
160 case LFUN_INSET_MODIFY: {
161 InsetCommandParams p(INCLUDE_CODE);
162 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
163 if (!p.getCmdName().empty()) {
165 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
166 InsetListingsParams par_new(to_utf8(p["lstparams"]));
167 if (par_old.getParamValue("label") !=
168 par_new.getParamValue("label")
169 && !par_new.getParamValue("label").empty())
170 cur.bv().buffer().changeRefsIfUnique(
171 from_utf8(par_old.getParamValue("label")),
172 from_utf8(par_new.getParamValue("label")),
175 set(p, cur.buffer());
176 cur.buffer().updateBibfilesCache();
182 //pass everything else up the chain
184 InsetCommand::doDispatch(cur, cmd);
192 FileName const masterFileName(Buffer const & buffer)
194 return buffer.masterBuffer()->fileName();
198 string const parentFilename(Buffer const & buffer)
200 return buffer.absFileName();
204 FileName const includedFilename(Buffer const & buffer,
205 InsetCommandParams const & params)
207 return makeAbsPath(to_utf8(params["filename"]),
208 onlyPath(parentFilename(buffer)));
212 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
217 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
222 if (preview_->monitoring())
223 preview_->stopMonitoring();
225 if (type(params()) == INPUT)
226 add_preview(*preview_, *this, buffer);
230 Inset * InsetInclude::clone() const
232 return new InsetInclude(*this);
236 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
240 switch (type(params())) {
242 temp = buf.B_("Input");
245 temp = buf.B_("Verbatim Input");
248 temp = buf.B_("Verbatim Input*");
251 temp = buf.B_("Include");
254 temp = listings_label_;
262 if (params()["filename"].empty())
265 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
273 /// return the child buffer if the file is a LyX doc and is loaded
274 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
276 if (isVerbatim(params) || isListings(params))
279 string const included_file = includedFilename(buffer, params).absFilename();
280 if (!isLyXFilename(included_file))
283 Buffer * childBuffer = theBufferList().getBuffer(included_file);
285 //FIXME RECURSIVE INCLUDES
286 if (childBuffer == & buffer)
295 /// return true if the file is or got loaded.
296 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
298 if (isVerbatim(params) || isListings(params))
301 string const parent_filename = parent.absFileName();
302 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
303 onlyPath(parent_filename));
305 if (!isLyXFilename(included_file.absFilename()))
308 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
310 // the readonly flag can/will be wrong, not anymore I think.
311 if (!included_file.exists())
314 child = theBufferList().newBuffer(included_file.absFilename());
315 if (!child->loadLyXFile(included_file)) {
316 //close the buffer we just opened
317 theBufferList().release(child);
321 child->setParent(&parent);
326 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
329 if (isVerbatim(params) || isListings(params))
332 string const parent_filename = parent->absFileName();
333 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
334 onlyPath(parent_filename));
336 if (!isLyXFilename(included_file.absFilename()))
339 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
340 // File not opened, nothing to close.
344 // Child document has a different parent, don't close it.
345 if (child->parent() != parent)
351 theBufferList().release(child);
353 updateLabels(*child);
357 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
358 OutputParams const & runparams) const
360 string incfile(to_utf8(params()["filename"]));
362 // Do nothing if no file name has been specified
366 FileName const included_file = includedFilename(buffer, params());
368 //Check we're not trying to include ourselves.
369 //FIXME RECURSIVE INCLUDE
370 //This isn't sufficient, as the inclusion could be downstream.
371 //But it'll have to do for now.
372 if (isInputOrInclude(params()) &&
373 buffer.absFileName() == included_file.absFilename())
375 Alert::error(_("Recursive input"),
376 bformat(_("Attempted to include file %1$s in itself! "
377 "Ignoring inclusion."), from_utf8(incfile)));
381 Buffer const * const masterBuffer = buffer.masterBuffer();
383 // if incfile is relative, make it relative to the master
385 if (!FileName(incfile).isAbsolute()) {
387 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
388 from_utf8(masterBuffer->filePath())));
391 // write it to a file (so far the complete file)
392 string const exportfile = changeExtension(incfile, ".tex");
393 string const mangled =
394 DocFileName(changeExtension(included_file.absFilename(),".tex")).
396 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
400 else if (!isValidLaTeXFilename(incfile)) {
401 frontend::Alert::warning(_("Invalid filename"),
402 _("The following filename is likely to cause trouble "
403 "when running the exported file through LaTeX: ") +
406 LYXERR(Debug::LATEX, "incfile:" << incfile);
407 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
408 LYXERR(Debug::LATEX, "writefile:" << writefile);
410 if (runparams.inComment || runparams.dryrun) {
411 //Don't try to load or copy the file if we're
412 //in a comment or doing a dryrun
413 } else if (isInputOrInclude(params()) &&
414 isLyXFilename(included_file.absFilename())) {
415 //if it's a LyX file and we're inputting or including,
416 //try to load it so we can write the associated latex
417 if (!loadIfNeeded(buffer, params()))
420 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
422 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
424 docstring text = bformat(_("Included file `%1$s'\n"
425 "has textclass `%2$s'\n"
426 "while parent file has textclass `%3$s'."),
427 included_file.displayName(),
428 from_utf8(tmp->params().getTextClass().name()),
429 from_utf8(masterBuffer->params().getTextClass().name()));
430 Alert::warning(_("Different textclasses"), text);
434 // Make sure modules used in child are all included in master
435 //FIXME It might be worth loading the children's modules into the master
436 //over in BufferParams rather than doing this check.
437 vector<string> const masterModules = masterBuffer->params().getModules();
438 vector<string> const childModules = tmp->params().getModules();
439 vector<string>::const_iterator it = childModules.begin();
440 vector<string>::const_iterator end = childModules.end();
441 for (; it != end; ++it) {
442 string const module = *it;
443 vector<string>::const_iterator found =
444 find(masterModules.begin(), masterModules.end(), module);
445 if (found != masterModules.end()) {
446 docstring text = bformat(_("Included file `%1$s'\n"
447 "uses module `%2$s'\n"
448 "which is not used in parent file."),
449 included_file.displayName(), from_utf8(module));
450 Alert::warning(_("Module not found"), text);
454 tmp->markDepClean(masterBuffer->temppath());
456 // FIXME: handle non existing files
457 // FIXME: Second argument is irrelevant!
458 // since only_body is true, makeLaTeXFile will not look at second
459 // argument. Should we set it to string(), or should makeLaTeXFile
460 // make use of it somehow? (JMarc 20031002)
461 // The included file might be written in a different encoding
462 Encoding const * const oldEnc = runparams.encoding;
463 runparams.encoding = &tmp->params().encoding();
464 tmp->makeLaTeXFile(writefile,
465 masterFileName(buffer).onlyPath().absFilename(),
467 runparams.encoding = oldEnc;
469 // In this case, it's not a LyX file, so we copy the file
470 // to the temp dir, so that .aux files etc. are not created
471 // in the original dir. Files included by this file will be
472 // found via input@path, see ../Buffer.cpp.
473 unsigned long const checksum_in = included_file.checksum();
474 unsigned long const checksum_out = writefile.checksum();
476 if (checksum_in != checksum_out) {
477 if (!included_file.copyTo(writefile)) {
480 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
481 "into the temporary directory."),
482 from_utf8(included_file.absFilename()))));
488 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
489 "latex" : "pdflatex";
490 if (isVerbatim(params())) {
491 incfile = latex_path(incfile);
493 os << '\\' << from_ascii(params().getCmdName()) << '{'
494 << from_utf8(incfile) << '}';
495 } else if (type(params()) == INPUT) {
496 runparams.exportdata->addExternalFile(tex_format, writefile,
499 // \input wants file with extension (default is .tex)
500 if (!isLyXFilename(included_file.absFilename())) {
501 incfile = latex_path(incfile);
503 os << '\\' << from_ascii(params().getCmdName())
504 << '{' << from_utf8(incfile) << '}';
506 incfile = changeExtension(incfile, ".tex");
507 incfile = latex_path(incfile);
509 os << '\\' << from_ascii(params().getCmdName())
510 << '{' << from_utf8(incfile) << '}';
512 } else if (type(params()) == LISTINGS) {
513 os << '\\' << from_ascii(params().getCmdName());
514 string const opt = to_utf8(params()["lstparams"]);
515 // opt is set in QInclude dialog and should have passed validation.
516 InsetListingsParams params(opt);
517 if (!params.params().empty())
518 os << "[" << from_utf8(params.params()) << "]";
519 os << '{' << from_utf8(incfile) << '}';
521 runparams.exportdata->addExternalFile(tex_format, writefile,
524 // \include don't want extension and demands that the
525 // file really have .tex
526 incfile = changeExtension(incfile, string());
527 incfile = latex_path(incfile);
529 os << '\\' << from_ascii(params().getCmdName()) << '{'
530 << from_utf8(incfile) << '}';
537 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
538 OutputParams const &) const
540 if (isVerbatim(params()) || isListings(params())) {
541 os << '[' << getScreenLabel(buffer) << '\n';
542 // FIXME: We don't know the encoding of the file, default to UTF-8.
543 os << includedFilename(buffer, params()).fileContents("UTF-8");
545 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
547 docstring const str = '[' + getScreenLabel(buffer) + ']';
554 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
555 OutputParams const & runparams) const
557 string incfile = to_utf8(params()["filename"]);
559 // Do nothing if no file name has been specified
563 string const included_file = includedFilename(buffer, params()).absFilename();
565 //Check we're not trying to include ourselves.
566 //FIXME RECURSIVE INCLUDE
567 //This isn't sufficient, as the inclusion could be downstream.
568 //But it'll have to do for now.
569 if (buffer.absFileName() == included_file) {
570 Alert::error(_("Recursive input"),
571 bformat(_("Attempted to include file %1$s in itself! "
572 "Ignoring inclusion."), from_utf8(incfile)));
576 // write it to a file (so far the complete file)
577 string const exportfile = changeExtension(incfile, ".sgml");
578 DocFileName writefile(changeExtension(included_file, ".sgml"));
580 if (loadIfNeeded(buffer, params())) {
581 Buffer * tmp = theBufferList().getBuffer(included_file);
583 string const mangled = writefile.mangledFilename();
584 writefile = makeAbsPath(mangled,
585 buffer.masterBuffer()->temppath());
589 LYXERR(Debug::LATEX, "incfile:" << incfile);
590 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
591 LYXERR(Debug::LATEX, "writefile:" << writefile);
593 tmp->makeDocBookFile(writefile, runparams, true);
596 runparams.exportdata->addExternalFile("docbook", writefile,
598 runparams.exportdata->addExternalFile("docbook-xml", writefile,
601 if (isVerbatim(params()) || isListings(params())) {
602 os << "<inlinegraphic fileref=\""
603 << '&' << include_label << ';'
604 << "\" format=\"linespecific\">";
606 os << '&' << include_label << ';';
612 void InsetInclude::validate(LaTeXFeatures & features) const
614 string incfile = to_utf8(params()["filename"]);
617 Buffer const & buffer = features.buffer();
619 string const included_file = includedFilename(buffer, params()).absFilename();
621 if (isLyXFilename(included_file))
622 writefile = changeExtension(included_file, ".sgml");
624 writefile = included_file;
626 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
627 incfile = DocFileName(writefile).mangledFilename();
628 writefile = makeAbsPath(incfile,
629 buffer.masterBuffer()->temppath()).absFilename();
632 features.includeFile(include_label, writefile);
634 if (isVerbatim(params()))
635 features.require("verbatim");
636 else if (isListings(params()))
637 features.require("listings");
639 // Here we must do the fun stuff...
640 // Load the file in the include if it needs
642 if (loadIfNeeded(buffer, params())) {
644 Buffer * const tmp = theBufferList().getBuffer(included_file);
645 // make sure the buffer isn't us
646 // FIXME RECURSIVE INCLUDES
647 // This is not sufficient, as recursive includes could be
648 // more than a file away. But it will do for now.
649 if (tmp && tmp != & buffer) {
650 // We must temporarily change features.buffer,
651 // otherwise it would always be the master buffer,
652 // and nested includes would not work.
653 features.setBuffer(*tmp);
654 tmp->validate(features);
655 features.setBuffer(buffer);
661 void InsetInclude::getLabelList(Buffer const & buffer,
662 vector<docstring> & list) const
664 if (isListings(params())) {
665 InsetListingsParams p(to_utf8(params()["lstparams"]));
666 string label = p.getParamValue("label");
668 list.push_back(from_utf8(label));
670 else if (loadIfNeeded(buffer, params())) {
671 string const included_file = includedFilename(buffer, params()).absFilename();
672 Buffer * tmp = theBufferList().getBuffer(included_file);
674 tmp->getLabelList(list);
675 tmp->setParent(const_cast<Buffer *>(&buffer));
680 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
681 BiblioInfo & keys, InsetIterator const & /*di*/) const
683 if (loadIfNeeded(buffer, params())) {
684 string const included_file = includedFilename(buffer, params()).absFilename();
685 Buffer * tmp = theBufferList().getBuffer(included_file);
686 //FIXME This is kind of a dirty hack and should be made reasonable.
688 keys.fillWithBibKeys(tmp);
689 tmp->setParent(&buffer);
694 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
696 Buffer * const tmp = getChildBuffer(buffer, params());
699 tmp->updateBibfilesCache();
700 tmp->setParent(&buffer);
706 InsetInclude::getBibfilesCache(Buffer const & buffer) const
708 Buffer * const tmp = getChildBuffer(buffer, params());
711 FileNameList const & cache = tmp->getBibfilesCache();
712 tmp->setParent(&buffer);
715 static FileNameList const empty;
720 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
722 BOOST_ASSERT(mi.base.bv);
724 bool use_preview = false;
725 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
726 graphics::PreviewImage const * pimage =
727 preview_->getPreviewImage(mi.base.bv->buffer());
728 use_preview = pimage && pimage->image();
732 preview_->metrics(mi, dim);
736 button_.update(getScreenLabel(mi.base.bv->buffer()),
739 button_.metrics(mi, dim);
742 Box b(0, dim.wid, -dim.asc, dim.des);
747 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
749 BOOST_ASSERT(pi.base.bv);
751 bool use_preview = false;
752 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
753 graphics::PreviewImage const * pimage =
754 preview_->getPreviewImage(pi.base.bv->buffer());
755 use_preview = pimage && pimage->image();
759 preview_->draw(pi, x, y);
761 button_.draw(pi, x, y);
765 Inset::DisplayType InsetInclude::display() const
767 return type(params()) == INPUT ? Inline : AlignCenter;
776 void InsetInclude::fileChanged() const
778 Buffer const * const buffer = updateFrontend();
782 preview_->removePreview(*buffer);
783 add_preview(*preview_.get(), *this, *buffer);
784 preview_->startLoading(*buffer);
790 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
792 FileName const included_file = includedFilename(buffer, params);
794 return type(params) == INPUT && params.preview() &&
795 included_file.isReadableFile();
799 docstring const latex_string(InsetInclude const & inset, Buffer const & buffer)
802 // We don't need to set runparams.encoding since this will be done
803 // by latex() anyway.
804 OutputParams runparams(0);
805 runparams.flavor = OutputParams::LATEX;
806 inset.latex(buffer, os, runparams);
812 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
813 Buffer const & buffer)
815 InsetCommandParams const & params = inset.params();
816 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
817 preview_wanted(params, buffer)) {
818 renderer.setAbsFile(includedFilename(buffer, params));
819 docstring const snippet = latex_string(inset, buffer);
820 renderer.addPreview(snippet, buffer);
827 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
829 Buffer const & buffer = ploader.buffer();
830 if (preview_wanted(params(), buffer)) {
831 preview_->setAbsFile(includedFilename(buffer, params()));
832 docstring const snippet = latex_string(*this, buffer);
833 preview_->addPreview(snippet, ploader);
838 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
839 ParConstIterator const & pit) const
841 if (isListings(params())) {
842 InsetListingsParams p(to_utf8(params()["lstparams"]));
843 string caption = p.getParamValue("caption");
846 Toc & toc = toclist["listing"];
847 docstring const str = convert<docstring>(toc.size() + 1)
848 + ". " + from_utf8(caption);
849 // This inset does not have a valid ParConstIterator
850 // so it has to use the iterator of its parent paragraph
851 toc.push_back(TocItem(pit, 0, str));
854 Buffer const * const childbuffer = getChildBuffer(buffer, params());
858 TocList const & childtoclist = childbuffer->tocBackend().tocs();
859 TocList::const_iterator it = childtoclist.begin();
860 TocList::const_iterator const end = childtoclist.end();
861 for(; it != end; ++it)
862 toclist[it->first].insert(toclist[it->first].end(),
863 it->second.begin(), it->second.end());
867 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
869 Buffer const * const childbuffer = getChildBuffer(buffer, params());
871 lyx::updateLabels(*childbuffer, true);
872 else if (isListings(params())) {
873 InsetListingsParams const par(to_utf8(params()["lstparams"]));
874 if (par.getParamValue("caption").empty())
875 listings_label_.clear();
877 Counters & counters = buffer.params().getTextClass().counters();
878 docstring const cnt = from_ascii("listing");
879 if (counters.hasCounter(cnt)) {
881 listings_label_ = buffer.B_("Program Listing ")
882 + convert<docstring>(counters.value(cnt));
884 listings_label_ = buffer.B_("Program Listing");
890 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
891 EmbeddedFiles & files) const
893 // include and input are temprarily not considered.
894 if (isVerbatim(params()) || isListings(params()))
895 files.registerFile(includedFilename(buffer, params()).absFilename(),