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 Kimberly 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"
21 #include "Converter.h"
24 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LaTeXFeatures.h"
30 #include "LayoutModuleList.h"
32 #include "MetricsInfo.h"
33 #include "output_plaintext.h"
34 #include "output_xhtml.h"
35 #include "texstream.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 "mathed/MacroTable.h"
51 #include "support/convert.h"
52 #include "support/debug.h"
53 #include "support/docstream.h"
54 #include "support/FileName.h"
55 #include "support/FileNameList.h"
56 #include "support/filetools.h"
57 #include "support/gettext.h"
58 #include "support/lassert.h"
59 #include "support/lstrings.h" // contains
60 #include "support/mutex.h"
61 #include "support/ExceptionMessage.h"
64 using namespace lyx::support;
68 namespace Alert = frontend::Alert;
73 docstring const uniqueID()
75 static unsigned int seed = 1000;
77 Mutex::Locker lock(&mutex);
78 return "file" + convert<docstring>(++seed);
82 /// the type of inclusion
84 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
88 Types type(string const & s)
92 if (s == "verbatiminput")
94 if (s == "verbatiminput*")
96 if (s == "lstinputlisting" || s == "inputminted")
104 Types type(InsetCommandParams const & params)
106 return type(params.getCmdName());
110 bool isListings(InsetCommandParams const & params)
112 return type(params) == LISTINGS;
116 bool isVerbatim(InsetCommandParams const & params)
118 Types const t = type(params);
119 return t == VERB || t == VERBAST;
123 bool isInputOrInclude(InsetCommandParams const & params)
125 Types const t = type(params);
126 return t == INPUT || t == INCLUDE;
130 FileName const masterFileName(Buffer const & buffer)
132 return buffer.masterBuffer()->fileName();
136 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
139 string const parentFileName(Buffer const & buffer)
141 return buffer.absFileName();
145 FileName const includedFileName(Buffer const & buffer,
146 InsetCommandParams const & params)
148 return makeAbsPath(ltrim(to_utf8(params["filename"])),
149 onlyPath(parentFileName(buffer)));
153 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
155 if (label_str.empty())
157 InsetCommandParams icp(LABEL_CODE);
158 icp["name"] = label_str;
159 return new InsetLabel(buf, icp);
163 char_type replaceCommaInBraces(docstring & params)
165 // Code point from private use area
166 char_type private_char = 0xE000;
168 for (char_type & c : params) {
173 else if (c == ',' && count)
182 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
183 : InsetCommand(buf, p), include_label(uniqueID()),
184 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
185 set_label_(false), label_(nullptr), child_buffer_(nullptr), file_exist_(false),
186 recursion_error_(false)
188 preview_->connect([this](){ fileChanged(); });
190 if (isListings(params())) {
191 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
192 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
193 } else if (isInputOrInclude(params()) && buf)
198 InsetInclude::InsetInclude(InsetInclude const & other)
199 : InsetCommand(other), include_label(other.include_label),
200 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
201 set_label_(false), label_(nullptr), child_buffer_(nullptr),
202 file_exist_(other.file_exist_),recursion_error_(other.recursion_error_)
204 preview_->connect([this](){ fileChanged(); });
207 label_ = new InsetLabel(*other.label_);
211 InsetInclude::~InsetInclude()
217 void InsetInclude::setBuffer(Buffer & buffer)
219 InsetCommand::setBuffer(buffer);
221 label_->setBuffer(buffer);
225 void InsetInclude::setChildBuffer(Buffer * buffer)
227 child_buffer_ = buffer;
231 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
234 // This is only correct for the case of listings, but it'll do for now.
235 // In the other cases, this second parameter should just be empty.
236 static ParamInfo param_info_;
237 if (param_info_.empty()) {
238 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
239 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
240 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
246 bool InsetInclude::isCompatibleCommand(string const & s)
248 return type(s) != NONE;
252 bool InsetInclude::needsCProtection(bool const /*maintext*/, bool const fragile) const
254 // We need to \cprotect all types in fragile context
259 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
261 switch (cmd.action()) {
263 case LFUN_INSET_EDIT: {
264 editIncluded(ltrim(to_utf8(params()["filename"])));
268 case LFUN_INSET_MODIFY: {
269 // It should be OK just to invalidate the cache in setParams()
271 // child_buffer_ = 0;
272 InsetCommandParams p(INCLUDE_CODE);
273 if (cmd.getArg(0) == "changetype") {
275 InsetCommand::doDispatch(cur, cmd);
278 InsetCommand::string2params(to_utf8(cmd.argument()), p);
279 if (!p.getCmdName().empty()) {
281 InsetListingsParams new_params(to_utf8(p["lstparams"]));
282 docstring const new_label =
283 from_utf8(new_params.getParamValue("label"));
285 if (new_label.empty()) {
291 old_label = label_->getParam("name");
293 label_ = createLabel(buffer_, new_label);
294 label_->setBuffer(buffer());
297 if (new_label != old_label) {
298 label_->updateLabelAndRefs(new_label, &cur);
299 // the label might have been adapted (duplicate)
300 if (new_label != label_->getParam("name")) {
301 new_params.addParam("label", "{" +
302 to_utf8(label_->getParam("name")) + "}", true);
303 p["lstparams"] = from_utf8(new_params.params());
310 cur.forceBufferUpdate();
312 cur.noScreenUpdate();
316 case LFUN_MOUSE_RELEASE: {
317 if (cmd.modifier() == ControlModifier) {
318 FileName const incfile = includedFileName(buffer(), params());
319 string const & incname = incfile.absFileName();
320 editIncluded(incname);
326 //pass everything else up the chain
328 InsetCommand::doDispatch(cur, cmd);
334 void InsetInclude::editIncluded(string const & f)
336 if (isLyXFileName(f)) {
337 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, f);
340 // tex file or other text file in verbatim mode
341 theFormats().edit(buffer(),
342 support::makeAbsPath(f, support::onlyPath(buffer().absFileName())),
347 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
348 FuncStatus & flag) const
350 switch (cmd.action()) {
352 case LFUN_INSET_EDIT:
353 flag.setEnabled(true);
356 case LFUN_INSET_MODIFY:
357 if (cmd.getArg(0) == "changetype")
358 return InsetCommand::getStatus(cur, cmd, flag);
360 flag.setEnabled(true);
364 return InsetCommand::getStatus(cur, cmd, flag);
369 void InsetInclude::setParams(InsetCommandParams const & p)
371 // invalidate the cache
372 child_buffer_ = nullptr;
374 // reset in order to allow loading new file
375 failedtoload_ = false;
376 recursion_error_ = false;
378 InsetCommand::setParams(p);
381 if (preview_->monitoring())
382 preview_->stopMonitoring();
384 if (type(params()) == INPUT)
385 add_preview(*preview_, *this, buffer());
389 bool InsetInclude::isChildIncluded() const
391 std::list<std::string> includeonlys =
392 buffer().params().getIncludedChildren();
393 if (includeonlys.empty())
395 return (std::find(includeonlys.begin(),
397 ltrim(to_utf8(params()["filename"]))) != includeonlys.end());
401 docstring InsetInclude::screenLabel() const
403 docstring pre = file_exist_ ? docstring() : _("FILE MISSING:");
407 switch (type(params())) {
409 temp = buffer().B_("Input");
412 temp = buffer().B_("Verbatim");
415 temp = buffer().B_("Verbatim*");
418 if (isChildIncluded())
419 temp = buffer().B_("Include");
421 temp += buffer().B_("Include (excluded)");
424 temp = listings_label_;
427 LASSERT(false, temp = buffer().B_("Unknown"));
433 if (ltrim(params()["filename"]).empty())
436 temp += from_utf8(onlyFileName(ltrim(to_utf8(params()["filename"]))));
438 return pre.empty() ? temp : pre + from_ascii(" ") + temp;
442 Buffer * InsetInclude::loadIfNeeded() const
444 // This is for background export and preview. We don't even want to
445 // try to load the cloned child document again.
446 if (buffer().isClone())
447 return child_buffer_;
449 // Don't try to load it again if we failed before.
450 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
453 FileName const included_file = includedFileName(buffer(), params());
454 // Use cached Buffer if possible.
455 if (child_buffer_ != nullptr) {
456 if (theBufferList().isLoaded(child_buffer_)
457 // additional sanity check: make sure the Buffer really is
458 // associated with the file we want.
459 && child_buffer_ == theBufferList().getBuffer(included_file))
460 return child_buffer_;
461 // Buffer vanished, so invalidate cache and try to reload.
462 child_buffer_ = nullptr;
465 if (!isLyXFileName(included_file.absFileName()))
468 Buffer * child = theBufferList().getBuffer(included_file);
469 if (checkForRecursiveInclude(child))
473 // the readonly flag can/will be wrong, not anymore I think.
474 if (!included_file.exists()) {
475 failedtoload_ = true;
479 child = theBufferList().newBuffer(included_file.absFileName());
481 // Buffer creation is not possible.
484 buffer().pushIncludedBuffer(child);
485 // Set parent before loading, such that macros can be tracked
486 child->setParent(&buffer());
488 if (child->loadLyXFile() != Buffer::ReadSuccess) {
489 failedtoload_ = true;
490 child->setParent(nullptr);
491 //close the buffer we just opened
492 theBufferList().release(child);
493 buffer().popIncludedBuffer();
497 buffer().popIncludedBuffer();
498 if (!child->errorList("Parse").empty()) {
499 // FIXME: Do something.
502 // The file was already loaded, so, simply
503 // inform parent buffer about local macros.
504 Buffer const * parent = &buffer();
505 child->setParent(parent);
507 child->listMacroNames(macros);
508 MacroNameSet::const_iterator cit = macros.begin();
509 MacroNameSet::const_iterator end = macros.end();
510 for (; cit != end; ++cit)
511 parent->usermacros.insert(*cit);
514 // Cache the child buffer.
515 child_buffer_ = child;
520 bool InsetInclude::checkForRecursiveInclude(
521 Buffer const * cbuf, bool silent) const
523 if (recursion_error_)
526 if (!buffer().isBufferIncluded(cbuf))
530 docstring const msg = _("The file\n%1$s\n has attempted to include itself.\n"
531 "The document set will not work properly until this is fixed!");
532 frontend::Alert::warning(_("Recursive Include"),
533 bformat(msg, from_utf8(cbuf->fileName().absFileName())));
535 recursion_error_ = true;
540 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
542 string incfile = ltrim(to_utf8(params()["filename"]));
544 // Warn if no file name has been specified
545 if (incfile.empty()) {
546 frontend::Alert::warning(_("No file name specified"),
547 _("An included file name is empty.\n"
548 "Ignoring Inclusion"),
552 // Warn if file doesn't exist
553 if (!includedFileExist()) {
554 frontend::Alert::warning(_("Included file not found"),
555 bformat(_("The included file\n"
557 "has not been found. LyX will ignore the inclusion."),
563 FileName const included_file = includedFileName(buffer(), params());
564 Buffer const * const masterBuffer = buffer().masterBuffer();
566 if (runparams.inDeletedInset) {
567 // We cannot strike-out whole children,
568 // so we just output a note.
570 << bformat(buffer().B_("[INCLUDED FILE %1$s DELETED!]"),
571 from_utf8(included_file.onlyFileName()))
576 // if incfile is relative, make it relative to the master
578 if (!FileName::isAbsolute(incfile)) {
580 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
581 from_utf8(masterBuffer->filePath())));
584 string exppath = incfile;
585 if (!runparams.export_folder.empty()) {
586 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
589 // write it to a file (so far the complete file)
593 if (type(params()) == LISTINGS) {
594 exportfile = exppath;
595 mangled = DocFileName(included_file).mangledFileName();
597 exportfile = changeExtension(exppath, ".tex");
598 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
604 else if (!runparams.silent)
605 ; // no warning wanted
606 else if (!isValidLaTeXFileName(incfile)) {
607 frontend::Alert::warning(_("Invalid filename"),
608 _("The following filename will cause troubles "
609 "when running the exported file through LaTeX: ") +
611 } else if (!isValidDVIFileName(incfile)) {
612 frontend::Alert::warning(_("Problematic filename for DVI"),
613 _("The following filename can cause troubles "
614 "when running the exported file through LaTeX "
615 "and opening the resulting DVI: ") +
616 from_utf8(incfile), true);
619 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
620 buffer().temppath() : masterBuffer->temppath()));
622 LYXERR(Debug::LATEX, "incfile:" << incfile);
623 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
624 LYXERR(Debug::LATEX, "writefile:" << writefile);
626 string const tex_format = flavor2format(runparams.flavor);
628 switch (type(params())) {
631 incfile = latex_path(incfile);
633 os << '\\' << from_ascii(params().getCmdName()) << '{'
634 << from_utf8(incfile) << '}';
638 runparams.exportdata->addExternalFile(tex_format, writefile,
641 // \input wants file with extension (default is .tex)
642 if (!isLyXFileName(included_file.absFileName())) {
643 incfile = latex_path(incfile);
645 os << '\\' << from_ascii(params().getCmdName())
646 << '{' << from_utf8(incfile) << '}';
648 incfile = changeExtension(incfile, ".tex");
649 incfile = latex_path(incfile);
651 os << '\\' << from_ascii(params().getCmdName())
652 << '{' << from_utf8(incfile) << '}';
657 // Here, listings and minted have slightly different behaviors.
658 // Using listings, it is always possible to have a caption,
659 // even for non-floats. Using minted, only floats can have a
660 // caption. So, with minted we use the following strategy.
661 // If a caption was specified but the float parameter was not,
662 // we ourselves add a caption above the listing (because the
663 // listing comes from a file and might span several pages).
664 // Otherwise, if float was specified, the floating listing
665 // environment provided by minted is used. In either case, the
666 // label parameter is taken as the label by which the float
667 // can be referenced, otherwise it will have the meaning
668 // intended by minted. In this last case, the label will
669 // serve as a sort of caption that, however, will be shown
670 // by minted only if the frame parameter is also specified.
671 bool const use_minted = buffer().params().use_minted;
672 runparams.exportdata->addExternalFile(tex_format, writefile,
674 string const opt = to_utf8(params()["lstparams"]);
675 // opt is set in QInclude dialog and should have passed validation.
676 InsetListingsParams lstparams(opt);
677 docstring parameters = from_utf8(lstparams.params());
682 bool isfloat = lstparams.isFloat();
683 // We are going to split parameters at commas, so
684 // replace commas that are not parameter separators
685 // with a code point from the private use area
686 char_type comma = replaceCommaInBraces(parameters);
687 // Get float placement, language, caption, and
688 // label, then remove the relative options if minted.
689 vector<docstring> opts =
690 getVectorFromString(parameters, from_ascii(","), false);
691 vector<docstring> latexed_opts;
692 for (size_t i = 0; i < opts.size(); ++i) {
693 // Restore replaced commas
694 opts[i] = subst(opts[i], comma, ',');
695 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
696 if (prefixIs(opts[i], from_ascii("float=")))
697 placement = opts[i].substr(6);
698 opts.erase(opts.begin() + i--);
699 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
700 language = opts[i].substr(9);
701 opts.erase(opts.begin() + i--);
702 } else if (prefixIs(opts[i], from_ascii("caption="))) {
703 caption = params().prepareCommand(runparams, trim(opts[i].substr(8), "{}"),
704 ParamInfo::HANDLING_LATEXIFY);
705 opts.erase(opts.begin() + i--);
707 latexed_opts.push_back(from_ascii("caption={") + caption + "}");
708 } else if (prefixIs(opts[i], from_ascii("label="))) {
709 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
710 ParamInfo::HANDLING_ESCAPE);
711 opts.erase(opts.begin() + i--);
713 latexed_opts.push_back(from_ascii("label={") + label + "}");
715 if (use_minted && !label.empty()) {
716 if (isfloat || !caption.empty())
717 label = trim(label, "{}");
719 opts.push_back(from_ascii("label=") + label);
722 if (!latexed_opts.empty())
723 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
724 parameters = getStringFromVector(opts, from_ascii(","));
725 if (language.empty())
726 language = from_ascii("TeX");
727 if (use_minted && isfloat) {
728 os << breakln << "\\begin{listing}";
729 if (!placement.empty())
730 os << '[' << placement << "]";
732 } else if (use_minted && !caption.empty()) {
733 os << breakln << "\\lyxmintcaption[t]{" << caption;
735 os << "\\label{" << label << "}";
738 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
739 if (!parameters.empty())
740 os << "[" << parameters << "]";
742 os << '{' << ascii_lowercase(language) << '}';
743 os << '{' << incfile << '}';
744 if (use_minted && isfloat) {
745 if (!caption.empty())
746 os << breakln << "\\caption{" << caption << "}";
748 os << breakln << "\\label{" << label << "}";
749 os << breakln << "\\end{listing}\n";
754 runparams.exportdata->addExternalFile(tex_format, writefile,
757 // \include don't want extension and demands that the
758 // file really have .tex
759 incfile = changeExtension(incfile, string());
760 incfile = latex_path(incfile);
762 os << '\\' << from_ascii(params().getCmdName()) << '{'
763 << from_utf8(incfile) << '}';
770 if (runparams.inComment || runparams.dryrun)
771 // Don't try to load or copy the file if we're
772 // in a comment or doing a dryrun
775 if (!isInputOrInclude(params()) ||
776 !isLyXFileName(included_file.absFileName())) {
777 // In this case, it's not a LyX file, so we copy the file
778 // to the temp dir, so that .aux files etc. are not created
779 // in the original dir. Files included by this file will be
780 // found via either the environment variable TEXINPUTS, or
781 // input@path, see ../Buffer.cpp.
782 unsigned long const checksum_in = included_file.checksum();
783 unsigned long const checksum_out = writefile.checksum();
784 if (checksum_in != checksum_out) {
785 if (!included_file.copyTo(writefile)) {
788 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
789 "into the temporary directory."),
790 from_utf8(included_file.absFileName()))));
797 // it's a LyX file and we're inputting or including, so
798 // try to load it so we can write the associated latex
799 Buffer * tmp = loadIfNeeded();
801 if (!runparams.silent) {
802 docstring text = bformat(_("Could not load included "
804 "Please, check whether it actually exists."),
805 included_file.displayName());
806 throw ExceptionMessage(ErrorException, _("Error: "),
812 if (recursion_error_)
815 if (!runparams.silent) {
816 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
818 docstring text = bformat(_("Included file `%1$s'\n"
819 "has textclass `%2$s'\n"
820 "while parent file has textclass `%3$s'."),
821 included_file.displayName(),
822 from_utf8(tmp->params().documentClass().name()),
823 from_utf8(masterBuffer->params().documentClass().name()));
824 Alert::warning(_("Different textclasses"), text, true);
827 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
828 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
829 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
830 docstring text = bformat(_("Included file `%1$s'\n"
831 "has use-non-TeX-fonts set to `%2$s'\n"
832 "while parent file has use-non-TeX-fonts set to `%3$s'."),
833 included_file.displayName(),
835 from_utf8(master_tf));
836 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
838 else if (tmp->params().inputenc != masterBuffer->params().inputenc) {
839 docstring text = bformat(_("Included file `%1$s'\n"
840 "uses input encoding \"%2$s\" [%3$s]\n"
841 "while parent file uses input encoding \"%4$s\" [%5$s]."),
842 included_file.displayName(),
843 _(tmp->params().inputenc),
844 from_utf8(tmp->params().encoding().guiName()),
845 _(masterBuffer->params().inputenc),
846 from_utf8(masterBuffer->params().encoding().guiName()));
847 Alert::warning(_("Different LaTeX input encodings"), text, true);
850 // Make sure modules used in child are all included in master
851 // FIXME It might be worth loading the children's modules into the master
852 // over in BufferParams rather than doing this check.
853 LayoutModuleList const masterModules = masterBuffer->params().getModules();
854 LayoutModuleList const childModules = tmp->params().getModules();
855 LayoutModuleList::const_iterator it = childModules.begin();
856 LayoutModuleList::const_iterator end = childModules.end();
857 for (; it != end; ++it) {
858 string const module = *it;
859 LayoutModuleList::const_iterator found =
860 find(masterModules.begin(), masterModules.end(), module);
861 if (found == masterModules.end()) {
862 docstring text = bformat(_("Included file `%1$s'\n"
863 "uses module `%2$s'\n"
864 "which is not used in parent file."),
865 included_file.displayName(), from_utf8(module));
866 Alert::warning(_("Module not found"), text, true);
871 tmp->markDepClean(masterBuffer->temppath());
873 // Don't assume the child's format is latex
874 string const inc_format = tmp->params().bufferFormat();
875 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
876 theFormats().extension(inc_format)));
878 // FIXME: handle non existing files
879 // The included file might be written in a different encoding
881 Encoding const * const oldEnc = runparams.encoding;
882 Language const * const oldLang = runparams.master_language;
883 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
884 // the children must be encoded in plain utf8!
885 if (masterBuffer->params().useNonTeXFonts)
886 runparams.encoding = encodings.fromLyXName("utf8-plain");
888 runparams.encoding = oldEnc;
889 else runparams.encoding = &tmp->params().encoding();
890 runparams.master_language = buffer().params().language;
891 runparams.par_begin = 0;
892 runparams.par_end = tmp->paragraphs().size();
893 runparams.is_child = true;
894 Buffer::ExportStatus retval =
895 tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
896 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
897 if (retval == Buffer::ExportKilled && buffer().isClone() &&
898 buffer().isExporting()) {
899 // We really shouldn't get here, I don't think.
900 LYXERR0("No conversion exception?");
901 throw ConversionException();
903 else if (retval != Buffer::ExportSuccess) {
904 if (!runparams.silent) {
905 docstring msg = bformat(_("Included file `%1$s' "
906 "was not exported correctly.\n "
907 "LaTeX export is probably incomplete."),
908 included_file.displayName());
909 ErrorList const & el = tmp->errorList("Export");
911 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
912 msg, el.begin()->error, el.begin()->description);
913 throw ExceptionMessage(ErrorException, _("Error: "), msg);
916 runparams.encoding = oldEnc;
917 runparams.master_language = oldLang;
918 runparams.is_child = false;
920 // If needed, use converters to produce a latex file from the child
921 if (tmpwritefile != writefile) {
923 Converters::RetVal const conv_retval =
924 theConverters().convert(tmp, tmpwritefile, writefile,
925 included_file, inc_format, tex_format, el);
926 if (conv_retval == Converters::KILLED && buffer().isClone() &&
927 buffer().isExporting()) {
928 // We really shouldn't get here, I don't think.
929 LYXERR0("No conversion exception?");
930 throw ConversionException();
931 } else if (conv_retval != Converters::SUCCESS && !runparams.silent) {
932 docstring msg = bformat(_("Included file `%1$s' "
933 "was not exported correctly.\n "
934 "LaTeX export is probably incomplete."),
935 included_file.displayName());
937 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
938 msg, el.begin()->error, el.begin()->description);
939 throw ExceptionMessage(ErrorException, _("Error: "), msg);
945 docstring InsetInclude::xhtml(XMLStream & xs, OutputParams const & rp) const
950 // For verbatim and listings, we just include the contents of the file as-is.
951 // In the case of listings, we wrap it in <pre>.
952 bool const listing = isListings(params());
953 if (listing || isVerbatim(params())) {
955 xs << xml::StartTag("pre");
956 // FIXME: We don't know the encoding of the file, default to UTF-8.
957 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
959 xs << xml::EndTag("pre");
963 // We don't (yet) know how to Input or Include non-LyX files.
964 // (If we wanted to get really arcane, we could run some tex2html
965 // converter on the included file. But that's just masochistic.)
966 FileName const included_file = includedFileName(buffer(), params());
967 if (!isLyXFileName(included_file.absFileName())) {
969 frontend::Alert::warning(_("Unsupported Inclusion"),
970 bformat(_("LyX does not know how to include non-LyX files when "
971 "generating HTML output. Offending file:\n%1$s"),
972 ltrim(params()["filename"])));
976 // In the other cases, we will generate the HTML and include it.
978 Buffer const * const ibuf = loadIfNeeded();
982 if (recursion_error_)
985 // are we generating only some paragraphs, or all of them?
986 bool const all_pars = !rp.dryrun ||
987 (rp.par_begin == 0 &&
988 rp.par_end == (int)buffer().text().paragraphs().size());
990 OutputParams op = rp;
994 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
996 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
997 xs << from_utf8(included_file.absFileName());
998 xs << XMLStream::ESCAPE_NONE << " -->";
1005 int InsetInclude::plaintext(odocstringstream & os,
1006 OutputParams const & op, size_t) const
1008 // just write the filename if we're making a tooltip or toc entry,
1009 // or are generating this for advanced search
1010 if (op.for_tooltip || op.for_toc || op.for_search) {
1011 os << '[' << screenLabel() << '\n'
1012 << ltrim(getParam("filename")) << "\n]";
1013 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1016 if (isVerbatim(params()) || isListings(params())) {
1017 if (op.for_search) {
1018 os << '[' << screenLabel() << ']';
1021 os << '[' << screenLabel() << '\n'
1022 // FIXME: We don't know the encoding of the file, default to UTF-8.
1023 << includedFileName(buffer(), params()).fileContents("UTF-8")
1026 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1029 Buffer const * const ibuf = loadIfNeeded();
1031 docstring const str = '[' + screenLabel() + ']';
1036 if (recursion_error_)
1039 writePlaintextFile(*ibuf, os, op);
1044 void InsetInclude::docbook(XMLStream & xs, OutputParams const & rp) const
1049 // For verbatim and listings, we just include the contents of the file as-is.
1050 bool const verbatim = isVerbatim(params());
1051 bool const listing = isListings(params());
1052 if (listing || verbatim) {
1054 xs << xml::StartTag("programlisting");
1056 xs << xml::StartTag("literallayout");
1058 // FIXME: We don't know the encoding of the file, default to UTF-8.
1059 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
1062 xs << xml::EndTag("programlisting");
1064 xs << xml::EndTag("literallayout");
1069 // We don't know how to input or include non-LyX files. Input it as a comment.
1070 FileName const included_file = includedFileName(buffer(), params());
1071 if (!isLyXFileName(included_file.absFileName())) {
1073 frontend::Alert::warning(_("Unsupported Inclusion"),
1074 bformat(_("LyX does not know how to process included non-LyX files when "
1075 "generating DocBook output. The content of the file will be output as a "
1076 "comment. Offending file:\n%1$s"),
1077 ltrim(params()["filename"])));
1079 // Read the file, output it wrapped into comments.
1080 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
1081 xs << from_utf8(included_file.absFileName());
1082 xs << XMLStream::ESCAPE_NONE << " -->";
1084 xs << XMLStream::ESCAPE_NONE << "<!-- ";
1085 xs << included_file.fileContents("UTF-8");
1086 xs << XMLStream::ESCAPE_NONE << " -->";
1088 xs << XMLStream::ESCAPE_NONE << "<!-- End of included file: ";
1089 xs << from_utf8(included_file.absFileName());
1090 xs << XMLStream::ESCAPE_NONE << " -->";
1093 // In the other cases, we generate the DocBook version and include it.
1094 Buffer const * const ibuf = loadIfNeeded();
1098 if (recursion_error_)
1101 // are we generating only some paragraphs, or all of them?
1102 bool const all_pars = !rp.dryrun ||
1103 (rp.par_begin == 0 &&
1104 rp.par_end == (int) buffer().text().paragraphs().size());
1106 OutputParams op = rp;
1110 op.inInclude = true;
1111 op.docbook_in_par = false;
1112 ibuf->writeDocBookSource(xs.os(), op, Buffer::IncludedFile);
1114 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
1115 xs << from_utf8(included_file.absFileName());
1116 xs << XMLStream::ESCAPE_NONE << " -->";
1121 void InsetInclude::validate(LaTeXFeatures & features) const
1123 LATTEST(&buffer() == &features.buffer());
1125 string incfile = ltrim(to_utf8(params()["filename"]));
1126 string const included_file =
1127 includedFileName(buffer(), params()).absFileName();
1130 if (isLyXFileName(included_file))
1131 writefile = changeExtension(included_file, ".sgml");
1133 writefile = included_file;
1135 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1136 incfile = DocFileName(writefile).mangledFileName();
1137 writefile = makeAbsPath(incfile,
1138 buffer().masterBuffer()->temppath()).absFileName();
1141 features.includeFile(include_label, writefile);
1143 features.useInsetLayout(getLayout());
1144 if (isVerbatim(params()))
1145 features.require("verbatim");
1146 else if (isListings(params())) {
1147 if (buffer().params().use_minted) {
1148 features.require("minted");
1149 string const opts = to_utf8(params()["lstparams"]);
1150 InsetListingsParams lstpars(opts);
1151 if (!lstpars.isFloat() && contains(opts, "caption="))
1152 features.require("lyxmintcaption");
1154 features.require("listings");
1157 // Here we must do the fun stuff...
1158 // Load the file in the include if it needs
1160 Buffer * const tmp = loadIfNeeded();
1164 // the file is loaded
1165 if (checkForRecursiveInclude(tmp))
1167 buffer().pushIncludedBuffer(tmp);
1169 // We must temporarily change features.buffer,
1170 // otherwise it would always be the master buffer,
1171 // and nested includes would not work.
1172 features.setBuffer(*tmp);
1173 // Maybe this is already a child
1174 bool const is_child =
1175 features.runparams().is_child;
1176 features.runparams().is_child = true;
1177 tmp->validate(features);
1178 features.runparams().is_child = is_child;
1179 features.setBuffer(buffer());
1181 buffer().popIncludedBuffer();
1185 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1187 Buffer * ibuf = loadIfNeeded();
1191 if (checkForRecursiveInclude(ibuf))
1193 buffer().pushIncludedBuffer(ibuf);
1194 ibuf->collectBibKeys(checkedFiles);
1195 buffer().popIncludedBuffer();
1199 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1201 LBUFERR(mi.base.bv);
1203 bool use_preview = false;
1204 if (RenderPreview::previewText()) {
1205 graphics::PreviewImage const * pimage =
1206 preview_->getPreviewImage(mi.base.bv->buffer());
1207 use_preview = pimage && pimage->image();
1211 preview_->metrics(mi, dim);
1215 button_.update(screenLabel(), true, false, !file_exist_ || recursion_error_);
1217 button_.metrics(mi, dim);
1220 Box b(0, dim.wid, -dim.asc, dim.des);
1225 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1227 LBUFERR(pi.base.bv);
1229 bool use_preview = false;
1230 if (RenderPreview::previewText()) {
1231 graphics::PreviewImage const * pimage =
1232 preview_->getPreviewImage(pi.base.bv->buffer());
1233 use_preview = pimage && pimage->image();
1237 preview_->draw(pi, x, y);
1239 button_.draw(pi, x, y);
1243 void InsetInclude::write(ostream & os) const
1245 params().Write(os, &buffer());
1249 string InsetInclude::contextMenuName() const
1251 return "context-include";
1255 Inset::RowFlags InsetInclude::rowFlags() const
1257 return type(params()) == INPUT ? Inline : Display;
1261 docstring InsetInclude::layoutName() const
1263 if (isListings(params()))
1264 return from_ascii("IncludeListings");
1265 return InsetCommand::layoutName();
1273 void InsetInclude::fileChanged() const
1275 Buffer const * const buffer = updateFrontend();
1279 preview_->removePreview(*buffer);
1280 add_preview(*preview_, *this, *buffer);
1281 preview_->startLoading(*buffer);
1287 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1289 FileName const included_file = includedFileName(buffer, params);
1291 return type(params) == INPUT && params.preview() &&
1292 included_file.isReadableFile();
1296 docstring latexString(InsetInclude const & inset)
1298 odocstringstream ods;
1300 // We don't need to set runparams.encoding since this will be done
1301 // by latex() anyway.
1302 OutputParams runparams(nullptr);
1303 runparams.flavor = Flavor::LaTeX;
1304 runparams.for_preview = true;
1305 inset.latex(os, runparams);
1311 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1312 Buffer const & buffer)
1314 InsetCommandParams const & params = inset.params();
1315 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1316 renderer.setAbsFile(includedFileName(buffer, params));
1319 // InsetInclude::latex() throws if generation of LaTeX
1320 // fails, e.g. if lyx2lyx fails because file is too
1321 // new, or knitr fails.
1322 snippet = latexString(inset);
1324 // remove current preview because it is likely
1325 // associated with the previous included file name
1326 renderer.removePreview(buffer);
1327 LYXERR0("Preview of include failed.");
1330 renderer.addPreview(snippet, buffer);
1337 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1338 graphics::PreviewLoader & ploader) const
1340 Buffer const & buffer = ploader.buffer();
1341 if (!preview_wanted(params(), buffer))
1343 preview_->setAbsFile(includedFileName(buffer, params()));
1344 docstring const snippet = latexString(*this);
1345 preview_->addPreview(snippet, ploader);
1349 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1350 UpdateType utype, TocBackend & backend) const
1352 if (isListings(params())) {
1354 label_->addToToc(cpit, output_active, utype, backend);
1355 TocBuilder & b = backend.builder("listing");
1356 b.pushItem(cpit, screenLabel(), output_active);
1357 InsetListingsParams p(to_utf8(params()["lstparams"]));
1358 b.argumentItem(from_utf8(p.getParamValue("caption")));
1360 } else if (isVerbatim(params())) {
1361 TocBuilder & b = backend.builder("child");
1362 b.pushItem(cpit, screenLabel(), output_active);
1365 Buffer const * const childbuffer = loadIfNeeded();
1367 TocBuilder & b = backend.builder("child");
1368 string const fname = ltrim(to_utf8(params()["filename"]));
1369 // mark non-existent childbuffer with FILE MISSING
1370 docstring const str = (childbuffer ? from_ascii("") : _("FILE MISSING: "))
1371 + from_utf8(onlyFileName(fname)) + " (" + from_utf8(fname) + ")";
1372 b.pushItem(cpit, str, output_active);
1378 if (checkForRecursiveInclude(childbuffer))
1380 buffer().pushIncludedBuffer(childbuffer);
1381 // Update the child's tocBackend. The outliner uses the master's, but
1382 // the navigation menu uses the child's.
1383 childbuffer->tocBackend().update(output_active, utype);
1384 // Include Tocs from children
1385 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1387 buffer().popIncludedBuffer();
1388 // Copy missing outliner names (though the user has been warned against
1389 // having different document class and module selection between master
1391 for (auto const & name
1392 : childbuffer->params().documentClass().outlinerNames())
1393 backend.addName(name.first, translateIfPossible(name.second));
1398 void InsetInclude::updateCommand()
1403 docstring old_label = label_->getParam("name");
1404 label_->updateLabel(old_label);
1405 // the label might have been adapted (duplicate)
1406 docstring new_label = label_->getParam("name");
1407 if (old_label == new_label)
1410 // update listings parameters...
1411 InsetCommandParams p(INCLUDE_CODE);
1413 InsetListingsParams par(to_utf8(params()["lstparams"]));
1414 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1415 p["lstparams"] = from_utf8(par.params());
1420 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1422 file_exist_ = includedFileExist();
1423 Buffer const * const childbuffer = loadIfNeeded();
1425 if (!checkForRecursiveInclude(childbuffer))
1426 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1427 button_.update(screenLabel(), true, false, recursion_error_);
1431 button_.update(screenLabel(), true, false, !file_exist_);
1433 if (!isListings(params()))
1437 label_->updateBuffer(it, utype, deleted);
1439 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1440 if (par.getParamValue("caption").empty()) {
1441 listings_label_ = buffer().B_("Program Listing");
1444 Buffer const & master = *buffer().masterBuffer();
1445 Counters & counters = master.params().documentClass().counters();
1446 docstring const cnt = from_ascii("listing");
1447 listings_label_ = master.B_("Program Listing");
1448 if (counters.hasCounter(cnt)) {
1449 counters.step(cnt, utype);
1450 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1455 bool InsetInclude::includedFileExist() const
1457 // check whether the included file exist
1458 string incFileName = ltrim(to_utf8(params()["filename"]));
1460 support::makeAbsPath(incFileName,
1461 support::onlyPath(buffer().absFileName()));