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 "BaseClassList.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/RenderPreview.h"
45 #include "insets/InsetListingsParams.h"
47 #include "support/debug.h"
48 #include "support/docstream.h"
49 #include "support/ExceptionMessage.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.enable(buffer.embedded(), &buffer);
154 InsetInclude::InsetInclude(InsetCommandParams const & p)
155 : InsetCommand(p, "include"), include_label(uniqueID()),
156 preview_(new RenderMonitoredPreview(this)), set_label_(false)
158 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
162 InsetInclude::InsetInclude(InsetInclude const & other)
163 : InsetCommand(other), include_label(other.include_label),
164 preview_(new RenderMonitoredPreview(this)), set_label_(false)
166 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
170 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
173 // This is only correct for the case of listings, but it'll do for now.
174 // In the other cases, this second parameter should just be empty.
175 static ParamInfo param_info_;
176 if (param_info_.empty()) {
177 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
178 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
179 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
185 bool InsetInclude::isCompatibleCommand(string const & s)
187 return type(s) != NONE;
191 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
193 BOOST_ASSERT(&cur.buffer() == &buffer());
194 switch (cmd.action) {
196 case LFUN_INSET_MODIFY: {
197 InsetCommandParams p(INCLUDE_CODE);
198 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
199 if (!p.getCmdName().empty()) {
201 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
202 InsetListingsParams par_new(to_utf8(p["lstparams"]));
203 if (par_old.getParamValue("label") !=
204 par_new.getParamValue("label")
205 && !par_new.getParamValue("label").empty())
206 cur.bv().buffer().changeRefsIfUnique(
207 from_utf8(par_old.getParamValue("label")),
208 from_utf8(par_new.getParamValue("label")),
212 // the embed parameter passed back from the dialog
213 // is "true" or "false", we need to change it.
214 if (p["embed"] == _("false"))
217 p["embed"] = from_utf8(EmbeddedFile(to_utf8(p["filename"]),
218 onlyPath(parentFilename(cur.buffer()))).inzipName());
220 includedFilename(cur.buffer(), p);
221 } catch (ExceptionMessage const & message) {
222 Alert::error(message.title_, message.details_);
223 // do not set parameter if an error happens
227 buffer().updateBibfilesCache();
233 //pass everything else up the chain
235 InsetCommand::doDispatch(cur, cmd);
241 void InsetInclude::setParams(InsetCommandParams const & p)
243 InsetCommand::setParams(p);
246 if (preview_->monitoring())
247 preview_->stopMonitoring();
249 if (type(params()) == INPUT)
250 add_preview(*preview_, *this, buffer());
254 docstring InsetInclude::screenLabel() const
258 switch (type(params())) {
260 temp = buffer().B_("Input");
263 temp = buffer().B_("Verbatim Input");
266 temp = buffer().B_("Verbatim Input*");
269 temp = buffer().B_("Include");
272 temp = listings_label_;
280 if (params()["filename"].empty())
283 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
285 if (!params()["embed"].empty())
286 temp += _(" (embedded)");
291 /// return the child buffer if the file is a LyX doc and is loaded
292 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
294 if (isVerbatim(params) || isListings(params))
297 string const included_file = includedFilename(buffer, params).absFilename();
298 if (!isLyXFilename(included_file))
301 Buffer * childBuffer = loadIfNeeded(buffer, params);
303 // FIXME: recursive includes
304 return (childBuffer == &buffer) ? 0 : childBuffer;
308 /// return true if the file is or got loaded.
309 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
311 if (isVerbatim(params) || isListings(params))
314 string const parent_filename = parent.absFileName();
315 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
316 onlyPath(parent_filename));
318 if (!isLyXFilename(included_file.absFilename()))
321 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
323 // the readonly flag can/will be wrong, not anymore I think.
324 if (!included_file.exists())
327 child = theBufferList().newBuffer(included_file.absFilename());
329 // Buffer creation is not possible.
332 if (!child->loadLyXFile(included_file)) {
333 //close the buffer we just opened
334 theBufferList().release(child);
338 if (!child->errorList("Parse").empty()) {
339 // FIXME: Do something.
342 child->setParent(&parent);
347 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
350 if (isVerbatim(params) || isListings(params))
353 string const parent_filename = parent->absFileName();
354 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
355 onlyPath(parent_filename));
357 if (!isLyXFilename(included_file.absFilename()))
360 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
361 // File not opened, nothing to close.
365 // Child document has a different parent, don't close it.
366 if (child->parent() != parent)
372 theBufferList().release(child);
374 updateLabels(*child);
378 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
380 string incfile = to_utf8(params()["filename"]);
382 // Do nothing if no file name has been specified
386 FileName const included_file =
387 includedFilename(buffer(), params()).availableFile();
389 // Check we're not trying to include ourselves.
390 // FIXME RECURSIVE INCLUDE
391 // This isn't sufficient, as the inclusion could be downstream.
392 // But it'll have to do for now.
393 if (isInputOrInclude(params()) &&
394 buffer().absFileName() == included_file.absFilename())
396 Alert::error(_("Recursive input"),
397 bformat(_("Attempted to include file %1$s in itself! "
398 "Ignoring inclusion."), from_utf8(incfile)));
402 Buffer const * const masterBuffer = buffer().masterBuffer();
404 // if incfile is relative, make it relative to the master
406 if (!FileName(incfile).isAbsolute()) {
408 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
409 from_utf8(masterBuffer->filePath())));
412 // write it to a file (so far the complete file)
413 string const exportfile = changeExtension(incfile, ".tex");
414 string const mangled =
415 DocFileName(changeExtension(included_file.absFilename(),".tex")).
417 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
421 else if (!isValidLaTeXFilename(incfile)) {
422 frontend::Alert::warning(_("Invalid filename"),
423 _("The following filename is likely to cause trouble "
424 "when running the exported file through LaTeX: ") +
427 LYXERR(Debug::LATEX, "incfile:" << incfile);
428 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
429 LYXERR(Debug::LATEX, "writefile:" << writefile);
431 if (runparams.inComment || runparams.dryrun) {
432 //Don't try to load or copy the file if we're
433 //in a comment or doing a dryrun
434 } else if (isInputOrInclude(params()) &&
435 isLyXFilename(included_file.absFilename())) {
436 //if it's a LyX file and we're inputting or including,
437 //try to load it so we can write the associated latex
438 if (!loadIfNeeded(buffer(), params()))
441 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
443 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
445 docstring text = bformat(_("Included file `%1$s'\n"
446 "has textclass `%2$s'\n"
447 "while parent file has textclass `%3$s'."),
448 included_file.displayName(),
449 from_utf8(tmp->params().documentClass().name()),
450 from_utf8(masterBuffer->params().documentClass().name()));
451 Alert::warning(_("Different textclasses"), text);
455 // Make sure modules used in child are all included in master
456 //FIXME It might be worth loading the children's modules into the master
457 //over in BufferParams rather than doing this check.
458 vector<string> const masterModules = masterBuffer->params().getModules();
459 vector<string> const childModules = tmp->params().getModules();
460 vector<string>::const_iterator it = childModules.begin();
461 vector<string>::const_iterator end = childModules.end();
462 for (; it != end; ++it) {
463 string const module = *it;
464 vector<string>::const_iterator found =
465 find(masterModules.begin(), masterModules.end(), module);
466 if (found != masterModules.end()) {
467 docstring text = bformat(_("Included file `%1$s'\n"
468 "uses module `%2$s'\n"
469 "which is not used in parent file."),
470 included_file.displayName(), from_utf8(module));
471 Alert::warning(_("Module not found"), text);
475 tmp->markDepClean(masterBuffer->temppath());
477 // FIXME: handle non existing files
478 // FIXME: Second argument is irrelevant!
479 // since only_body is true, makeLaTeXFile will not look at second
480 // argument. Should we set it to string(), or should makeLaTeXFile
481 // make use of it somehow? (JMarc 20031002)
482 // The included file might be written in a different encoding
483 Encoding const * const oldEnc = runparams.encoding;
484 runparams.encoding = &tmp->params().encoding();
485 tmp->makeLaTeXFile(writefile,
486 masterFileName(buffer()).onlyPath().absFilename(),
488 runparams.encoding = oldEnc;
490 // In this case, it's not a LyX file, so we copy the file
491 // to the temp dir, so that .aux files etc. are not created
492 // in the original dir. Files included by this file will be
493 // found via input@path, see ../Buffer.cpp.
494 unsigned long const checksum_in = included_file.checksum();
495 unsigned long const checksum_out = writefile.checksum();
497 if (checksum_in != checksum_out) {
498 if (!included_file.copyTo(writefile)) {
501 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
502 "into the temporary directory."),
503 from_utf8(included_file.absFilename()))));
509 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
510 "latex" : "pdflatex";
511 if (isVerbatim(params())) {
512 incfile = latex_path(incfile);
514 os << '\\' << from_ascii(params().getCmdName()) << '{'
515 << from_utf8(incfile) << '}';
516 } else if (type(params()) == INPUT) {
517 runparams.exportdata->addExternalFile(tex_format, writefile,
520 // \input wants file with extension (default is .tex)
521 if (!isLyXFilename(included_file.absFilename())) {
522 incfile = latex_path(incfile);
524 os << '\\' << from_ascii(params().getCmdName())
525 << '{' << from_utf8(incfile) << '}';
527 incfile = changeExtension(incfile, ".tex");
528 incfile = latex_path(incfile);
530 os << '\\' << from_ascii(params().getCmdName())
531 << '{' << from_utf8(incfile) << '}';
533 } else if (type(params()) == LISTINGS) {
534 os << '\\' << from_ascii(params().getCmdName());
535 string const opt = to_utf8(params()["lstparams"]);
536 // opt is set in QInclude dialog and should have passed validation.
537 InsetListingsParams params(opt);
538 if (!params.params().empty())
539 os << "[" << from_utf8(params.params()) << "]";
540 os << '{' << from_utf8(incfile) << '}';
542 runparams.exportdata->addExternalFile(tex_format, writefile,
545 // \include don't want extension and demands that the
546 // file really have .tex
547 incfile = changeExtension(incfile, string());
548 incfile = latex_path(incfile);
550 os << '\\' << from_ascii(params().getCmdName()) << '{'
551 << from_utf8(incfile) << '}';
558 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
560 if (isVerbatim(params()) || isListings(params())) {
561 os << '[' << screenLabel() << '\n';
562 // FIXME: We don't know the encoding of the file, default to UTF-8.
563 os << includedFilename(buffer(), params()).fileContents("UTF-8");
565 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
567 docstring const str = '[' + screenLabel() + ']';
574 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
576 string incfile = to_utf8(params()["filename"]);
578 // Do nothing if no file name has been specified
582 string const included_file = includedFilename(buffer(), params()).absFilename();
584 // Check we're not trying to include ourselves.
585 // FIXME RECURSIVE INCLUDE
586 // This isn't sufficient, as the inclusion could be downstream.
587 // But it'll have to do for now.
588 if (buffer().absFileName() == included_file) {
589 Alert::error(_("Recursive input"),
590 bformat(_("Attempted to include file %1$s in itself! "
591 "Ignoring inclusion."), from_utf8(incfile)));
595 // write it to a file (so far the complete file)
596 string const exportfile = changeExtension(incfile, ".sgml");
597 DocFileName writefile(changeExtension(included_file, ".sgml"));
599 if (loadIfNeeded(buffer(), params())) {
600 Buffer * tmp = theBufferList().getBuffer(included_file);
602 string const mangled = writefile.mangledFilename();
603 writefile = makeAbsPath(mangled,
604 buffer().masterBuffer()->temppath());
608 LYXERR(Debug::LATEX, "incfile:" << incfile);
609 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
610 LYXERR(Debug::LATEX, "writefile:" << writefile);
612 tmp->makeDocBookFile(writefile, runparams, true);
615 runparams.exportdata->addExternalFile("docbook", writefile,
617 runparams.exportdata->addExternalFile("docbook-xml", writefile,
620 if (isVerbatim(params()) || isListings(params())) {
621 os << "<inlinegraphic fileref=\""
622 << '&' << include_label << ';'
623 << "\" format=\"linespecific\">";
625 os << '&' << include_label << ';';
631 void InsetInclude::validate(LaTeXFeatures & features) const
633 string incfile = to_utf8(params()["filename"]);
636 BOOST_ASSERT(&buffer() == &features.buffer());
638 string const included_file =
639 includedFilename(buffer(), params()).availableFile().absFilename();
641 if (isLyXFilename(included_file))
642 writefile = changeExtension(included_file, ".sgml");
644 writefile = included_file;
646 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
647 incfile = DocFileName(writefile).mangledFilename();
648 writefile = makeAbsPath(incfile,
649 buffer().masterBuffer()->temppath()).absFilename();
652 features.includeFile(include_label, writefile);
654 if (isVerbatim(params()))
655 features.require("verbatim");
656 else if (isListings(params()))
657 features.require("listings");
659 // Here we must do the fun stuff...
660 // Load the file in the include if it needs
662 if (loadIfNeeded(buffer(), params())) {
664 Buffer * const tmp = theBufferList().getBuffer(included_file);
665 // make sure the buffer isn't us
666 // FIXME RECURSIVE INCLUDES
667 // This is not sufficient, as recursive includes could be
668 // more than a file away. But it will do for now.
669 if (tmp && tmp != &buffer()) {
670 // We must temporarily change features.buffer,
671 // otherwise it would always be the master buffer,
672 // and nested includes would not work.
673 features.setBuffer(*tmp);
674 tmp->validate(features);
675 features.setBuffer(buffer());
681 void InsetInclude::getLabelList(vector<docstring> & list) const
683 if (isListings(params())) {
684 InsetListingsParams p(to_utf8(params()["lstparams"]));
685 string label = p.getParamValue("label");
687 list.push_back(from_utf8(label));
689 else if (loadIfNeeded(buffer(), params())) {
690 string const included_file = includedFilename(buffer(), params()).absFilename();
691 Buffer * tmp = theBufferList().getBuffer(included_file);
693 tmp->getLabelList(list);
694 tmp->setParent(const_cast<Buffer *>(&buffer()));
699 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
700 InsetIterator const & /*di*/) const
702 if (loadIfNeeded(buffer(), params())) {
703 string const included_file = includedFilename(buffer(), params()).absFilename();
704 Buffer * tmp = theBufferList().getBuffer(included_file);
705 //FIXME This is kind of a dirty hack and should be made reasonable.
707 keys.fillWithBibKeys(tmp);
708 tmp->setParent(&buffer());
713 void InsetInclude::updateBibfilesCache()
715 Buffer * const tmp = getChildBuffer(buffer(), params());
718 tmp->updateBibfilesCache();
719 tmp->setParent(&buffer());
724 EmbeddedFileList const &
725 InsetInclude::getBibfilesCache(Buffer const & buffer) const
727 Buffer * const tmp = getChildBuffer(buffer, params());
730 EmbeddedFileList const & cache = tmp->getBibfilesCache();
731 tmp->setParent(&buffer);
734 static EmbeddedFileList const empty;
739 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
741 BOOST_ASSERT(mi.base.bv);
743 bool use_preview = false;
744 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
745 graphics::PreviewImage const * pimage =
746 preview_->getPreviewImage(mi.base.bv->buffer());
747 use_preview = pimage && pimage->image();
751 preview_->metrics(mi, dim);
755 button_.update(screenLabel(), true);
757 button_.metrics(mi, dim);
760 Box b(0, dim.wid, -dim.asc, dim.des);
765 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
767 BOOST_ASSERT(pi.base.bv);
769 bool use_preview = false;
770 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
771 graphics::PreviewImage const * pimage =
772 preview_->getPreviewImage(pi.base.bv->buffer());
773 use_preview = pimage && pimage->image();
777 preview_->draw(pi, x, y);
779 button_.draw(pi, x, y);
783 Inset::DisplayType InsetInclude::display() const
785 return type(params()) == INPUT ? Inline : AlignCenter;
794 void InsetInclude::fileChanged() const
796 Buffer const * const buffer = updateFrontend();
800 preview_->removePreview(*buffer);
801 add_preview(*preview_.get(), *this, *buffer);
802 preview_->startLoading(*buffer);
808 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
810 FileName const included_file = includedFilename(buffer, params);
812 return type(params) == INPUT && params.preview() &&
813 included_file.isReadableFile();
817 docstring latexString(InsetInclude const & inset)
820 // We don't need to set runparams.encoding since this will be done
821 // by latex() anyway.
822 OutputParams runparams(0);
823 runparams.flavor = OutputParams::LATEX;
824 inset.latex(os, runparams);
830 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
831 Buffer const & buffer)
833 InsetCommandParams const & params = inset.params();
834 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
835 preview_wanted(params, buffer)) {
836 renderer.setAbsFile(includedFilename(buffer, params));
837 docstring const snippet = latexString(inset);
838 renderer.addPreview(snippet, buffer);
845 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
847 Buffer const & buffer = ploader.buffer();
848 if (!preview_wanted(params(), buffer))
850 preview_->setAbsFile(includedFilename(buffer, params()));
851 docstring const snippet = latexString(*this);
852 preview_->addPreview(snippet, ploader);
856 void InsetInclude::addToToc(ParConstIterator const & cpit) const
858 if (isListings(params())) {
859 InsetListingsParams p(to_utf8(params()["lstparams"]));
860 string caption = p.getParamValue("caption");
863 Toc & toc = buffer().tocBackend().toc("listing");
864 docstring const str = convert<docstring>(toc.size() + 1)
865 + ". " + from_utf8(caption);
866 ParConstIterator pit = cpit;
867 pit.push_back(*this);
868 toc.push_back(TocItem(pit, 0, str));
871 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
875 TocList & toclist = buffer().tocBackend().tocs();
876 TocList const & childtoclist = childbuffer->tocBackend().tocs();
877 TocList::const_iterator it = childtoclist.begin();
878 TocList::const_iterator const end = childtoclist.end();
879 for(; it != end; ++it)
880 toclist[it->first].insert(toclist[it->first].end(),
881 it->second.begin(), it->second.end());
885 void InsetInclude::updateLabels(ParIterator const &)
887 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
889 lyx::updateLabels(*childbuffer, true);
892 if (!isListings(params()))
895 InsetListingsParams const par(to_utf8(params()["lstparams"]));
896 if (par.getParamValue("caption").empty()) {
897 listings_label_.clear();
900 Counters & counters = buffer().params().documentClass().counters();
901 docstring const cnt = from_ascii("listing");
902 listings_label_ = buffer().B_("Program Listing");
903 if (counters.hasCounter(cnt)) {
905 listings_label_ += " " + convert<docstring>(counters.value(cnt));
910 void InsetInclude::registerEmbeddedFiles(EmbeddedFileList & files) const
912 files.registerFile(includedFilename(buffer(), params()), this, buffer());
916 void InsetInclude::updateEmbeddedFile(EmbeddedFile const & file)
918 InsetCommandParams p = params();
919 p["filename"] = from_utf8(file.outputFilename());
920 p["embed"] = file.embedded() ? from_utf8(file.inzipName()) : docstring();