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([=](){ 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([=](){ 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 incfile is relative, make it relative to the master
568 if (!FileName::isAbsolute(incfile)) {
570 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
571 from_utf8(masterBuffer->filePath())));
574 string exppath = incfile;
575 if (!runparams.export_folder.empty()) {
576 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
579 // write it to a file (so far the complete file)
583 if (type(params()) == LISTINGS) {
584 exportfile = exppath;
585 mangled = DocFileName(included_file).mangledFileName();
587 exportfile = changeExtension(exppath, ".tex");
588 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
594 else if (!runparams.silent)
595 ; // no warning wanted
596 else if (!isValidLaTeXFileName(incfile)) {
597 frontend::Alert::warning(_("Invalid filename"),
598 _("The following filename will cause troubles "
599 "when running the exported file through LaTeX: ") +
601 } else if (!isValidDVIFileName(incfile)) {
602 frontend::Alert::warning(_("Problematic filename for DVI"),
603 _("The following filename can cause troubles "
604 "when running the exported file through LaTeX "
605 "and opening the resulting DVI: ") +
606 from_utf8(incfile), true);
609 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
610 buffer().temppath() : masterBuffer->temppath()));
612 LYXERR(Debug::LATEX, "incfile:" << incfile);
613 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
614 LYXERR(Debug::LATEX, "writefile:" << writefile);
616 string const tex_format = flavor2format(runparams.flavor);
618 switch (type(params())) {
621 incfile = latex_path(incfile);
623 os << '\\' << from_ascii(params().getCmdName()) << '{'
624 << from_utf8(incfile) << '}';
628 runparams.exportdata->addExternalFile(tex_format, writefile,
631 // \input wants file with extension (default is .tex)
632 if (!isLyXFileName(included_file.absFileName())) {
633 incfile = latex_path(incfile);
635 os << '\\' << from_ascii(params().getCmdName())
636 << '{' << from_utf8(incfile) << '}';
638 incfile = changeExtension(incfile, ".tex");
639 incfile = latex_path(incfile);
641 os << '\\' << from_ascii(params().getCmdName())
642 << '{' << from_utf8(incfile) << '}';
647 // Here, listings and minted have slightly different behaviors.
648 // Using listings, it is always possible to have a caption,
649 // even for non-floats. Using minted, only floats can have a
650 // caption. So, with minted we use the following strategy.
651 // If a caption was specified but the float parameter was not,
652 // we ourselves add a caption above the listing (because the
653 // listing comes from a file and might span several pages).
654 // Otherwise, if float was specified, the floating listing
655 // environment provided by minted is used. In either case, the
656 // label parameter is taken as the label by which the float
657 // can be referenced, otherwise it will have the meaning
658 // intended by minted. In this last case, the label will
659 // serve as a sort of caption that, however, will be shown
660 // by minted only if the frame parameter is also specified.
661 bool const use_minted = buffer().params().use_minted;
662 runparams.exportdata->addExternalFile(tex_format, writefile,
664 string const opt = to_utf8(params()["lstparams"]);
665 // opt is set in QInclude dialog and should have passed validation.
666 InsetListingsParams lstparams(opt);
667 docstring parameters = from_utf8(lstparams.params());
672 bool isfloat = lstparams.isFloat();
673 // We are going to split parameters at commas, so
674 // replace commas that are not parameter separators
675 // with a code point from the private use area
676 char_type comma = replaceCommaInBraces(parameters);
677 // Get float placement, language, caption, and
678 // label, then remove the relative options if minted.
679 vector<docstring> opts =
680 getVectorFromString(parameters, from_ascii(","), false);
681 vector<docstring> latexed_opts;
682 for (size_t i = 0; i < opts.size(); ++i) {
683 // Restore replaced commas
684 opts[i] = subst(opts[i], comma, ',');
685 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
686 if (prefixIs(opts[i], from_ascii("float=")))
687 placement = opts[i].substr(6);
688 opts.erase(opts.begin() + i--);
689 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
690 language = opts[i].substr(9);
691 opts.erase(opts.begin() + i--);
692 } else if (prefixIs(opts[i], from_ascii("caption="))) {
693 caption = params().prepareCommand(runparams, trim(opts[i].substr(8), "{}"),
694 ParamInfo::HANDLING_LATEXIFY);
695 opts.erase(opts.begin() + i--);
697 latexed_opts.push_back(from_ascii("caption={") + caption + "}");
698 } else if (prefixIs(opts[i], from_ascii("label="))) {
699 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
700 ParamInfo::HANDLING_ESCAPE);
701 opts.erase(opts.begin() + i--);
703 latexed_opts.push_back(from_ascii("label={") + label + "}");
705 if (use_minted && !label.empty()) {
706 if (isfloat || !caption.empty())
707 label = trim(label, "{}");
709 opts.push_back(from_ascii("label=") + label);
712 if (!latexed_opts.empty())
713 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
714 parameters = getStringFromVector(opts, from_ascii(","));
715 if (language.empty())
716 language = from_ascii("TeX");
717 if (use_minted && isfloat) {
718 os << breakln << "\\begin{listing}";
719 if (!placement.empty())
720 os << '[' << placement << "]";
722 } else if (use_minted && !caption.empty()) {
723 os << breakln << "\\lyxmintcaption[t]{" << caption;
725 os << "\\label{" << label << "}";
728 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
729 if (!parameters.empty())
730 os << "[" << parameters << "]";
732 os << '{' << ascii_lowercase(language) << '}';
733 os << '{' << incfile << '}';
734 if (use_minted && isfloat) {
735 if (!caption.empty())
736 os << breakln << "\\caption{" << caption << "}";
738 os << breakln << "\\label{" << label << "}";
739 os << breakln << "\\end{listing}\n";
744 runparams.exportdata->addExternalFile(tex_format, writefile,
747 // \include don't want extension and demands that the
748 // file really have .tex
749 incfile = changeExtension(incfile, string());
750 incfile = latex_path(incfile);
752 os << '\\' << from_ascii(params().getCmdName()) << '{'
753 << from_utf8(incfile) << '}';
760 if (runparams.inComment || runparams.dryrun)
761 // Don't try to load or copy the file if we're
762 // in a comment or doing a dryrun
765 if (!isInputOrInclude(params()) ||
766 !isLyXFileName(included_file.absFileName())) {
767 // In this case, it's not a LyX file, so we copy the file
768 // to the temp dir, so that .aux files etc. are not created
769 // in the original dir. Files included by this file will be
770 // found via either the environment variable TEXINPUTS, or
771 // input@path, see ../Buffer.cpp.
772 unsigned long const checksum_in = included_file.checksum();
773 unsigned long const checksum_out = writefile.checksum();
774 if (checksum_in != checksum_out) {
775 if (!included_file.copyTo(writefile)) {
778 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
779 "into the temporary directory."),
780 from_utf8(included_file.absFileName()))));
787 // it's a LyX file and we're inputting or including, so
788 // try to load it so we can write the associated latex
789 Buffer * tmp = loadIfNeeded();
791 if (!runparams.silent) {
792 docstring text = bformat(_("Could not load included "
794 "Please, check whether it actually exists."),
795 included_file.displayName());
796 throw ExceptionMessage(ErrorException, _("Error: "),
802 if (recursion_error_)
805 if (!runparams.silent) {
806 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
808 docstring text = bformat(_("Included file `%1$s'\n"
809 "has textclass `%2$s'\n"
810 "while parent file has textclass `%3$s'."),
811 included_file.displayName(),
812 from_utf8(tmp->params().documentClass().name()),
813 from_utf8(masterBuffer->params().documentClass().name()));
814 Alert::warning(_("Different textclasses"), text, true);
817 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
818 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
819 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
820 docstring text = bformat(_("Included file `%1$s'\n"
821 "has use-non-TeX-fonts set to `%2$s'\n"
822 "while parent file has use-non-TeX-fonts set to `%3$s'."),
823 included_file.displayName(),
825 from_utf8(master_tf));
826 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
828 else if (tmp->params().inputenc != masterBuffer->params().inputenc) {
829 docstring text = bformat(_("Included file `%1$s'\n"
830 "uses input encoding \"%2$s\" [%3$s]\n"
831 "while parent file uses input encoding \"%4$s\" [%5$s]."),
832 included_file.displayName(),
833 _(tmp->params().inputenc),
834 from_utf8(tmp->params().encoding().guiName()),
835 _(masterBuffer->params().inputenc),
836 from_utf8(masterBuffer->params().encoding().guiName()));
837 Alert::warning(_("Different LaTeX input encodings"), text, true);
840 // Make sure modules used in child are all included in master
841 // FIXME It might be worth loading the children's modules into the master
842 // over in BufferParams rather than doing this check.
843 LayoutModuleList const masterModules = masterBuffer->params().getModules();
844 LayoutModuleList const childModules = tmp->params().getModules();
845 LayoutModuleList::const_iterator it = childModules.begin();
846 LayoutModuleList::const_iterator end = childModules.end();
847 for (; it != end; ++it) {
848 string const module = *it;
849 LayoutModuleList::const_iterator found =
850 find(masterModules.begin(), masterModules.end(), module);
851 if (found == masterModules.end()) {
852 docstring text = bformat(_("Included file `%1$s'\n"
853 "uses module `%2$s'\n"
854 "which is not used in parent file."),
855 included_file.displayName(), from_utf8(module));
856 Alert::warning(_("Module not found"), text, true);
861 tmp->markDepClean(masterBuffer->temppath());
863 // Don't assume the child's format is latex
864 string const inc_format = tmp->params().bufferFormat();
865 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
866 theFormats().extension(inc_format)));
868 // FIXME: handle non existing files
869 // The included file might be written in a different encoding
871 Encoding const * const oldEnc = runparams.encoding;
872 Language const * const oldLang = runparams.master_language;
873 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
874 // the children must be encoded in plain utf8!
875 if (masterBuffer->params().useNonTeXFonts)
876 runparams.encoding = encodings.fromLyXName("utf8-plain");
878 runparams.encoding = oldEnc;
879 else runparams.encoding = &tmp->params().encoding();
880 runparams.master_language = buffer().params().language;
881 runparams.par_begin = 0;
882 runparams.par_end = tmp->paragraphs().size();
883 runparams.is_child = true;
884 Buffer::ExportStatus retval =
885 tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
886 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
887 if (retval == Buffer::ExportKilled && buffer().isClone() &&
888 buffer().isExporting()) {
889 // We really shouldn't get here, I don't think.
890 LYXERR0("No conversion exception?");
891 throw ConversionException();
893 else if (retval != Buffer::ExportSuccess) {
894 if (!runparams.silent) {
895 docstring msg = bformat(_("Included file `%1$s' "
896 "was not exported correctly.\n "
897 "LaTeX export is probably incomplete."),
898 included_file.displayName());
899 ErrorList const & el = tmp->errorList("Export");
901 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
902 msg, el.begin()->error, el.begin()->description);
903 throw ExceptionMessage(ErrorException, _("Error: "), msg);
906 runparams.encoding = oldEnc;
907 runparams.master_language = oldLang;
908 runparams.is_child = false;
910 // If needed, use converters to produce a latex file from the child
911 if (tmpwritefile != writefile) {
913 Converters::RetVal const conv_retval =
914 theConverters().convert(tmp, tmpwritefile, writefile,
915 included_file, inc_format, tex_format, el);
916 if (conv_retval == Converters::KILLED && buffer().isClone() &&
917 buffer().isExporting()) {
918 // We really shouldn't get here, I don't think.
919 LYXERR0("No conversion exception?");
920 throw ConversionException();
921 } else if (conv_retval != Converters::SUCCESS && !runparams.silent) {
922 docstring msg = bformat(_("Included file `%1$s' "
923 "was not exported correctly.\n "
924 "LaTeX export is probably incomplete."),
925 included_file.displayName());
927 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
928 msg, el.begin()->error, el.begin()->description);
929 throw ExceptionMessage(ErrorException, _("Error: "), msg);
935 docstring InsetInclude::xhtml(XMLStream & xs, OutputParams const & rp) const
940 // For verbatim and listings, we just include the contents of the file as-is.
941 // In the case of listings, we wrap it in <pre>.
942 bool const listing = isListings(params());
943 if (listing || isVerbatim(params())) {
945 xs << xml::StartTag("pre");
946 // FIXME: We don't know the encoding of the file, default to UTF-8.
947 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
949 xs << xml::EndTag("pre");
953 // We don't (yet) know how to Input or Include non-LyX files.
954 // (If we wanted to get really arcane, we could run some tex2html
955 // converter on the included file. But that's just masochistic.)
956 FileName const included_file = includedFileName(buffer(), params());
957 if (!isLyXFileName(included_file.absFileName())) {
959 frontend::Alert::warning(_("Unsupported Inclusion"),
960 bformat(_("LyX does not know how to include non-LyX files when "
961 "generating HTML output. Offending file:\n%1$s"),
962 ltrim(params()["filename"])));
966 // In the other cases, we will generate the HTML and include it.
968 Buffer const * const ibuf = loadIfNeeded();
972 if (recursion_error_)
975 // are we generating only some paragraphs, or all of them?
976 bool const all_pars = !rp.dryrun ||
977 (rp.par_begin == 0 &&
978 rp.par_end == (int)buffer().text().paragraphs().size());
980 OutputParams op = rp;
984 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
986 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
987 xs << from_utf8(included_file.absFileName());
988 xs << XMLStream::ESCAPE_NONE << " -->";
995 int InsetInclude::plaintext(odocstringstream & os,
996 OutputParams const & op, size_t) const
998 // just write the filename if we're making a tooltip or toc entry,
999 // or are generating this for advanced search
1000 if (op.for_tooltip || op.for_toc || op.for_search) {
1001 os << '[' << screenLabel() << '\n'
1002 << ltrim(getParam("filename")) << "\n]";
1003 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1006 if (isVerbatim(params()) || isListings(params())) {
1007 if (op.for_search) {
1008 os << '[' << screenLabel() << ']';
1011 os << '[' << screenLabel() << '\n'
1012 // FIXME: We don't know the encoding of the file, default to UTF-8.
1013 << includedFileName(buffer(), params()).fileContents("UTF-8")
1016 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1019 Buffer const * const ibuf = loadIfNeeded();
1021 docstring const str = '[' + screenLabel() + ']';
1026 if (recursion_error_)
1029 writePlaintextFile(*ibuf, os, op);
1034 void InsetInclude::docbook(XMLStream & xs, OutputParams const & rp) const
1039 // For verbatim and listings, we just include the contents of the file as-is.
1040 bool const verbatim = isVerbatim(params());
1041 bool const listing = isListings(params());
1042 if (listing || verbatim) {
1044 xs << xml::StartTag("programlisting");
1046 xs << xml::StartTag("literallayout");
1048 // FIXME: We don't know the encoding of the file, default to UTF-8.
1049 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
1052 xs << xml::EndTag("programlisting");
1054 xs << xml::EndTag("literallayout");
1059 // We don't know how to input or include non-LyX files. Input it as a comment.
1060 FileName const included_file = includedFileName(buffer(), params());
1061 if (!isLyXFileName(included_file.absFileName())) {
1063 frontend::Alert::warning(_("Unsupported Inclusion"),
1064 bformat(_("LyX does not know how to process included non-LyX files when "
1065 "generating DocBook output. The content of the file will be output as a "
1066 "comment. Offending file:\n%1$s"),
1067 ltrim(params()["filename"])));
1069 // Read the file, output it wrapped into comments.
1070 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
1071 xs << from_utf8(included_file.absFileName());
1072 xs << XMLStream::ESCAPE_NONE << " -->";
1074 xs << XMLStream::ESCAPE_NONE << "<!-- ";
1075 xs << included_file.fileContents("UTF-8");
1076 xs << XMLStream::ESCAPE_NONE << " -->";
1078 xs << XMLStream::ESCAPE_NONE << "<!-- End of included file: ";
1079 xs << from_utf8(included_file.absFileName());
1080 xs << XMLStream::ESCAPE_NONE << " -->";
1083 // In the other cases, we generate the DocBook version and include it.
1084 Buffer const * const ibuf = loadIfNeeded();
1088 if (recursion_error_)
1091 // are we generating only some paragraphs, or all of them?
1092 bool const all_pars = !rp.dryrun ||
1093 (rp.par_begin == 0 &&
1094 rp.par_end == (int) buffer().text().paragraphs().size());
1096 OutputParams op = rp;
1100 op.inInclude = true;
1101 op.docbook_in_par = false;
1102 ibuf->writeDocBookSource(xs.os(), op, Buffer::IncludedFile);
1104 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
1105 xs << from_utf8(included_file.absFileName());
1106 xs << XMLStream::ESCAPE_NONE << " -->";
1111 void InsetInclude::validate(LaTeXFeatures & features) const
1113 LATTEST(&buffer() == &features.buffer());
1115 string incfile = ltrim(to_utf8(params()["filename"]));
1116 string const included_file =
1117 includedFileName(buffer(), params()).absFileName();
1120 if (isLyXFileName(included_file))
1121 writefile = changeExtension(included_file, ".sgml");
1123 writefile = included_file;
1125 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1126 incfile = DocFileName(writefile).mangledFileName();
1127 writefile = makeAbsPath(incfile,
1128 buffer().masterBuffer()->temppath()).absFileName();
1131 features.includeFile(include_label, writefile);
1133 features.useInsetLayout(getLayout());
1134 if (isVerbatim(params()))
1135 features.require("verbatim");
1136 else if (isListings(params())) {
1137 if (buffer().params().use_minted) {
1138 features.require("minted");
1139 string const opts = to_utf8(params()["lstparams"]);
1140 InsetListingsParams lstpars(opts);
1141 if (!lstpars.isFloat() && contains(opts, "caption="))
1142 features.require("lyxmintcaption");
1144 features.require("listings");
1147 // Here we must do the fun stuff...
1148 // Load the file in the include if it needs
1150 Buffer * const tmp = loadIfNeeded();
1154 // the file is loaded
1155 if (checkForRecursiveInclude(tmp))
1157 buffer().pushIncludedBuffer(tmp);
1159 // We must temporarily change features.buffer,
1160 // otherwise it would always be the master buffer,
1161 // and nested includes would not work.
1162 features.setBuffer(*tmp);
1163 // Maybe this is already a child
1164 bool const is_child =
1165 features.runparams().is_child;
1166 features.runparams().is_child = true;
1167 tmp->validate(features);
1168 features.runparams().is_child = is_child;
1169 features.setBuffer(buffer());
1171 buffer().popIncludedBuffer();
1175 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1177 Buffer * ibuf = loadIfNeeded();
1181 if (checkForRecursiveInclude(ibuf))
1183 buffer().pushIncludedBuffer(ibuf);
1184 ibuf->collectBibKeys(checkedFiles);
1185 buffer().popIncludedBuffer();
1189 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1191 LBUFERR(mi.base.bv);
1193 bool use_preview = false;
1194 if (RenderPreview::previewText()) {
1195 graphics::PreviewImage const * pimage =
1196 preview_->getPreviewImage(mi.base.bv->buffer());
1197 use_preview = pimage && pimage->image();
1201 preview_->metrics(mi, dim);
1205 button_.update(screenLabel(), true, false, !file_exist_ || recursion_error_);
1207 button_.metrics(mi, dim);
1210 Box b(0, dim.wid, -dim.asc, dim.des);
1215 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1217 LBUFERR(pi.base.bv);
1219 bool use_preview = false;
1220 if (RenderPreview::previewText()) {
1221 graphics::PreviewImage const * pimage =
1222 preview_->getPreviewImage(pi.base.bv->buffer());
1223 use_preview = pimage && pimage->image();
1227 preview_->draw(pi, x, y);
1229 button_.draw(pi, x, y);
1233 void InsetInclude::write(ostream & os) const
1235 params().Write(os, &buffer());
1239 string InsetInclude::contextMenuName() const
1241 return "context-include";
1245 Inset::RowFlags InsetInclude::rowFlags() const
1247 return type(params()) == INPUT ? Inline : Display;
1251 docstring InsetInclude::layoutName() const
1253 if (isListings(params()))
1254 return from_ascii("IncludeListings");
1255 return InsetCommand::layoutName();
1263 void InsetInclude::fileChanged() const
1265 Buffer const * const buffer = updateFrontend();
1269 preview_->removePreview(*buffer);
1270 add_preview(*preview_, *this, *buffer);
1271 preview_->startLoading(*buffer);
1277 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1279 FileName const included_file = includedFileName(buffer, params);
1281 return type(params) == INPUT && params.preview() &&
1282 included_file.isReadableFile();
1286 docstring latexString(InsetInclude const & inset)
1288 odocstringstream ods;
1290 // We don't need to set runparams.encoding since this will be done
1291 // by latex() anyway.
1292 OutputParams runparams(nullptr);
1293 runparams.flavor = Flavor::LaTeX;
1294 runparams.for_preview = true;
1295 inset.latex(os, runparams);
1301 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1302 Buffer const & buffer)
1304 InsetCommandParams const & params = inset.params();
1305 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1306 renderer.setAbsFile(includedFileName(buffer, params));
1309 // InsetInclude::latex() throws if generation of LaTeX
1310 // fails, e.g. if lyx2lyx fails because file is too
1311 // new, or knitr fails.
1312 snippet = latexString(inset);
1314 // remove current preview because it is likely
1315 // associated with the previous included file name
1316 renderer.removePreview(buffer);
1317 LYXERR0("Preview of include failed.");
1320 renderer.addPreview(snippet, buffer);
1327 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1328 graphics::PreviewLoader & ploader) const
1330 Buffer const & buffer = ploader.buffer();
1331 if (!preview_wanted(params(), buffer))
1333 preview_->setAbsFile(includedFileName(buffer, params()));
1334 docstring const snippet = latexString(*this);
1335 preview_->addPreview(snippet, ploader);
1339 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1340 UpdateType utype, TocBackend & backend) const
1342 if (isListings(params())) {
1344 label_->addToToc(cpit, output_active, utype, backend);
1345 TocBuilder & b = backend.builder("listing");
1346 b.pushItem(cpit, screenLabel(), output_active);
1347 InsetListingsParams p(to_utf8(params()["lstparams"]));
1348 b.argumentItem(from_utf8(p.getParamValue("caption")));
1350 } else if (isVerbatim(params())) {
1351 TocBuilder & b = backend.builder("child");
1352 b.pushItem(cpit, screenLabel(), output_active);
1355 Buffer const * const childbuffer = loadIfNeeded();
1357 TocBuilder & b = backend.builder("child");
1358 string const fname = ltrim(to_utf8(params()["filename"]));
1359 // mark non-existent childbuffer with FILE MISSING
1360 docstring const str = (childbuffer ? from_ascii("") : _("FILE MISSING: "))
1361 + from_utf8(onlyFileName(fname)) + " (" + from_utf8(fname) + ")";
1362 b.pushItem(cpit, str, output_active);
1368 if (checkForRecursiveInclude(childbuffer))
1370 buffer().pushIncludedBuffer(childbuffer);
1371 // Update the child's tocBackend. The outliner uses the master's, but
1372 // the navigation menu uses the child's.
1373 childbuffer->tocBackend().update(output_active, utype);
1374 // Include Tocs from children
1375 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1377 buffer().popIncludedBuffer();
1378 // Copy missing outliner names (though the user has been warned against
1379 // having different document class and module selection between master
1381 for (auto const & name
1382 : childbuffer->params().documentClass().outlinerNames())
1383 backend.addName(name.first, translateIfPossible(name.second));
1388 void InsetInclude::updateCommand()
1393 docstring old_label = label_->getParam("name");
1394 label_->updateLabel(old_label);
1395 // the label might have been adapted (duplicate)
1396 docstring new_label = label_->getParam("name");
1397 if (old_label == new_label)
1400 // update listings parameters...
1401 InsetCommandParams p(INCLUDE_CODE);
1403 InsetListingsParams par(to_utf8(params()["lstparams"]));
1404 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1405 p["lstparams"] = from_utf8(par.params());
1410 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1412 file_exist_ = includedFileExist();
1413 Buffer const * const childbuffer = loadIfNeeded();
1415 if (!checkForRecursiveInclude(childbuffer))
1416 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1417 button_.update(screenLabel(), true, false, recursion_error_);
1421 button_.update(screenLabel(), true, false, !file_exist_);
1423 if (!isListings(params()))
1427 label_->updateBuffer(it, utype, deleted);
1429 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1430 if (par.getParamValue("caption").empty()) {
1431 listings_label_ = buffer().B_("Program Listing");
1434 Buffer const & master = *buffer().masterBuffer();
1435 Counters & counters = master.params().documentClass().counters();
1436 docstring const cnt = from_ascii("listing");
1437 listings_label_ = master.B_("Program Listing");
1438 if (counters.hasCounter(cnt)) {
1439 counters.step(cnt, utype);
1440 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1445 bool InsetInclude::includedFileExist() const
1447 // check whether the included file exist
1448 string incFileName = ltrim(to_utf8(params()["filename"]));
1450 support::makeAbsPath(incFileName,
1451 support::onlyPath(buffer().absFileName()));