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)
8 * \author Bo Peng (embedding stuff)
10 * Full author contact details are available in file CREDITS.
15 #include "InsetInclude.h"
17 #include "LayoutFile.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
24 #include "DispatchResult.h"
25 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LaTeXFeatures.h"
33 #include "MetricsInfo.h"
34 #include "OutputParams.h"
35 #include "TextClass.h"
36 #include "TocBackend.h"
38 #include "frontends/alert.h"
39 #include "frontends/Painter.h"
41 #include "graphics/PreviewImage.h"
42 #include "graphics/PreviewLoader.h"
44 #include "insets/InsetLabel.h"
45 #include "insets/InsetListingsParams.h"
46 #include "insets/RenderPreview.h"
48 #include "support/debug.h"
49 #include "support/docstream.h"
50 #include "support/FileNameList.h"
51 #include "support/filetools.h"
52 #include "support/gettext.h"
53 #include "support/lstrings.h" // contains
54 #include "support/lyxalgo.h"
55 #include "support/convert.h"
57 #include <boost/bind.hpp>
60 using namespace lyx::support;
64 namespace Alert = frontend::Alert;
69 docstring const uniqueID()
71 static unsigned int seed = 1000;
72 return "file" + convert<docstring>(++seed);
76 /// the type of inclusion
78 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
82 Types type(string const & s)
86 if (s == "verbatiminput")
88 if (s == "verbatiminput*")
90 if (s == "lstinputlisting")
98 Types type(InsetCommandParams const & params)
100 return type(params.getCmdName());
104 bool isListings(InsetCommandParams const & params)
106 return type(params) == LISTINGS;
110 bool isVerbatim(InsetCommandParams const & params)
112 Types const t = type(params);
113 return t == VERB || t == VERBAST;
117 bool isInputOrInclude(InsetCommandParams const & params)
119 Types const t = type(params);
120 return t == INPUT || t == INCLUDE;
124 FileName const masterFileName(Buffer const & buffer)
126 return buffer.masterBuffer()->fileName();
130 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
133 string const parentFilename(Buffer const & buffer)
135 return buffer.absFileName();
139 EmbeddedFile const includedFilename(Buffer const & buffer,
140 InsetCommandParams const & params)
142 // it is not a good idea to create this EmbeddedFile object
143 // each time, but there seems to be no easy way around.
144 EmbeddedFile file(to_utf8(params["filename"]),
145 onlyPath(parentFilename(buffer)));
146 file.setEmbed(!params["embed"].empty());
147 file.setInzipName(to_utf8(params["embed"]));
148 file.enable(buffer.embedded(), &buffer, false);
152 InsetLabel * createLabel(docstring const & label_str)
154 if (label_str.empty())
156 InsetCommandParams icp(LABEL_CODE);
157 icp["name"] = label_str;
158 return new InsetLabel(icp);
164 InsetInclude::InsetInclude(InsetCommandParams const & p)
165 : InsetCommand(p, "include"), include_label(uniqueID()),
166 preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
168 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
170 if (isListings(params())) {
171 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
172 label_ = createLabel(from_utf8(listing_params.getParamValue("label")));
177 InsetInclude::InsetInclude(InsetInclude const & other)
178 : InsetCommand(other), include_label(other.include_label),
179 preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
181 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
184 label_ = new InsetLabel(*other.label_);
188 InsetInclude::~InsetInclude()
191 if (isVerbatim(params()) || isListings(params()))
195 string const parent_filename = buffer().absFileName();
196 FileName const included_file = makeAbsPath(to_utf8(params()["filename"]),
197 onlyPath(parent_filename));
199 if (!isLyXFilename(included_file.absFilename()))
202 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
203 // File not opened, nothing to close.
207 // Child document has a different parent, don't close it.
208 if (child->parent() != &buffer())
212 theBufferList().release(child);
216 void InsetInclude::setBuffer(Buffer & buffer)
220 label_->setBuffer(buffer);
225 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
228 // This is only correct for the case of listings, but it'll do for now.
229 // In the other cases, this second parameter should just be empty.
230 static ParamInfo param_info_;
231 if (param_info_.empty()) {
232 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
233 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
234 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
240 bool InsetInclude::isCompatibleCommand(string const & s)
242 return type(s) != NONE;
246 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
248 BOOST_ASSERT(&cur.buffer() == &buffer());
249 switch (cmd.action) {
251 case LFUN_INSET_MODIFY: {
252 InsetCommandParams p(INCLUDE_CODE);
253 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
254 if (!p.getCmdName().empty()) {
256 InsetListingsParams new_params(to_utf8(p["lstparams"]));
257 docstring const label_str = from_utf8(new_params.getParamValue("label"));
258 if (label_str.empty())
261 label_->updateCommand(label_str);
263 label_ = createLabel(label_str);
264 label_->setBuffer(buffer());
269 buffer().updateBibfilesCache();
275 //pass everything else up the chain
277 InsetCommand::doDispatch(cur, cmd);
283 void InsetInclude::setParams(InsetCommandParams const & p)
285 InsetCommand::setParams(p);
288 if (preview_->monitoring())
289 preview_->stopMonitoring();
291 if (type(params()) == INPUT)
292 add_preview(*preview_, *this, buffer());
296 docstring InsetInclude::screenLabel() const
300 switch (type(params())) {
302 temp = buffer().B_("Input");
305 temp = buffer().B_("Verbatim Input");
308 temp = buffer().B_("Verbatim Input*");
311 temp = buffer().B_("Include");
314 temp = listings_label_;
322 if (params()["filename"].empty())
325 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
327 if (!params()["embed"].empty())
328 temp += _(" (embedded)");
333 /// return the child buffer if the file is a LyX doc and is loaded
334 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
336 if (isVerbatim(params) || isListings(params))
339 string const included_file = includedFilename(buffer, params).absFilename();
340 if (!isLyXFilename(included_file))
343 Buffer * childBuffer = loadIfNeeded(buffer, params);
345 // FIXME: recursive includes
346 return (childBuffer == &buffer) ? 0 : childBuffer;
350 /// return true if the file is or got loaded.
351 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
353 if (isVerbatim(params) || isListings(params))
356 string const parent_filename = parent.absFileName();
357 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
358 onlyPath(parent_filename));
360 if (!isLyXFilename(included_file.absFilename()))
363 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
365 // the readonly flag can/will be wrong, not anymore I think.
366 if (!included_file.exists())
369 child = theBufferList().newBuffer(included_file.absFilename());
371 // Buffer creation is not possible.
374 if (!child->loadLyXFile(included_file)) {
375 //close the buffer we just opened
376 theBufferList().release(child);
380 if (!child->errorList("Parse").empty()) {
381 // FIXME: Do something.
384 child->setParent(&parent);
389 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
391 string incfile = to_utf8(params()["filename"]);
393 // Do nothing if no file name has been specified
397 FileName const included_file =
398 includedFilename(buffer(), params()).availableFile();
400 // Check we're not trying to include ourselves.
401 // FIXME RECURSIVE INCLUDE
402 // This isn't sufficient, as the inclusion could be downstream.
403 // But it'll have to do for now.
404 if (isInputOrInclude(params()) &&
405 buffer().absFileName() == included_file.absFilename())
407 Alert::error(_("Recursive input"),
408 bformat(_("Attempted to include file %1$s in itself! "
409 "Ignoring inclusion."), from_utf8(incfile)));
413 Buffer const * const masterBuffer = buffer().masterBuffer();
415 // if incfile is relative, make it relative to the master
417 if (!FileName(incfile).isAbsolute()) {
419 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
420 from_utf8(masterBuffer->filePath())));
423 // write it to a file (so far the complete file)
424 string const exportfile = changeExtension(incfile, ".tex");
425 string const mangled =
426 DocFileName(changeExtension(included_file.absFilename(),".tex")).
428 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
432 else if (!isValidLaTeXFilename(incfile)) {
433 frontend::Alert::warning(_("Invalid filename"),
434 _("The following filename is likely to cause trouble "
435 "when running the exported file through LaTeX: ") +
438 LYXERR(Debug::LATEX, "incfile:" << incfile);
439 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
440 LYXERR(Debug::LATEX, "writefile:" << writefile);
442 if (runparams.inComment || runparams.dryrun) {
443 //Don't try to load or copy the file if we're
444 //in a comment or doing a dryrun
445 } else if (isInputOrInclude(params()) &&
446 isLyXFilename(included_file.absFilename())) {
447 //if it's a LyX file and we're inputting or including,
448 //try to load it so we can write the associated latex
449 if (!loadIfNeeded(buffer(), params()))
452 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
454 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
456 docstring text = bformat(_("Included file `%1$s'\n"
457 "has textclass `%2$s'\n"
458 "while parent file has textclass `%3$s'."),
459 included_file.displayName(),
460 from_utf8(tmp->params().documentClass().name()),
461 from_utf8(masterBuffer->params().documentClass().name()));
462 Alert::warning(_("Different textclasses"), text);
465 // Make sure modules used in child are all included in master
466 //FIXME It might be worth loading the children's modules into the master
467 //over in BufferParams rather than doing this check.
468 vector<string> const masterModules = masterBuffer->params().getModules();
469 vector<string> const childModules = tmp->params().getModules();
470 vector<string>::const_iterator it = childModules.begin();
471 vector<string>::const_iterator end = childModules.end();
472 for (; it != end; ++it) {
473 string const module = *it;
474 vector<string>::const_iterator found =
475 find(masterModules.begin(), masterModules.end(), module);
476 if (found != masterModules.end()) {
477 docstring text = bformat(_("Included file `%1$s'\n"
478 "uses module `%2$s'\n"
479 "which is not used in parent file."),
480 included_file.displayName(), from_utf8(module));
481 Alert::warning(_("Module not found"), text);
485 tmp->markDepClean(masterBuffer->temppath());
487 // FIXME: handle non existing files
488 // FIXME: Second argument is irrelevant!
489 // since only_body is true, makeLaTeXFile will not look at second
490 // argument. Should we set it to string(), or should makeLaTeXFile
491 // make use of it somehow? (JMarc 20031002)
492 // The included file might be written in a different encoding
493 Encoding const * const oldEnc = runparams.encoding;
494 runparams.encoding = &tmp->params().encoding();
495 tmp->makeLaTeXFile(writefile,
496 masterFileName(buffer()).onlyPath().absFilename(),
498 runparams.encoding = oldEnc;
500 // In this case, it's not a LyX file, so we copy the file
501 // to the temp dir, so that .aux files etc. are not created
502 // in the original dir. Files included by this file will be
503 // found via input@path, see ../Buffer.cpp.
504 unsigned long const checksum_in = included_file.checksum();
505 unsigned long const checksum_out = writefile.checksum();
507 if (checksum_in != checksum_out) {
508 if (!included_file.copyTo(writefile)) {
511 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
512 "into the temporary directory."),
513 from_utf8(included_file.absFilename()))));
519 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
520 "latex" : "pdflatex";
521 if (isVerbatim(params())) {
522 incfile = latex_path(incfile);
524 os << '\\' << from_ascii(params().getCmdName()) << '{'
525 << from_utf8(incfile) << '}';
526 } else if (type(params()) == INPUT) {
527 runparams.exportdata->addExternalFile(tex_format, writefile,
530 // \input wants file with extension (default is .tex)
531 if (!isLyXFilename(included_file.absFilename())) {
532 incfile = latex_path(incfile);
534 os << '\\' << from_ascii(params().getCmdName())
535 << '{' << from_utf8(incfile) << '}';
537 incfile = changeExtension(incfile, ".tex");
538 incfile = latex_path(incfile);
540 os << '\\' << from_ascii(params().getCmdName())
541 << '{' << from_utf8(incfile) << '}';
543 } else if (type(params()) == LISTINGS) {
544 os << '\\' << from_ascii(params().getCmdName());
545 string const opt = to_utf8(params()["lstparams"]);
546 // opt is set in QInclude dialog and should have passed validation.
547 InsetListingsParams params(opt);
548 if (!params.params().empty())
549 os << "[" << from_utf8(params.params()) << "]";
550 os << '{' << from_utf8(incfile) << '}';
552 runparams.exportdata->addExternalFile(tex_format, writefile,
555 // \include don't want extension and demands that the
556 // file really have .tex
557 incfile = changeExtension(incfile, string());
558 incfile = latex_path(incfile);
560 os << '\\' << from_ascii(params().getCmdName()) << '{'
561 << from_utf8(incfile) << '}';
568 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
570 if (isVerbatim(params()) || isListings(params())) {
571 os << '[' << screenLabel() << '\n';
572 // FIXME: We don't know the encoding of the file, default to UTF-8.
573 os << includedFilename(buffer(), params()).fileContents("UTF-8");
575 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
577 docstring const str = '[' + screenLabel() + ']';
584 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
586 string incfile = to_utf8(params()["filename"]);
588 // Do nothing if no file name has been specified
592 string const included_file = includedFilename(buffer(), params()).absFilename();
594 // Check we're not trying to include ourselves.
595 // FIXME RECURSIVE INCLUDE
596 // This isn't sufficient, as the inclusion could be downstream.
597 // But it'll have to do for now.
598 if (buffer().absFileName() == included_file) {
599 Alert::error(_("Recursive input"),
600 bformat(_("Attempted to include file %1$s in itself! "
601 "Ignoring inclusion."), from_utf8(incfile)));
605 // write it to a file (so far the complete file)
606 string const exportfile = changeExtension(incfile, ".sgml");
607 DocFileName writefile(changeExtension(included_file, ".sgml"));
609 if (loadIfNeeded(buffer(), params())) {
610 Buffer * tmp = theBufferList().getBuffer(included_file);
612 string const mangled = writefile.mangledFilename();
613 writefile = makeAbsPath(mangled,
614 buffer().masterBuffer()->temppath());
618 LYXERR(Debug::LATEX, "incfile:" << incfile);
619 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
620 LYXERR(Debug::LATEX, "writefile:" << writefile);
622 tmp->makeDocBookFile(writefile, runparams, true);
625 runparams.exportdata->addExternalFile("docbook", writefile,
627 runparams.exportdata->addExternalFile("docbook-xml", writefile,
630 if (isVerbatim(params()) || isListings(params())) {
631 os << "<inlinegraphic fileref=\""
632 << '&' << include_label << ';'
633 << "\" format=\"linespecific\">";
635 os << '&' << include_label << ';';
641 void InsetInclude::validate(LaTeXFeatures & features) const
643 string incfile = to_utf8(params()["filename"]);
646 BOOST_ASSERT(&buffer() == &features.buffer());
648 string const included_file =
649 includedFilename(buffer(), params()).availableFile().absFilename();
651 if (isLyXFilename(included_file))
652 writefile = changeExtension(included_file, ".sgml");
654 writefile = included_file;
656 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
657 incfile = DocFileName(writefile).mangledFilename();
658 writefile = makeAbsPath(incfile,
659 buffer().masterBuffer()->temppath()).absFilename();
662 features.includeFile(include_label, writefile);
664 if (isVerbatim(params()))
665 features.require("verbatim");
666 else if (isListings(params()))
667 features.require("listings");
669 // Here we must do the fun stuff...
670 // Load the file in the include if it needs
672 if (loadIfNeeded(buffer(), params())) {
674 Buffer * const tmp = theBufferList().getBuffer(included_file);
675 // make sure the buffer isn't us
676 // FIXME RECURSIVE INCLUDES
677 // This is not sufficient, as recursive includes could be
678 // more than a file away. But it will do for now.
679 if (tmp && tmp != &buffer()) {
680 // We must temporarily change features.buffer,
681 // otherwise it would always be the master buffer,
682 // and nested includes would not work.
683 features.setBuffer(*tmp);
684 tmp->validate(features);
685 features.setBuffer(buffer());
691 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
692 InsetIterator const & /*di*/) const
694 if (loadIfNeeded(buffer(), params())) {
695 string const included_file = includedFilename(buffer(), params()).absFilename();
696 Buffer * tmp = theBufferList().getBuffer(included_file);
697 //FIXME This is kind of a dirty hack and should be made reasonable.
699 keys.fillWithBibKeys(tmp);
700 tmp->setParent(&buffer());
705 void InsetInclude::updateBibfilesCache()
707 Buffer * const tmp = getChildBuffer(buffer(), params());
710 tmp->updateBibfilesCache();
711 tmp->setParent(&buffer());
716 EmbeddedFileList const &
717 InsetInclude::getBibfilesCache(Buffer const & buffer) const
719 Buffer * const tmp = getChildBuffer(buffer, params());
722 EmbeddedFileList const & cache = tmp->getBibfilesCache();
723 tmp->setParent(&buffer);
726 static EmbeddedFileList const empty;
731 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
733 BOOST_ASSERT(mi.base.bv);
735 bool use_preview = false;
736 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
737 graphics::PreviewImage const * pimage =
738 preview_->getPreviewImage(mi.base.bv->buffer());
739 use_preview = pimage && pimage->image();
743 preview_->metrics(mi, dim);
747 button_.update(screenLabel(), true);
749 button_.metrics(mi, dim);
752 Box b(0, dim.wid, -dim.asc, dim.des);
757 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
759 BOOST_ASSERT(pi.base.bv);
761 bool use_preview = false;
762 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
763 graphics::PreviewImage const * pimage =
764 preview_->getPreviewImage(pi.base.bv->buffer());
765 use_preview = pimage && pimage->image();
769 preview_->draw(pi, x, y);
771 button_.draw(pi, x, y);
775 Inset::DisplayType InsetInclude::display() const
777 return type(params()) == INPUT ? Inline : AlignCenter;
786 void InsetInclude::fileChanged() const
788 Buffer const * const buffer = updateFrontend();
792 preview_->removePreview(*buffer);
793 add_preview(*preview_.get(), *this, *buffer);
794 preview_->startLoading(*buffer);
800 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
802 FileName const included_file = includedFilename(buffer, params);
804 return type(params) == INPUT && params.preview() &&
805 included_file.isReadableFile();
809 docstring latexString(InsetInclude const & inset)
812 // We don't need to set runparams.encoding since this will be done
813 // by latex() anyway.
814 OutputParams runparams(0);
815 runparams.flavor = OutputParams::LATEX;
816 inset.latex(os, runparams);
822 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
823 Buffer const & buffer)
825 InsetCommandParams const & params = inset.params();
826 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
827 preview_wanted(params, buffer)) {
828 renderer.setAbsFile(includedFilename(buffer, params));
829 docstring const snippet = latexString(inset);
830 renderer.addPreview(snippet, buffer);
837 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
839 Buffer const & buffer = ploader.buffer();
840 if (!preview_wanted(params(), buffer))
842 preview_->setAbsFile(includedFilename(buffer, params()));
843 docstring const snippet = latexString(*this);
844 preview_->addPreview(snippet, ploader);
848 void InsetInclude::addToToc(ParConstIterator const & cpit) const
850 bool const embedded_status = !params()["embed"].empty();
851 TocBackend & backend = buffer().tocBackend();
853 if (isListings(params())) {
855 label_->addToToc(cpit);
857 InsetListingsParams p(to_utf8(params()["lstparams"]));
858 string caption = p.getParamValue("caption");
861 Toc & toc = backend.toc("listing");
862 docstring str = convert<docstring>(toc.size() + 1)
863 + ". " + from_utf8(caption);
864 if (embedded_status) {
865 backend.toc("embedded").push_back(TocItem(cpit, 0, str));
866 str += _(" (embedded)");
868 ParConstIterator pit = cpit;
869 pit.push_back(*this);
870 toc.push_back(TocItem(pit, 0, str));
873 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
876 // Add it to the embedded list nonetheless.
877 backend.toc("embedded").push_back(TocItem(cpit, 0,
878 params()["filename"]));
882 Toc & toc = backend.toc("child");
883 docstring str = childbuffer->fileName().displayName();
884 if (embedded_status) {
885 backend.toc("embedded").push_back(TocItem(cpit, 0, str));
886 str += _(" (embedded)");
888 toc.push_back(TocItem(cpit, 0, str));
890 TocList & toclist = backend.tocs();
891 TocList const & childtoclist = childbuffer->tocBackend().tocs();
892 TocList::const_iterator it = childtoclist.begin();
893 TocList::const_iterator const end = childtoclist.end();
894 for(; it != end; ++it)
895 toclist[it->first].insert(toclist[it->first].end(),
896 it->second.begin(), it->second.end());
900 void InsetInclude::updateLabels(ParIterator const & it)
902 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
904 lyx::updateLabels(*childbuffer, true);
907 if (!isListings(params()))
911 label_->updateLabels(it);
913 InsetListingsParams const par(to_utf8(params()["lstparams"]));
914 if (par.getParamValue("caption").empty()) {
915 listings_label_.clear();
918 Counters & counters = buffer().params().documentClass().counters();
919 docstring const cnt = from_ascii("listing");
920 listings_label_ = buffer().B_("Program Listing");
921 if (counters.hasCounter(cnt)) {
923 listings_label_ += " " + convert<docstring>(counters.value(cnt));
928 void InsetInclude::registerEmbeddedFiles(EmbeddedFileList & files) const
930 files.registerFile(includedFilename(buffer(), params()), this, buffer());
934 void InsetInclude::updateEmbeddedFile(EmbeddedFile const & file)
936 InsetCommandParams p = params();
937 p["filename"] = from_utf8(file.outputFilename());
938 p["embed"] = file.embedded() ? from_utf8(file.inzipName()) : docstring();