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 "DispatchResult.h"
23 #include "ErrorList.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
29 #include "LayoutFile.h"
34 #include "MetricsInfo.h"
35 #include "OutputParams.h"
36 #include "TextClass.h"
37 #include "TocBackend.h"
39 #include "frontends/alert.h"
40 #include "frontends/Painter.h"
42 #include "graphics/PreviewImage.h"
43 #include "graphics/PreviewLoader.h"
45 #include "insets/InsetLabel.h"
46 #include "insets/InsetListingsParams.h"
47 #include "insets/RenderPreview.h"
49 #include "support/convert.h"
50 #include "support/debug.h"
51 #include "support/docstream.h"
52 #include "support/FileNameList.h"
53 #include "support/filetools.h"
54 #include "support/gettext.h"
55 #include "support/lassert.h"
56 #include "support/lstrings.h" // contains
57 #include "support/lyxalgo.h"
59 #include <boost/bind.hpp>
62 using namespace lyx::support;
66 namespace Alert = frontend::Alert;
71 docstring const uniqueID()
73 static unsigned int seed = 1000;
74 return "file" + convert<docstring>(++seed);
78 /// the type of inclusion
80 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
84 Types type(string const & s)
88 if (s == "verbatiminput")
90 if (s == "verbatiminput*")
92 if (s == "lstinputlisting")
100 Types type(InsetCommandParams const & params)
102 return type(params.getCmdName());
106 bool isListings(InsetCommandParams const & params)
108 return type(params) == LISTINGS;
112 bool isVerbatim(InsetCommandParams const & params)
114 Types const t = type(params);
115 return t == VERB || t == VERBAST;
119 bool isInputOrInclude(InsetCommandParams const & params)
121 Types const t = type(params);
122 return t == INPUT || t == INCLUDE;
126 FileName const masterFileName(Buffer const & buffer)
128 return buffer.masterBuffer()->fileName();
132 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
135 string const parentFilename(Buffer const & buffer)
137 return buffer.absFileName();
141 FileName const includedFilename(Buffer const & buffer,
142 InsetCommandParams const & params)
144 return makeAbsPath(to_utf8(params["filename"]),
145 onlyPath(parentFilename(buffer)));
149 InsetLabel * createLabel(docstring const & label_str)
151 if (label_str.empty())
153 InsetCommandParams icp(LABEL_CODE);
154 icp["name"] = label_str;
155 return new InsetLabel(icp);
161 InsetInclude::InsetInclude(InsetCommandParams const & p)
162 : InsetCommand(p, "include"), include_label(uniqueID()),
163 preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
165 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
167 if (isListings(params())) {
168 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
169 label_ = createLabel(from_utf8(listing_params.getParamValue("label")));
174 InsetInclude::InsetInclude(InsetInclude const & other)
175 : InsetCommand(other), include_label(other.include_label),
176 preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
178 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
181 label_ = new InsetLabel(*other.label_);
185 InsetInclude::~InsetInclude()
191 void InsetInclude::setBuffer(Buffer & buffer)
193 InsetCommand::setBuffer(buffer);
195 label_->setBuffer(buffer);
199 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
202 // This is only correct for the case of listings, but it'll do for now.
203 // In the other cases, this second parameter should just be empty.
204 static ParamInfo param_info_;
205 if (param_info_.empty()) {
206 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
207 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
213 bool InsetInclude::isCompatibleCommand(string const & s)
215 return type(s) != NONE;
219 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
221 LASSERT(&cur.buffer() == &buffer(), /**/);
222 switch (cmd.action) {
224 case LFUN_INSET_EDIT: {
225 editIncluded(to_utf8(params()["filename"]));
229 case LFUN_INSET_MODIFY: {
230 InsetCommandParams p(INCLUDE_CODE);
231 if (cmd.getArg(0) == "changetype") {
232 InsetCommand::doDispatch(cur, cmd);
235 InsetCommand::string2params("include", to_utf8(cmd.argument()), p);
236 if (!p.getCmdName().empty()) {
238 InsetListingsParams new_params(to_utf8(p["lstparams"]));
239 docstring const label_str = from_utf8(new_params.getParamValue("label"));
240 if (label_str.empty())
243 label_->updateCommand(label_str);
245 label_ = createLabel(label_str);
246 label_->setBuffer(buffer());
256 //pass everything else up the chain
258 InsetCommand::doDispatch(cur, cmd);
264 void InsetInclude::editIncluded(string const & file)
266 string const ext = support::getExtension(file);
268 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
271 // tex file or other text file in verbatim mode
272 formats.edit(buffer(),
273 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
278 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
279 FuncStatus & flag) const
281 switch (cmd.action) {
283 case LFUN_INSET_EDIT:
284 case LFUN_INSET_MODIFY:
285 flag.setEnabled(true);
289 return InsetCommand::getStatus(cur, cmd, flag);
294 void InsetInclude::setParams(InsetCommandParams const & p)
296 InsetCommand::setParams(p);
299 if (preview_->monitoring())
300 preview_->stopMonitoring();
302 if (type(params()) == INPUT)
303 add_preview(*preview_, *this, buffer());
305 buffer().updateBibfilesCache();
309 docstring InsetInclude::screenLabel() const
313 switch (type(params())) {
315 temp = buffer().B_("Input");
318 temp = buffer().B_("Verbatim Input");
321 temp = buffer().B_("Verbatim Input*");
324 temp = buffer().B_("Include");
327 temp = listings_label_;
330 LASSERT(false, /**/);
335 if (params()["filename"].empty())
338 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
344 /// return the child buffer if the file is a LyX doc and is loaded
345 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
347 if (isVerbatim(params) || isListings(params))
350 string const included_file = includedFilename(buffer, params).absFilename();
351 if (!isLyXFilename(included_file))
354 Buffer * childBuffer = loadIfNeeded(buffer, params);
356 // FIXME: recursive includes
357 return (childBuffer == &buffer) ? 0 : childBuffer;
361 /// return true if the file is or got loaded.
362 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
364 if (isVerbatim(params) || isListings(params))
367 string const parent_filename = parent.absFileName();
368 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
369 onlyPath(parent_filename));
371 if (!isLyXFilename(included_file.absFilename()))
374 Buffer * child = theBufferList().getBuffer(included_file);
376 // the readonly flag can/will be wrong, not anymore I think.
377 if (!included_file.exists())
380 child = theBufferList().newBuffer(included_file.absFilename());
382 // Buffer creation is not possible.
385 if (!child->loadLyXFile(included_file)) {
386 //close the buffer we just opened
387 theBufferList().release(child);
391 if (!child->errorList("Parse").empty()) {
392 // FIXME: Do something.
395 child->setParent(&parent);
400 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
402 string incfile = to_utf8(params()["filename"]);
404 // Do nothing if no file name has been specified
408 FileName const included_file = includedFilename(buffer(), params());
410 // Check we're not trying to include ourselves.
411 // FIXME RECURSIVE INCLUDE
412 // This isn't sufficient, as the inclusion could be downstream.
413 // But it'll have to do for now.
414 if (isInputOrInclude(params()) &&
415 buffer().absFileName() == included_file.absFilename())
417 Alert::error(_("Recursive input"),
418 bformat(_("Attempted to include file %1$s in itself! "
419 "Ignoring inclusion."), from_utf8(incfile)));
423 Buffer const * const masterBuffer = buffer().masterBuffer();
425 // if incfile is relative, make it relative to the master
427 if (!FileName(incfile).isAbsolute()) {
429 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
430 from_utf8(masterBuffer->filePath())));
433 // write it to a file (so far the complete file)
434 string const exportfile = changeExtension(incfile, ".tex");
435 string const mangled =
436 DocFileName(changeExtension(included_file.absFilename(),".tex")).
438 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
442 else if (!isValidLaTeXFilename(incfile)) {
443 frontend::Alert::warning(_("Invalid filename"),
444 _("The following filename is likely to cause trouble "
445 "when running the exported file through LaTeX: ") +
448 LYXERR(Debug::LATEX, "incfile:" << incfile);
449 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
450 LYXERR(Debug::LATEX, "writefile:" << writefile);
452 if (runparams.inComment || runparams.dryrun) {
453 //Don't try to load or copy the file if we're
454 //in a comment or doing a dryrun
455 } else if (isInputOrInclude(params()) &&
456 isLyXFilename(included_file.absFilename())) {
457 //if it's a LyX file and we're inputting or including,
458 //try to load it so we can write the associated latex
459 if (!loadIfNeeded(buffer(), params()))
462 Buffer * tmp = theBufferList().getBuffer(included_file);
464 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
466 docstring text = bformat(_("Included file `%1$s'\n"
467 "has textclass `%2$s'\n"
468 "while parent file has textclass `%3$s'."),
469 included_file.displayName(),
470 from_utf8(tmp->params().documentClass().name()),
471 from_utf8(masterBuffer->params().documentClass().name()));
472 Alert::warning(_("Different textclasses"), text);
475 // Make sure modules used in child are all included in master
476 //FIXME It might be worth loading the children's modules into the master
477 //over in BufferParams rather than doing this check.
478 vector<string> const masterModules = masterBuffer->params().getModules();
479 vector<string> const childModules = tmp->params().getModules();
480 vector<string>::const_iterator it = childModules.begin();
481 vector<string>::const_iterator end = childModules.end();
482 for (; it != end; ++it) {
483 string const module = *it;
484 vector<string>::const_iterator found =
485 find(masterModules.begin(), masterModules.end(), module);
486 if (found == masterModules.end()) {
487 docstring text = bformat(_("Included file `%1$s'\n"
488 "uses module `%2$s'\n"
489 "which is not used in parent file."),
490 included_file.displayName(), from_utf8(module));
491 Alert::warning(_("Module not found"), text);
495 tmp->markDepClean(masterBuffer->temppath());
497 // FIXME: handle non existing files
498 // FIXME: Second argument is irrelevant!
499 // since only_body is true, makeLaTeXFile will not look at second
500 // argument. Should we set it to string(), or should makeLaTeXFile
501 // make use of it somehow? (JMarc 20031002)
502 // The included file might be written in a different encoding
503 Encoding const * const oldEnc = runparams.encoding;
504 runparams.encoding = &tmp->params().encoding();
505 tmp->makeLaTeXFile(writefile,
506 masterFileName(buffer()).onlyPath().absFilename(),
508 runparams.encoding = oldEnc;
510 // In this case, it's not a LyX file, so we copy the file
511 // to the temp dir, so that .aux files etc. are not created
512 // in the original dir. Files included by this file will be
513 // found via input@path, see ../Buffer.cpp.
514 unsigned long const checksum_in = included_file.checksum();
515 unsigned long const checksum_out = writefile.checksum();
517 if (checksum_in != checksum_out) {
518 if (!included_file.copyTo(writefile)) {
521 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
522 "into the temporary directory."),
523 from_utf8(included_file.absFilename()))));
529 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
530 "latex" : "pdflatex";
531 if (isVerbatim(params())) {
532 incfile = latex_path(incfile);
534 os << '\\' << from_ascii(params().getCmdName()) << '{'
535 << from_utf8(incfile) << '}';
536 } else if (type(params()) == INPUT) {
537 runparams.exportdata->addExternalFile(tex_format, writefile,
540 // \input wants file with extension (default is .tex)
541 if (!isLyXFilename(included_file.absFilename())) {
542 incfile = latex_path(incfile);
544 os << '\\' << from_ascii(params().getCmdName())
545 << '{' << from_utf8(incfile) << '}';
547 incfile = changeExtension(incfile, ".tex");
548 incfile = latex_path(incfile);
550 os << '\\' << from_ascii(params().getCmdName())
551 << '{' << from_utf8(incfile) << '}';
553 } else if (type(params()) == LISTINGS) {
554 os << '\\' << from_ascii(params().getCmdName());
555 string const opt = to_utf8(params()["lstparams"]);
556 // opt is set in QInclude dialog and should have passed validation.
557 InsetListingsParams params(opt);
558 if (!params.params().empty())
559 os << "[" << from_utf8(params.params()) << "]";
560 os << '{' << from_utf8(incfile) << '}';
562 runparams.exportdata->addExternalFile(tex_format, writefile,
565 // \include don't want extension and demands that the
566 // file really have .tex
567 incfile = changeExtension(incfile, string());
568 incfile = latex_path(incfile);
570 os << '\\' << from_ascii(params().getCmdName()) << '{'
571 << from_utf8(incfile) << '}';
578 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
580 if (isVerbatim(params()) || isListings(params())) {
581 os << '[' << screenLabel() << '\n';
582 // FIXME: We don't know the encoding of the file, default to UTF-8.
583 os << includedFilename(buffer(), params()).fileContents("UTF-8");
585 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
587 docstring const str = '[' + screenLabel() + ']';
594 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
596 string incfile = to_utf8(params()["filename"]);
598 // Do nothing if no file name has been specified
602 string const included_file = includedFilename(buffer(), params()).absFilename();
604 // Check we're not trying to include ourselves.
605 // FIXME RECURSIVE INCLUDE
606 // This isn't sufficient, as the inclusion could be downstream.
607 // But it'll have to do for now.
608 if (buffer().absFileName() == included_file) {
609 Alert::error(_("Recursive input"),
610 bformat(_("Attempted to include file %1$s in itself! "
611 "Ignoring inclusion."), from_utf8(incfile)));
615 // write it to a file (so far the complete file)
616 string const exportfile = changeExtension(incfile, ".sgml");
617 DocFileName writefile(changeExtension(included_file, ".sgml"));
619 if (loadIfNeeded(buffer(), params())) {
620 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
622 string const mangled = writefile.mangledFilename();
623 writefile = makeAbsPath(mangled,
624 buffer().masterBuffer()->temppath());
628 LYXERR(Debug::LATEX, "incfile:" << incfile);
629 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
630 LYXERR(Debug::LATEX, "writefile:" << writefile);
632 tmp->makeDocBookFile(writefile, runparams, true);
635 runparams.exportdata->addExternalFile("docbook", writefile,
637 runparams.exportdata->addExternalFile("docbook-xml", writefile,
640 if (isVerbatim(params()) || isListings(params())) {
641 os << "<inlinegraphic fileref=\""
642 << '&' << include_label << ';'
643 << "\" format=\"linespecific\">";
645 os << '&' << include_label << ';';
651 void InsetInclude::validate(LaTeXFeatures & features) const
653 string incfile = to_utf8(params()["filename"]);
656 LASSERT(&buffer() == &features.buffer(), /**/);
658 string const included_file =
659 includedFilename(buffer(), params()).absFilename();
661 if (isLyXFilename(included_file))
662 writefile = changeExtension(included_file, ".sgml");
664 writefile = included_file;
666 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
667 incfile = DocFileName(writefile).mangledFilename();
668 writefile = makeAbsPath(incfile,
669 buffer().masterBuffer()->temppath()).absFilename();
672 features.includeFile(include_label, writefile);
674 if (isVerbatim(params()))
675 features.require("verbatim");
676 else if (isListings(params()))
677 features.require("listings");
679 // Here we must do the fun stuff...
680 // Load the file in the include if it needs
682 if (loadIfNeeded(buffer(), params())) {
684 Buffer * const tmp = theBufferList().getBuffer(FileName(included_file));
685 // make sure the buffer isn't us
686 // FIXME RECURSIVE INCLUDES
687 // This is not sufficient, as recursive includes could be
688 // more than a file away. But it will do for now.
689 if (tmp && tmp != &buffer()) {
690 // We must temporarily change features.buffer,
691 // otherwise it would always be the master buffer,
692 // and nested includes would not work.
693 features.setBuffer(*tmp);
694 tmp->validate(features);
695 features.setBuffer(buffer());
701 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
702 InsetIterator const & /*di*/) const
704 if (loadIfNeeded(buffer(), params())) {
705 string const included_file = includedFilename(buffer(), params()).absFilename();
706 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
707 BiblioInfo const & newkeys = tmp->localBibInfo();
708 keys.mergeBiblioInfo(newkeys);
713 void InsetInclude::updateBibfilesCache()
715 Buffer * const tmp = getChildBuffer(buffer(), params());
718 tmp->updateBibfilesCache();
719 tmp->setParent(&buffer());
724 support::FileNameList const &
725 InsetInclude::getBibfilesCache(Buffer const & buffer) const
727 Buffer * const tmp = getChildBuffer(buffer, params());
730 support::FileNameList const & cache = tmp->getBibfilesCache();
731 tmp->setParent(&buffer);
734 static support::FileNameList const empty;
739 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
741 LASSERT(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 LASSERT(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 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
785 return from_ascii("context-include");
789 Inset::DisplayType InsetInclude::display() const
791 return type(params()) == INPUT ? Inline : AlignCenter;
800 void InsetInclude::fileChanged() const
802 Buffer const * const buffer = updateFrontend();
806 preview_->removePreview(*buffer);
807 add_preview(*preview_.get(), *this, *buffer);
808 preview_->startLoading(*buffer);
814 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
816 FileName const included_file = includedFilename(buffer, params);
818 return type(params) == INPUT && params.preview() &&
819 included_file.isReadableFile();
823 docstring latexString(InsetInclude const & inset)
826 // We don't need to set runparams.encoding since this will be done
827 // by latex() anyway.
828 OutputParams runparams(0);
829 runparams.flavor = OutputParams::LATEX;
830 inset.latex(os, runparams);
836 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
837 Buffer const & buffer)
839 InsetCommandParams const & params = inset.params();
840 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
841 preview_wanted(params, buffer)) {
842 renderer.setAbsFile(includedFilename(buffer, params));
843 docstring const snippet = latexString(inset);
844 renderer.addPreview(snippet, buffer);
851 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
853 Buffer const & buffer = ploader.buffer();
854 if (!preview_wanted(params(), buffer))
856 preview_->setAbsFile(includedFilename(buffer, params()));
857 docstring const snippet = latexString(*this);
858 preview_->addPreview(snippet, ploader);
862 void InsetInclude::addToToc(DocIterator const & cpit)
864 TocBackend & backend = buffer().tocBackend();
866 if (isListings(params())) {
868 label_->addToToc(cpit);
870 InsetListingsParams p(to_utf8(params()["lstparams"]));
871 string caption = p.getParamValue("caption");
874 Toc & toc = backend.toc("listing");
875 docstring str = convert<docstring>(toc.size() + 1)
876 + ". " + from_utf8(caption);
877 DocIterator pit = cpit;
878 toc.push_back(TocItem(pit, 0, str));
881 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
885 Toc & toc = backend.toc("child");
886 docstring str = childbuffer->fileName().displayName();
887 toc.push_back(TocItem(cpit, 0, str));
889 TocList & toclist = backend.tocs();
890 childbuffer->tocBackend().update();
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_ = buffer().B_("Program Listing");
918 Buffer const & master = *buffer().masterBuffer();
919 Counters & counters = master.params().documentClass().counters();
920 docstring const cnt = from_ascii("listing");
921 listings_label_ = master.B_("Program Listing");
922 if (counters.hasCounter(cnt)) {
924 listings_label_ += " " + convert<docstring>(counters.value(cnt));