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"
16 #include "LayoutFile.h"
18 #include "buffer_funcs.h"
19 #include "BufferList.h"
20 #include "BufferParams.h"
21 #include "BufferView.h"
23 #include "DispatchResult.h"
24 #include "ErrorList.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
32 #include "MetricsInfo.h"
33 #include "OutputParams.h"
34 #include "TextClass.h"
35 #include "TocBackend.h"
37 #include "frontends/alert.h"
38 #include "frontends/Painter.h"
40 #include "graphics/PreviewImage.h"
41 #include "graphics/PreviewLoader.h"
43 #include "insets/InsetLabel.h"
44 #include "insets/InsetListingsParams.h"
45 #include "insets/RenderPreview.h"
47 #include "support/assert.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 FileName const includedFilename(Buffer const & buffer,
140 InsetCommandParams const & params)
142 return makeAbsPath(to_utf8(params["filename"]),
143 onlyPath(parentFilename(buffer)));
146 InsetLabel * createLabel(docstring const & label_str)
148 if (label_str.empty())
150 InsetCommandParams icp(LABEL_CODE);
151 icp["name"] = label_str;
152 return new InsetLabel(icp);
158 InsetInclude::InsetInclude(InsetCommandParams const & p)
159 : InsetCommand(p, "include"), include_label(uniqueID()),
160 preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
162 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
164 if (isListings(params())) {
165 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
166 label_ = createLabel(from_utf8(listing_params.getParamValue("label")));
171 InsetInclude::InsetInclude(InsetInclude const & other)
172 : InsetCommand(other), include_label(other.include_label),
173 preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
175 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
178 label_ = new InsetLabel(*other.label_);
182 InsetInclude::~InsetInclude()
185 if (isVerbatim(params()) || isListings(params()))
189 string const parent_filename = buffer().absFileName();
190 FileName const included_file = makeAbsPath(to_utf8(params()["filename"]),
191 onlyPath(parent_filename));
193 if (!isLyXFilename(included_file.absFilename()))
196 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
197 // File not opened, nothing to close.
201 // Child document has a different parent, don't close it.
202 if (child->parent() != &buffer())
206 theBufferList().release(child);
210 void InsetInclude::setBuffer(Buffer & buffer)
212 InsetCommand::setBuffer(buffer);
214 label_->setBuffer(buffer);
218 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
221 // This is only correct for the case of listings, but it'll do for now.
222 // In the other cases, this second parameter should just be empty.
223 static ParamInfo param_info_;
224 if (param_info_.empty()) {
225 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
226 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
232 bool InsetInclude::isCompatibleCommand(string const & s)
234 return type(s) != NONE;
238 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
240 LASSERT(&cur.buffer() == &buffer(), /**/);
241 switch (cmd.action) {
243 case LFUN_INSET_MODIFY: {
244 InsetCommandParams p(INCLUDE_CODE);
245 InsetCommand::string2params("include", to_utf8(cmd.argument()), p);
246 if (!p.getCmdName().empty()) {
248 InsetListingsParams new_params(to_utf8(p["lstparams"]));
249 docstring const label_str = from_utf8(new_params.getParamValue("label"));
250 if (label_str.empty())
253 label_->updateCommand(label_str);
255 label_ = createLabel(label_str);
256 label_->setBuffer(buffer());
266 //pass everything else up the chain
268 InsetCommand::doDispatch(cur, cmd);
274 void InsetInclude::setParams(InsetCommandParams const & p)
276 InsetCommand::setParams(p);
279 if (preview_->monitoring())
280 preview_->stopMonitoring();
282 if (type(params()) == INPUT)
283 add_preview(*preview_, *this, buffer());
285 buffer().updateBibfilesCache();
289 docstring InsetInclude::screenLabel() const
293 switch (type(params())) {
295 temp = buffer().B_("Input");
298 temp = buffer().B_("Verbatim Input");
301 temp = buffer().B_("Verbatim Input*");
304 temp = buffer().B_("Include");
307 temp = listings_label_;
310 LASSERT(false, /**/);
315 if (params()["filename"].empty())
318 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
324 /// return the child buffer if the file is a LyX doc and is loaded
325 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
327 if (isVerbatim(params) || isListings(params))
330 string const included_file = includedFilename(buffer, params).absFilename();
331 if (!isLyXFilename(included_file))
334 Buffer * childBuffer = loadIfNeeded(buffer, params);
336 // FIXME: recursive includes
337 return (childBuffer == &buffer) ? 0 : childBuffer;
341 /// return true if the file is or got loaded.
342 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
344 if (isVerbatim(params) || isListings(params))
347 string const parent_filename = parent.absFileName();
348 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
349 onlyPath(parent_filename));
351 if (!isLyXFilename(included_file.absFilename()))
354 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
356 // the readonly flag can/will be wrong, not anymore I think.
357 if (!included_file.exists())
360 child = theBufferList().newBuffer(included_file.absFilename());
362 // Buffer creation is not possible.
365 if (!child->loadLyXFile(included_file)) {
366 //close the buffer we just opened
367 theBufferList().release(child);
371 if (!child->errorList("Parse").empty()) {
372 // FIXME: Do something.
375 child->setParent(&parent);
380 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
382 string incfile = to_utf8(params()["filename"]);
384 // Do nothing if no file name has been specified
388 FileName const included_file =
389 includedFilename(buffer(), params());
391 // Check we're not trying to include ourselves.
392 // FIXME RECURSIVE INCLUDE
393 // This isn't sufficient, as the inclusion could be downstream.
394 // But it'll have to do for now.
395 if (isInputOrInclude(params()) &&
396 buffer().absFileName() == included_file.absFilename())
398 Alert::error(_("Recursive input"),
399 bformat(_("Attempted to include file %1$s in itself! "
400 "Ignoring inclusion."), from_utf8(incfile)));
404 Buffer const * const masterBuffer = buffer().masterBuffer();
406 // if incfile is relative, make it relative to the master
408 if (!FileName(incfile).isAbsolute()) {
410 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
411 from_utf8(masterBuffer->filePath())));
414 // write it to a file (so far the complete file)
415 string const exportfile = changeExtension(incfile, ".tex");
416 string const mangled =
417 DocFileName(changeExtension(included_file.absFilename(),".tex")).
419 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
423 else if (!isValidLaTeXFilename(incfile)) {
424 frontend::Alert::warning(_("Invalid filename"),
425 _("The following filename is likely to cause trouble "
426 "when running the exported file through LaTeX: ") +
429 LYXERR(Debug::LATEX, "incfile:" << incfile);
430 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
431 LYXERR(Debug::LATEX, "writefile:" << writefile);
433 if (runparams.inComment || runparams.dryrun) {
434 //Don't try to load or copy the file if we're
435 //in a comment or doing a dryrun
436 } else if (isInputOrInclude(params()) &&
437 isLyXFilename(included_file.absFilename())) {
438 //if it's a LyX file and we're inputting or including,
439 //try to load it so we can write the associated latex
440 if (!loadIfNeeded(buffer(), params()))
443 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
445 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
447 docstring text = bformat(_("Included file `%1$s'\n"
448 "has textclass `%2$s'\n"
449 "while parent file has textclass `%3$s'."),
450 included_file.displayName(),
451 from_utf8(tmp->params().documentClass().name()),
452 from_utf8(masterBuffer->params().documentClass().name()));
453 Alert::warning(_("Different textclasses"), text);
456 // Make sure modules used in child are all included in master
457 //FIXME It might be worth loading the children's modules into the master
458 //over in BufferParams rather than doing this check.
459 vector<string> const masterModules = masterBuffer->params().getModules();
460 vector<string> const childModules = tmp->params().getModules();
461 vector<string>::const_iterator it = childModules.begin();
462 vector<string>::const_iterator end = childModules.end();
463 for (; it != end; ++it) {
464 string const module = *it;
465 vector<string>::const_iterator found =
466 find(masterModules.begin(), masterModules.end(), module);
467 if (found == masterModules.end()) {
468 docstring text = bformat(_("Included file `%1$s'\n"
469 "uses module `%2$s'\n"
470 "which is not used in parent file."),
471 included_file.displayName(), from_utf8(module));
472 Alert::warning(_("Module not found"), text);
476 tmp->markDepClean(masterBuffer->temppath());
478 // FIXME: handle non existing files
479 // FIXME: Second argument is irrelevant!
480 // since only_body is true, makeLaTeXFile will not look at second
481 // argument. Should we set it to string(), or should makeLaTeXFile
482 // make use of it somehow? (JMarc 20031002)
483 // The included file might be written in a different encoding
484 Encoding const * const oldEnc = runparams.encoding;
485 runparams.encoding = &tmp->params().encoding();
486 tmp->makeLaTeXFile(writefile,
487 masterFileName(buffer()).onlyPath().absFilename(),
489 runparams.encoding = oldEnc;
491 // In this case, it's not a LyX file, so we copy the file
492 // to the temp dir, so that .aux files etc. are not created
493 // in the original dir. Files included by this file will be
494 // found via input@path, see ../Buffer.cpp.
495 unsigned long const checksum_in = included_file.checksum();
496 unsigned long const checksum_out = writefile.checksum();
498 if (checksum_in != checksum_out) {
499 if (!included_file.copyTo(writefile)) {
502 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
503 "into the temporary directory."),
504 from_utf8(included_file.absFilename()))));
510 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
511 "latex" : "pdflatex";
512 if (isVerbatim(params())) {
513 incfile = latex_path(incfile);
515 os << '\\' << from_ascii(params().getCmdName()) << '{'
516 << from_utf8(incfile) << '}';
517 } else if (type(params()) == INPUT) {
518 runparams.exportdata->addExternalFile(tex_format, writefile,
521 // \input wants file with extension (default is .tex)
522 if (!isLyXFilename(included_file.absFilename())) {
523 incfile = latex_path(incfile);
525 os << '\\' << from_ascii(params().getCmdName())
526 << '{' << from_utf8(incfile) << '}';
528 incfile = changeExtension(incfile, ".tex");
529 incfile = latex_path(incfile);
531 os << '\\' << from_ascii(params().getCmdName())
532 << '{' << from_utf8(incfile) << '}';
534 } else if (type(params()) == LISTINGS) {
535 os << '\\' << from_ascii(params().getCmdName());
536 string const opt = to_utf8(params()["lstparams"]);
537 // opt is set in QInclude dialog and should have passed validation.
538 InsetListingsParams params(opt);
539 if (!params.params().empty())
540 os << "[" << from_utf8(params.params()) << "]";
541 os << '{' << from_utf8(incfile) << '}';
543 runparams.exportdata->addExternalFile(tex_format, writefile,
546 // \include don't want extension and demands that the
547 // file really have .tex
548 incfile = changeExtension(incfile, string());
549 incfile = latex_path(incfile);
551 os << '\\' << from_ascii(params().getCmdName()) << '{'
552 << from_utf8(incfile) << '}';
559 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
561 if (isVerbatim(params()) || isListings(params())) {
562 os << '[' << screenLabel() << '\n';
563 // FIXME: We don't know the encoding of the file, default to UTF-8.
564 os << includedFilename(buffer(), params()).fileContents("UTF-8");
566 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
568 docstring const str = '[' + screenLabel() + ']';
575 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
577 string incfile = to_utf8(params()["filename"]);
579 // Do nothing if no file name has been specified
583 string const included_file = includedFilename(buffer(), params()).absFilename();
585 // Check we're not trying to include ourselves.
586 // FIXME RECURSIVE INCLUDE
587 // This isn't sufficient, as the inclusion could be downstream.
588 // But it'll have to do for now.
589 if (buffer().absFileName() == included_file) {
590 Alert::error(_("Recursive input"),
591 bformat(_("Attempted to include file %1$s in itself! "
592 "Ignoring inclusion."), from_utf8(incfile)));
596 // write it to a file (so far the complete file)
597 string const exportfile = changeExtension(incfile, ".sgml");
598 DocFileName writefile(changeExtension(included_file, ".sgml"));
600 if (loadIfNeeded(buffer(), params())) {
601 Buffer * tmp = theBufferList().getBuffer(included_file);
603 string const mangled = writefile.mangledFilename();
604 writefile = makeAbsPath(mangled,
605 buffer().masterBuffer()->temppath());
609 LYXERR(Debug::LATEX, "incfile:" << incfile);
610 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
611 LYXERR(Debug::LATEX, "writefile:" << writefile);
613 tmp->makeDocBookFile(writefile, runparams, true);
616 runparams.exportdata->addExternalFile("docbook", writefile,
618 runparams.exportdata->addExternalFile("docbook-xml", writefile,
621 if (isVerbatim(params()) || isListings(params())) {
622 os << "<inlinegraphic fileref=\""
623 << '&' << include_label << ';'
624 << "\" format=\"linespecific\">";
626 os << '&' << include_label << ';';
632 void InsetInclude::validate(LaTeXFeatures & features) const
634 string incfile = to_utf8(params()["filename"]);
637 LASSERT(&buffer() == &features.buffer(), /**/);
639 string const included_file =
640 includedFilename(buffer(), params()).absFilename();
642 if (isLyXFilename(included_file))
643 writefile = changeExtension(included_file, ".sgml");
645 writefile = included_file;
647 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
648 incfile = DocFileName(writefile).mangledFilename();
649 writefile = makeAbsPath(incfile,
650 buffer().masterBuffer()->temppath()).absFilename();
653 features.includeFile(include_label, writefile);
655 if (isVerbatim(params()))
656 features.require("verbatim");
657 else if (isListings(params()))
658 features.require("listings");
660 // Here we must do the fun stuff...
661 // Load the file in the include if it needs
663 if (loadIfNeeded(buffer(), params())) {
665 Buffer * const tmp = theBufferList().getBuffer(included_file);
666 // make sure the buffer isn't us
667 // FIXME RECURSIVE INCLUDES
668 // This is not sufficient, as recursive includes could be
669 // more than a file away. But it will do for now.
670 if (tmp && tmp != &buffer()) {
671 // We must temporarily change features.buffer,
672 // otherwise it would always be the master buffer,
673 // and nested includes would not work.
674 features.setBuffer(*tmp);
675 tmp->validate(features);
676 features.setBuffer(buffer());
682 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
683 InsetIterator const & /*di*/) const
685 if (loadIfNeeded(buffer(), params())) {
686 string const included_file = includedFilename(buffer(), params()).absFilename();
687 Buffer * tmp = theBufferList().getBuffer(included_file);
688 //FIXME This is kind of a dirty hack and should be made reasonable.
690 keys.fillWithBibKeys(tmp);
691 tmp->setParent(&buffer());
696 void InsetInclude::updateBibfilesCache()
698 Buffer * const tmp = getChildBuffer(buffer(), params());
701 tmp->updateBibfilesCache();
702 tmp->setParent(&buffer());
707 EmbeddedFileList const &
708 InsetInclude::getBibfilesCache(Buffer const & buffer) const
710 Buffer * const tmp = getChildBuffer(buffer, params());
713 EmbeddedFileList const & cache = tmp->getBibfilesCache();
714 tmp->setParent(&buffer);
717 static EmbeddedFileList const empty;
722 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
724 LASSERT(mi.base.bv, /**/);
726 bool use_preview = false;
727 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
728 graphics::PreviewImage const * pimage =
729 preview_->getPreviewImage(mi.base.bv->buffer());
730 use_preview = pimage && pimage->image();
734 preview_->metrics(mi, dim);
738 button_.update(screenLabel(), true);
740 button_.metrics(mi, dim);
743 Box b(0, dim.wid, -dim.asc, dim.des);
748 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
750 LASSERT(pi.base.bv, /**/);
752 bool use_preview = false;
753 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
754 graphics::PreviewImage const * pimage =
755 preview_->getPreviewImage(pi.base.bv->buffer());
756 use_preview = pimage && pimage->image();
760 preview_->draw(pi, x, y);
762 button_.draw(pi, x, y);
766 Inset::DisplayType InsetInclude::display() const
768 return type(params()) == INPUT ? Inline : AlignCenter;
777 void InsetInclude::fileChanged() const
779 Buffer const * const buffer = updateFrontend();
783 preview_->removePreview(*buffer);
784 add_preview(*preview_.get(), *this, *buffer);
785 preview_->startLoading(*buffer);
791 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
793 FileName const included_file = includedFilename(buffer, params);
795 return type(params) == INPUT && params.preview() &&
796 included_file.isReadableFile();
800 docstring latexString(InsetInclude const & inset)
803 // We don't need to set runparams.encoding since this will be done
804 // by latex() anyway.
805 OutputParams runparams(0);
806 runparams.flavor = OutputParams::LATEX;
807 inset.latex(os, runparams);
813 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
814 Buffer const & buffer)
816 InsetCommandParams const & params = inset.params();
817 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
818 preview_wanted(params, buffer)) {
819 renderer.setAbsFile(includedFilename(buffer, params));
820 docstring const snippet = latexString(inset);
821 renderer.addPreview(snippet, buffer);
828 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
830 Buffer const & buffer = ploader.buffer();
831 if (!preview_wanted(params(), buffer))
833 preview_->setAbsFile(includedFilename(buffer, params()));
834 docstring const snippet = latexString(*this);
835 preview_->addPreview(snippet, ploader);
839 void InsetInclude::addToToc(ParConstIterator const & cpit) const
841 TocBackend & backend = buffer().tocBackend();
843 if (isListings(params())) {
845 label_->addToToc(cpit);
847 InsetListingsParams p(to_utf8(params()["lstparams"]));
848 string caption = p.getParamValue("caption");
851 Toc & toc = backend.toc("listing");
852 docstring str = convert<docstring>(toc.size() + 1)
853 + ". " + from_utf8(caption);
854 ParConstIterator pit = cpit;
855 pit.push_back(*this);
856 toc.push_back(TocItem(pit, 0, str));
859 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
863 Toc & toc = backend.toc("child");
864 docstring str = childbuffer->fileName().displayName();
865 toc.push_back(TocItem(cpit, 0, str));
867 TocList & toclist = backend.tocs();
868 TocList const & childtoclist = childbuffer->tocBackend().tocs();
869 TocList::const_iterator it = childtoclist.begin();
870 TocList::const_iterator const end = childtoclist.end();
871 for(; it != end; ++it)
872 toclist[it->first].insert(toclist[it->first].end(),
873 it->second.begin(), it->second.end());
877 void InsetInclude::updateLabels(ParIterator const & it)
879 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
881 lyx::updateLabels(*childbuffer, true);
884 if (!isListings(params()))
888 label_->updateLabels(it);
890 InsetListingsParams const par(to_utf8(params()["lstparams"]));
891 if (par.getParamValue("caption").empty()) {
892 listings_label_.clear();
895 Counters & counters = buffer().params().documentClass().counters();
896 docstring const cnt = from_ascii("listing");
897 listings_label_ = buffer().B_("Program Listing");
898 if (counters.hasCounter(cnt)) {
900 listings_label_ += " " + convert<docstring>(counters.value(cnt));