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"
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 "OutputParams.h"
36 #include "texstream.h"
37 #include "TextClass.h"
38 #include "TocBackend.h"
40 #include "frontends/alert.h"
41 #include "frontends/Painter.h"
43 #include "graphics/PreviewImage.h"
44 #include "graphics/PreviewLoader.h"
46 #include "insets/InsetLabel.h"
47 #include "insets/InsetListingsParams.h"
48 #include "insets/RenderPreview.h"
50 #include "mathed/MacroTable.h"
52 #include "support/convert.h"
53 #include "support/debug.h"
54 #include "support/docstream.h"
55 #include "support/FileName.h"
56 #include "support/FileNameList.h"
57 #include "support/filetools.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/lstrings.h" // contains
61 #include "support/mutex.h"
62 #include "support/ExceptionMessage.h"
65 using namespace lyx::support;
69 namespace Alert = frontend::Alert;
74 docstring const uniqueID()
76 static unsigned int seed = 1000;
78 Mutex::Locker lock(&mutex);
79 return "file" + convert<docstring>(++seed);
83 /// the type of inclusion
85 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
89 Types type(string const & s)
93 if (s == "verbatiminput")
95 if (s == "verbatiminput*")
97 if (s == "lstinputlisting" || s == "inputminted")
105 Types type(InsetCommandParams const & params)
107 return type(params.getCmdName());
111 bool isListings(InsetCommandParams const & params)
113 return type(params) == LISTINGS;
117 bool isVerbatim(InsetCommandParams const & params)
119 Types const t = type(params);
120 return t == VERB || t == VERBAST;
124 bool isInputOrInclude(InsetCommandParams const & params)
126 Types const t = type(params);
127 return t == INPUT || t == INCLUDE;
131 FileName const masterFileName(Buffer const & buffer)
133 return buffer.masterBuffer()->fileName();
137 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
140 string const parentFileName(Buffer const & buffer)
142 return buffer.absFileName();
146 FileName const includedFileName(Buffer const & buffer,
147 InsetCommandParams const & params)
149 return makeAbsPath(ltrim(to_utf8(params["filename"])),
150 onlyPath(parentFileName(buffer)));
154 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
156 if (label_str.empty())
158 InsetCommandParams icp(LABEL_CODE);
159 icp["name"] = label_str;
160 return new InsetLabel(buf, icp);
164 char_type replaceCommaInBraces(docstring & params)
166 // Code point from private use area
167 char_type private_char = 0xE000;
169 for (char_type & c : params) {
174 else if (c == ',' && count)
183 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
184 : InsetCommand(buf, p), include_label(uniqueID()),
185 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
186 set_label_(false), label_(nullptr), child_buffer_(nullptr), file_exist_(false),
187 recursion_error_(false)
189 preview_->connect([=](){ fileChanged(); });
191 if (isListings(params())) {
192 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
193 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
194 } else if (isInputOrInclude(params()) && buf)
199 InsetInclude::InsetInclude(InsetInclude const & other)
200 : InsetCommand(other), include_label(other.include_label),
201 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
202 set_label_(false), label_(nullptr), child_buffer_(nullptr),
203 file_exist_(other.file_exist_),recursion_error_(other.recursion_error_)
205 preview_->connect([=](){ fileChanged(); });
208 label_ = new InsetLabel(*other.label_);
212 InsetInclude::~InsetInclude()
218 void InsetInclude::setBuffer(Buffer & buffer)
220 InsetCommand::setBuffer(buffer);
222 label_->setBuffer(buffer);
226 void InsetInclude::setChildBuffer(Buffer * buffer)
228 child_buffer_ = buffer;
232 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
235 // This is only correct for the case of listings, but it'll do for now.
236 // In the other cases, this second parameter should just be empty.
237 static ParamInfo param_info_;
238 if (param_info_.empty()) {
239 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
240 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
241 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
247 bool InsetInclude::isCompatibleCommand(string const & s)
249 return type(s) != NONE;
253 bool InsetInclude::needsCProtection(bool const /*maintext*/, bool const fragile) const
255 // We need to \cprotect all types in fragile context
260 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
262 switch (cmd.action()) {
264 case LFUN_INSET_EDIT: {
265 editIncluded(ltrim(to_utf8(params()["filename"])));
269 case LFUN_INSET_MODIFY: {
270 // It should be OK just to invalidate the cache in setParams()
272 // child_buffer_ = 0;
273 InsetCommandParams p(INCLUDE_CODE);
274 if (cmd.getArg(0) == "changetype") {
276 InsetCommand::doDispatch(cur, cmd);
279 InsetCommand::string2params(to_utf8(cmd.argument()), p);
280 if (!p.getCmdName().empty()) {
282 InsetListingsParams new_params(to_utf8(p["lstparams"]));
283 docstring const new_label =
284 from_utf8(new_params.getParamValue("label"));
286 if (new_label.empty()) {
292 old_label = label_->getParam("name");
294 label_ = createLabel(buffer_, new_label);
295 label_->setBuffer(buffer());
298 if (new_label != old_label) {
299 label_->updateLabelAndRefs(new_label, &cur);
300 // the label might have been adapted (duplicate)
301 if (new_label != label_->getParam("name")) {
302 new_params.addParam("label", "{" +
303 to_utf8(label_->getParam("name")) + "}", true);
304 p["lstparams"] = from_utf8(new_params.params());
311 cur.forceBufferUpdate();
313 cur.noScreenUpdate();
317 case LFUN_MOUSE_RELEASE: {
318 if (cmd.modifier() == ControlModifier) {
319 FileName const incfile = includedFileName(buffer(), params());
320 string const & incname = incfile.absFileName();
321 editIncluded(incname);
327 //pass everything else up the chain
329 InsetCommand::doDispatch(cur, cmd);
335 void InsetInclude::editIncluded(string const & f)
337 if (isLyXFileName(f)) {
338 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, f);
341 // tex file or other text file in verbatim mode
342 theFormats().edit(buffer(),
343 support::makeAbsPath(f, support::onlyPath(buffer().absFileName())),
348 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
349 FuncStatus & flag) const
351 switch (cmd.action()) {
353 case LFUN_INSET_EDIT:
354 flag.setEnabled(true);
357 case LFUN_INSET_MODIFY:
358 if (cmd.getArg(0) == "changetype")
359 return InsetCommand::getStatus(cur, cmd, flag);
361 flag.setEnabled(true);
365 return InsetCommand::getStatus(cur, cmd, flag);
370 void InsetInclude::setParams(InsetCommandParams const & p)
372 // invalidate the cache
373 child_buffer_ = nullptr;
375 // reset in order to allow loading new file
376 failedtoload_ = false;
377 recursion_error_ = false;
379 InsetCommand::setParams(p);
382 if (preview_->monitoring())
383 preview_->stopMonitoring();
385 if (type(params()) == INPUT)
386 add_preview(*preview_, *this, buffer());
390 bool InsetInclude::isChildIncluded() const
392 std::list<std::string> includeonlys =
393 buffer().params().getIncludedChildren();
394 if (includeonlys.empty())
396 return (std::find(includeonlys.begin(),
398 ltrim(to_utf8(params()["filename"]))) != includeonlys.end());
402 docstring InsetInclude::screenLabel() const
404 docstring pre = file_exist_ ? docstring() : _("FILE MISSING:");
408 switch (type(params())) {
410 temp = buffer().B_("Input");
413 temp = buffer().B_("Verbatim");
416 temp = buffer().B_("Verbatim*");
419 if (isChildIncluded())
420 temp = buffer().B_("Include");
422 temp += buffer().B_("Include (excluded)");
425 temp = listings_label_;
428 LASSERT(false, temp = buffer().B_("Unknown"));
434 if (ltrim(params()["filename"]).empty())
437 temp += from_utf8(onlyFileName(ltrim(to_utf8(params()["filename"]))));
439 return pre.empty() ? temp : pre + from_ascii(" ") + temp;
443 Buffer * InsetInclude::loadIfNeeded() const
445 // This is for background export and preview. We don't even want to
446 // try to load the cloned child document again.
447 if (buffer().isClone())
448 return child_buffer_;
450 // Don't try to load it again if we failed before.
451 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
454 FileName const included_file = includedFileName(buffer(), params());
455 // Use cached Buffer if possible.
456 if (child_buffer_ != nullptr) {
457 if (theBufferList().isLoaded(child_buffer_)
458 // additional sanity check: make sure the Buffer really is
459 // associated with the file we want.
460 && child_buffer_ == theBufferList().getBuffer(included_file))
461 return child_buffer_;
462 // Buffer vanished, so invalidate cache and try to reload.
463 child_buffer_ = nullptr;
466 if (!isLyXFileName(included_file.absFileName()))
469 Buffer * child = theBufferList().getBuffer(included_file);
470 if (checkForRecursiveInclude(child))
474 // the readonly flag can/will be wrong, not anymore I think.
475 if (!included_file.exists()) {
476 failedtoload_ = true;
480 child = theBufferList().newBuffer(included_file.absFileName());
482 // Buffer creation is not possible.
485 buffer().pushIncludedBuffer(child);
486 // Set parent before loading, such that macros can be tracked
487 child->setParent(&buffer());
489 if (child->loadLyXFile() != Buffer::ReadSuccess) {
490 failedtoload_ = true;
491 child->setParent(nullptr);
492 //close the buffer we just opened
493 theBufferList().release(child);
494 buffer().popIncludedBuffer();
498 buffer().popIncludedBuffer();
499 if (!child->errorList("Parse").empty()) {
500 // FIXME: Do something.
503 // The file was already loaded, so, simply
504 // inform parent buffer about local macros.
505 Buffer const * parent = &buffer();
506 child->setParent(parent);
508 child->listMacroNames(macros);
509 MacroNameSet::const_iterator cit = macros.begin();
510 MacroNameSet::const_iterator end = macros.end();
511 for (; cit != end; ++cit)
512 parent->usermacros.insert(*cit);
515 // Cache the child buffer.
516 child_buffer_ = child;
521 bool InsetInclude::checkForRecursiveInclude(
522 Buffer const * cbuf, bool silent) const
524 if (recursion_error_)
527 if (!buffer().isBufferIncluded(cbuf))
531 docstring const msg = _("The file\n%1$s\n has attempted to include itself.\n"
532 "The document set will not work properly until this is fixed!");
533 frontend::Alert::warning(_("Recursive Include"),
534 bformat(msg, from_utf8(cbuf->fileName().absFileName())));
536 recursion_error_ = true;
541 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
543 string incfile = ltrim(to_utf8(params()["filename"]));
545 // Warn if no file name has been specified
546 if (incfile.empty()) {
547 frontend::Alert::warning(_("No file name specified"),
548 _("An included file name is empty.\n"
549 "Ignoring Inclusion"),
553 // Warn if file doesn't exist
554 if (!includedFileExist()) {
555 frontend::Alert::warning(_("Included file not found"),
556 bformat(_("The included file\n"
558 "has not been found. LyX will ignore the inclusion."),
564 FileName const included_file = includedFileName(buffer(), params());
565 Buffer const * const masterBuffer = buffer().masterBuffer();
567 // if incfile is relative, make it relative to the master
569 if (!FileName::isAbsolute(incfile)) {
571 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
572 from_utf8(masterBuffer->filePath())));
575 string exppath = incfile;
576 if (!runparams.export_folder.empty()) {
577 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
580 // write it to a file (so far the complete file)
584 if (type(params()) == LISTINGS) {
585 exportfile = exppath;
586 mangled = DocFileName(included_file).mangledFileName();
588 exportfile = changeExtension(exppath, ".tex");
589 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
595 else if (!runparams.silent)
596 ; // no warning wanted
597 else if (!isValidLaTeXFileName(incfile)) {
598 frontend::Alert::warning(_("Invalid filename"),
599 _("The following filename will cause troubles "
600 "when running the exported file through LaTeX: ") +
602 } else if (!isValidDVIFileName(incfile)) {
603 frontend::Alert::warning(_("Problematic filename for DVI"),
604 _("The following filename can cause troubles "
605 "when running the exported file through LaTeX "
606 "and opening the resulting DVI: ") +
607 from_utf8(incfile), true);
610 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
611 buffer().temppath() : masterBuffer->temppath()));
613 LYXERR(Debug::LATEX, "incfile:" << incfile);
614 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
615 LYXERR(Debug::LATEX, "writefile:" << writefile);
617 string const tex_format = flavor2format(runparams.flavor);
619 switch (type(params())) {
622 incfile = latex_path(incfile);
624 os << '\\' << from_ascii(params().getCmdName()) << '{'
625 << from_utf8(incfile) << '}';
629 runparams.exportdata->addExternalFile(tex_format, writefile,
632 // \input wants file with extension (default is .tex)
633 if (!isLyXFileName(included_file.absFileName())) {
634 incfile = latex_path(incfile);
636 os << '\\' << from_ascii(params().getCmdName())
637 << '{' << from_utf8(incfile) << '}';
639 incfile = changeExtension(incfile, ".tex");
640 incfile = latex_path(incfile);
642 os << '\\' << from_ascii(params().getCmdName())
643 << '{' << from_utf8(incfile) << '}';
648 // Here, listings and minted have slightly different behaviors.
649 // Using listings, it is always possible to have a caption,
650 // even for non-floats. Using minted, only floats can have a
651 // caption. So, with minted we use the following strategy.
652 // If a caption was specified but the float parameter was not,
653 // we ourselves add a caption above the listing (because the
654 // listing comes from a file and might span several pages).
655 // Otherwise, if float was specified, the floating listing
656 // environment provided by minted is used. In either case, the
657 // label parameter is taken as the label by which the float
658 // can be referenced, otherwise it will have the meaning
659 // intended by minted. In this last case, the label will
660 // serve as a sort of caption that, however, will be shown
661 // by minted only if the frame parameter is also specified.
662 bool const use_minted = buffer().params().use_minted;
663 runparams.exportdata->addExternalFile(tex_format, writefile,
665 string const opt = to_utf8(params()["lstparams"]);
666 // opt is set in QInclude dialog and should have passed validation.
667 InsetListingsParams lstparams(opt);
668 docstring parameters = from_utf8(lstparams.params());
673 bool isfloat = lstparams.isFloat();
674 // We are going to split parameters at commas, so
675 // replace commas that are not parameter separators
676 // with a code point from the private use area
677 char_type comma = replaceCommaInBraces(parameters);
678 // Get float placement, language, caption, and
679 // label, then remove the relative options if minted.
680 vector<docstring> opts =
681 getVectorFromString(parameters, from_ascii(","), false);
682 vector<docstring> latexed_opts;
683 for (size_t i = 0; i < opts.size(); ++i) {
684 // Restore replaced commas
685 opts[i] = subst(opts[i], comma, ',');
686 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
687 if (prefixIs(opts[i], from_ascii("float=")))
688 placement = opts[i].substr(6);
689 opts.erase(opts.begin() + i--);
690 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
691 language = opts[i].substr(9);
692 opts.erase(opts.begin() + i--);
693 } else if (prefixIs(opts[i], from_ascii("caption="))) {
694 caption = params().prepareCommand(runparams, trim(opts[i].substr(8), "{}"),
695 ParamInfo::HANDLING_LATEXIFY);
696 opts.erase(opts.begin() + i--);
698 latexed_opts.push_back(from_ascii("caption={") + caption + "}");
699 } else if (prefixIs(opts[i], from_ascii("label="))) {
700 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
701 ParamInfo::HANDLING_ESCAPE);
702 opts.erase(opts.begin() + i--);
704 latexed_opts.push_back(from_ascii("label={") + label + "}");
706 if (use_minted && !label.empty()) {
707 if (isfloat || !caption.empty())
708 label = trim(label, "{}");
710 opts.push_back(from_ascii("label=") + label);
713 if (!latexed_opts.empty())
714 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
715 parameters = getStringFromVector(opts, from_ascii(","));
716 if (language.empty())
717 language = from_ascii("TeX");
718 if (use_minted && isfloat) {
719 os << breakln << "\\begin{listing}";
720 if (!placement.empty())
721 os << '[' << placement << "]";
723 } else if (use_minted && !caption.empty()) {
724 os << breakln << "\\lyxmintcaption[t]{" << caption;
726 os << "\\label{" << label << "}";
729 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
730 if (!parameters.empty())
731 os << "[" << parameters << "]";
733 os << '{' << ascii_lowercase(language) << '}';
734 os << '{' << incfile << '}';
735 if (use_minted && isfloat) {
736 if (!caption.empty())
737 os << breakln << "\\caption{" << caption << "}";
739 os << breakln << "\\label{" << label << "}";
740 os << breakln << "\\end{listing}\n";
745 runparams.exportdata->addExternalFile(tex_format, writefile,
748 // \include don't want extension and demands that the
749 // file really have .tex
750 incfile = changeExtension(incfile, string());
751 incfile = latex_path(incfile);
753 os << '\\' << from_ascii(params().getCmdName()) << '{'
754 << from_utf8(incfile) << '}';
761 if (runparams.inComment || runparams.dryrun)
762 // Don't try to load or copy the file if we're
763 // in a comment or doing a dryrun
766 if (!isInputOrInclude(params()) ||
767 !isLyXFileName(included_file.absFileName())) {
768 // In this case, it's not a LyX file, so we copy the file
769 // to the temp dir, so that .aux files etc. are not created
770 // in the original dir. Files included by this file will be
771 // found via either the environment variable TEXINPUTS, or
772 // input@path, see ../Buffer.cpp.
773 unsigned long const checksum_in = included_file.checksum();
774 unsigned long const checksum_out = writefile.checksum();
775 if (checksum_in != checksum_out) {
776 if (!included_file.copyTo(writefile)) {
779 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
780 "into the temporary directory."),
781 from_utf8(included_file.absFileName()))));
788 // it's a LyX file and we're inputting or including, so
789 // try to load it so we can write the associated latex
790 Buffer * tmp = loadIfNeeded();
792 if (!runparams.silent) {
793 docstring text = bformat(_("Could not load included "
795 "Please, check whether it actually exists."),
796 included_file.displayName());
797 throw ExceptionMessage(ErrorException, _("Error: "),
803 if (recursion_error_)
806 if (!runparams.silent) {
807 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
809 docstring text = bformat(_("Included file `%1$s'\n"
810 "has textclass `%2$s'\n"
811 "while parent file has textclass `%3$s'."),
812 included_file.displayName(),
813 from_utf8(tmp->params().documentClass().name()),
814 from_utf8(masterBuffer->params().documentClass().name()));
815 Alert::warning(_("Different textclasses"), text, true);
818 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
819 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
820 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
821 docstring text = bformat(_("Included file `%1$s'\n"
822 "has use-non-TeX-fonts set to `%2$s'\n"
823 "while parent file has use-non-TeX-fonts set to `%3$s'."),
824 included_file.displayName(),
826 from_utf8(master_tf));
827 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
829 else if (tmp->params().inputenc != masterBuffer->params().inputenc) {
830 docstring text = bformat(_("Included file `%1$s'\n"
831 "uses input encoding \"%2$s\" [%3$s]\n"
832 "while parent file uses input encoding \"%4$s\" [%5$s]."),
833 included_file.displayName(),
834 _(tmp->params().inputenc),
835 from_utf8(tmp->params().encoding().guiName()),
836 _(masterBuffer->params().inputenc),
837 from_utf8(masterBuffer->params().encoding().guiName()));
838 Alert::warning(_("Different LaTeX input encodings"), text, true);
841 // Make sure modules used in child are all included in master
842 // FIXME It might be worth loading the children's modules into the master
843 // over in BufferParams rather than doing this check.
844 LayoutModuleList const masterModules = masterBuffer->params().getModules();
845 LayoutModuleList const childModules = tmp->params().getModules();
846 LayoutModuleList::const_iterator it = childModules.begin();
847 LayoutModuleList::const_iterator end = childModules.end();
848 for (; it != end; ++it) {
849 string const module = *it;
850 LayoutModuleList::const_iterator found =
851 find(masterModules.begin(), masterModules.end(), module);
852 if (found == masterModules.end()) {
853 docstring text = bformat(_("Included file `%1$s'\n"
854 "uses module `%2$s'\n"
855 "which is not used in parent file."),
856 included_file.displayName(), from_utf8(module));
857 Alert::warning(_("Module not found"), text, true);
862 tmp->markDepClean(masterBuffer->temppath());
864 // Don't assume the child's format is latex
865 string const inc_format = tmp->params().bufferFormat();
866 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
867 theFormats().extension(inc_format)));
869 // FIXME: handle non existing files
870 // The included file might be written in a different encoding
872 Encoding const * const oldEnc = runparams.encoding;
873 Language const * const oldLang = runparams.master_language;
874 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
875 // the children must be encoded in plain utf8!
876 if (masterBuffer->params().useNonTeXFonts)
877 runparams.encoding = encodings.fromLyXName("utf8-plain");
879 runparams.encoding = oldEnc;
880 else runparams.encoding = &tmp->params().encoding();
881 runparams.master_language = buffer().params().language;
882 runparams.par_begin = 0;
883 runparams.par_end = tmp->paragraphs().size();
884 runparams.is_child = true;
885 Buffer::ExportStatus retval =
886 tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
887 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
888 if (retval == Buffer::ExportKilled && buffer().isClone() &&
889 buffer().isExporting()) {
890 // We really shouldn't get here, I don't think.
891 LYXERR0("No conversion exception?");
892 throw ConversionException();
894 else if (retval != Buffer::ExportSuccess) {
895 if (!runparams.silent) {
896 docstring msg = bformat(_("Included file `%1$s' "
897 "was not exported correctly.\n "
898 "LaTeX export is probably incomplete."),
899 included_file.displayName());
900 ErrorList const & el = tmp->errorList("Export");
902 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
903 msg, el.begin()->error, el.begin()->description);
904 throw ExceptionMessage(ErrorException, _("Error: "), msg);
907 runparams.encoding = oldEnc;
908 runparams.master_language = oldLang;
909 runparams.is_child = false;
911 // If needed, use converters to produce a latex file from the child
912 if (tmpwritefile != writefile) {
914 Converters::RetVal const conv_retval =
915 theConverters().convert(tmp, tmpwritefile, writefile,
916 included_file, inc_format, tex_format, el);
917 if (conv_retval == Converters::KILLED && buffer().isClone() &&
918 buffer().isExporting()) {
919 // We really shouldn't get here, I don't think.
920 LYXERR0("No conversion exception?");
921 throw ConversionException();
922 } else if (conv_retval != Converters::SUCCESS && !runparams.silent) {
923 docstring msg = bformat(_("Included file `%1$s' "
924 "was not exported correctly.\n "
925 "LaTeX export is probably incomplete."),
926 included_file.displayName());
928 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
929 msg, el.begin()->error, el.begin()->description);
930 throw ExceptionMessage(ErrorException, _("Error: "), msg);
936 docstring InsetInclude::xhtml(XMLStream & xs, OutputParams const & rp) const
941 // For verbatim and listings, we just include the contents of the file as-is.
942 // In the case of listings, we wrap it in <pre>.
943 bool const listing = isListings(params());
944 if (listing || isVerbatim(params())) {
946 xs << xml::StartTag("pre");
947 // FIXME: We don't know the encoding of the file, default to UTF-8.
948 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
950 xs << xml::EndTag("pre");
954 // We don't (yet) know how to Input or Include non-LyX files.
955 // (If we wanted to get really arcane, we could run some tex2html
956 // converter on the included file. But that's just masochistic.)
957 FileName const included_file = includedFileName(buffer(), params());
958 if (!isLyXFileName(included_file.absFileName())) {
960 frontend::Alert::warning(_("Unsupported Inclusion"),
961 bformat(_("LyX does not know how to include non-LyX files when "
962 "generating HTML output. Offending file:\n%1$s"),
963 ltrim(params()["filename"])));
967 // In the other cases, we will generate the HTML and include it.
969 Buffer const * const ibuf = loadIfNeeded();
973 if (recursion_error_)
976 // are we generating only some paragraphs, or all of them?
977 bool const all_pars = !rp.dryrun ||
978 (rp.par_begin == 0 &&
979 rp.par_end == (int)buffer().text().paragraphs().size());
981 OutputParams op = rp;
985 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
987 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
988 xs << from_utf8(included_file.absFileName());
989 xs << XMLStream::ESCAPE_NONE << " -->";
996 int InsetInclude::plaintext(odocstringstream & os,
997 OutputParams const & op, size_t) const
999 // just write the filename if we're making a tooltip or toc entry,
1000 // or are generating this for advanced search
1001 if (op.for_tooltip || op.for_toc || op.for_search) {
1002 os << '[' << screenLabel() << '\n'
1003 << ltrim(getParam("filename")) << "\n]";
1004 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1007 if (isVerbatim(params()) || isListings(params())) {
1008 if (op.for_search) {
1009 os << '[' << screenLabel() << ']';
1012 os << '[' << screenLabel() << '\n'
1013 // FIXME: We don't know the encoding of the file, default to UTF-8.
1014 << includedFileName(buffer(), params()).fileContents("UTF-8")
1017 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1020 Buffer const * const ibuf = loadIfNeeded();
1022 docstring const str = '[' + screenLabel() + ']';
1027 if (recursion_error_)
1030 writePlaintextFile(*ibuf, os, op);
1035 void InsetInclude::docbook(XMLStream & xs, OutputParams const & rp) const
1040 // For verbatim and listings, we just include the contents of the file as-is.
1041 bool const verbatim = isVerbatim(params());
1042 bool const listing = isListings(params());
1043 if (listing || verbatim) {
1045 xs << xml::StartTag("programlisting");
1047 xs << xml::StartTag("literallayout");
1049 // FIXME: We don't know the encoding of the file, default to UTF-8.
1050 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
1053 xs << xml::EndTag("programlisting");
1055 xs << xml::EndTag("literallayout");
1060 // We don't know how to input or include non-LyX files. Input it as a comment.
1061 FileName const included_file = includedFileName(buffer(), params());
1062 if (!isLyXFileName(included_file.absFileName())) {
1064 frontend::Alert::warning(_("Unsupported Inclusion"),
1065 bformat(_("LyX does not know how to process included non-LyX files when "
1066 "generating DocBook output. The content of the file will be output as a "
1067 "comment. Offending file:\n%1$s"),
1068 ltrim(params()["filename"])));
1070 // Read the file, output it wrapped into comments.
1071 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
1072 xs << from_utf8(included_file.absFileName());
1073 xs << XMLStream::ESCAPE_NONE << " -->";
1075 xs << XMLStream::ESCAPE_NONE << "<!-- ";
1076 xs << included_file.fileContents("UTF-8");
1077 xs << XMLStream::ESCAPE_NONE << " -->";
1079 xs << XMLStream::ESCAPE_NONE << "<!-- End of included file: ";
1080 xs << from_utf8(included_file.absFileName());
1081 xs << XMLStream::ESCAPE_NONE << " -->";
1084 // In the other cases, we generate the DocBook version and include it.
1085 Buffer const * const ibuf = loadIfNeeded();
1089 if (recursion_error_)
1092 // are we generating only some paragraphs, or all of them?
1093 bool const all_pars = !rp.dryrun ||
1094 (rp.par_begin == 0 &&
1095 rp.par_end == (int) buffer().text().paragraphs().size());
1097 OutputParams op = rp;
1101 op.inInclude = true;
1102 op.docbook_in_par = false;
1103 ibuf->writeDocBookSource(xs.os(), op, Buffer::IncludedFile);
1105 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
1106 xs << from_utf8(included_file.absFileName());
1107 xs << XMLStream::ESCAPE_NONE << " -->";
1112 void InsetInclude::validate(LaTeXFeatures & features) const
1114 LATTEST(&buffer() == &features.buffer());
1116 string incfile = ltrim(to_utf8(params()["filename"]));
1117 string const included_file =
1118 includedFileName(buffer(), params()).absFileName();
1121 if (isLyXFileName(included_file))
1122 writefile = changeExtension(included_file, ".sgml");
1124 writefile = included_file;
1126 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1127 incfile = DocFileName(writefile).mangledFileName();
1128 writefile = makeAbsPath(incfile,
1129 buffer().masterBuffer()->temppath()).absFileName();
1132 features.includeFile(include_label, writefile);
1134 features.useInsetLayout(getLayout());
1135 if (isVerbatim(params()))
1136 features.require("verbatim");
1137 else if (isListings(params())) {
1138 if (buffer().params().use_minted) {
1139 features.require("minted");
1140 string const opts = to_utf8(params()["lstparams"]);
1141 InsetListingsParams lstpars(opts);
1142 if (!lstpars.isFloat() && contains(opts, "caption="))
1143 features.require("lyxmintcaption");
1145 features.require("listings");
1148 // Here we must do the fun stuff...
1149 // Load the file in the include if it needs
1151 Buffer * const tmp = loadIfNeeded();
1155 // the file is loaded
1156 if (checkForRecursiveInclude(tmp))
1158 buffer().pushIncludedBuffer(tmp);
1160 // We must temporarily change features.buffer,
1161 // otherwise it would always be the master buffer,
1162 // and nested includes would not work.
1163 features.setBuffer(*tmp);
1164 // Maybe this is already a child
1165 bool const is_child =
1166 features.runparams().is_child;
1167 features.runparams().is_child = true;
1168 tmp->validate(features);
1169 features.runparams().is_child = is_child;
1170 features.setBuffer(buffer());
1172 buffer().popIncludedBuffer();
1176 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1178 Buffer * ibuf = loadIfNeeded();
1182 if (checkForRecursiveInclude(ibuf))
1184 buffer().pushIncludedBuffer(ibuf);
1185 ibuf->collectBibKeys(checkedFiles);
1186 buffer().popIncludedBuffer();
1190 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1192 LBUFERR(mi.base.bv);
1194 bool use_preview = false;
1195 if (RenderPreview::previewText()) {
1196 graphics::PreviewImage const * pimage =
1197 preview_->getPreviewImage(mi.base.bv->buffer());
1198 use_preview = pimage && pimage->image();
1202 preview_->metrics(mi, dim);
1206 button_.update(screenLabel(), true, false, !file_exist_ || recursion_error_);
1208 button_.metrics(mi, dim);
1211 Box b(0, dim.wid, -dim.asc, dim.des);
1216 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1218 LBUFERR(pi.base.bv);
1220 bool use_preview = false;
1221 if (RenderPreview::previewText()) {
1222 graphics::PreviewImage const * pimage =
1223 preview_->getPreviewImage(pi.base.bv->buffer());
1224 use_preview = pimage && pimage->image();
1228 preview_->draw(pi, x, y);
1230 button_.draw(pi, x, y);
1234 void InsetInclude::write(ostream & os) const
1236 params().Write(os, &buffer());
1240 string InsetInclude::contextMenuName() const
1242 return "context-include";
1246 Inset::RowFlags InsetInclude::rowFlags() const
1248 return type(params()) == INPUT ? Inline : Display;
1252 docstring InsetInclude::layoutName() const
1254 if (isListings(params()))
1255 return from_ascii("IncludeListings");
1256 return InsetCommand::layoutName();
1264 void InsetInclude::fileChanged() const
1266 Buffer const * const buffer = updateFrontend();
1270 preview_->removePreview(*buffer);
1271 add_preview(*preview_, *this, *buffer);
1272 preview_->startLoading(*buffer);
1278 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1280 FileName const included_file = includedFileName(buffer, params);
1282 return type(params) == INPUT && params.preview() &&
1283 included_file.isReadableFile();
1287 docstring latexString(InsetInclude const & inset)
1289 odocstringstream ods;
1291 // We don't need to set runparams.encoding since this will be done
1292 // by latex() anyway.
1293 OutputParams runparams(nullptr);
1294 runparams.flavor = OutputParams::LATEX;
1295 runparams.for_preview = true;
1296 inset.latex(os, runparams);
1302 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1303 Buffer const & buffer)
1305 InsetCommandParams const & params = inset.params();
1306 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1307 renderer.setAbsFile(includedFileName(buffer, params));
1310 // InsetInclude::latex() throws if generation of LaTeX
1311 // fails, e.g. if lyx2lyx fails because file is too
1312 // new, or knitr fails.
1313 snippet = latexString(inset);
1315 // remove current preview because it is likely
1316 // associated with the previous included file name
1317 renderer.removePreview(buffer);
1318 LYXERR0("Preview of include failed.");
1321 renderer.addPreview(snippet, buffer);
1328 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1329 graphics::PreviewLoader & ploader) const
1331 Buffer const & buffer = ploader.buffer();
1332 if (!preview_wanted(params(), buffer))
1334 preview_->setAbsFile(includedFileName(buffer, params()));
1335 docstring const snippet = latexString(*this);
1336 preview_->addPreview(snippet, ploader);
1340 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1341 UpdateType utype, TocBackend & backend) const
1343 if (isListings(params())) {
1345 label_->addToToc(cpit, output_active, utype, backend);
1346 TocBuilder & b = backend.builder("listing");
1347 b.pushItem(cpit, screenLabel(), output_active);
1348 InsetListingsParams p(to_utf8(params()["lstparams"]));
1349 b.argumentItem(from_utf8(p.getParamValue("caption")));
1351 } else if (isVerbatim(params())) {
1352 TocBuilder & b = backend.builder("child");
1353 b.pushItem(cpit, screenLabel(), output_active);
1356 Buffer const * const childbuffer = loadIfNeeded();
1358 TocBuilder & b = backend.builder("child");
1359 string const fname = ltrim(to_utf8(params()["filename"]));
1360 // mark non-existent childbuffer with FILE MISSING
1361 docstring const str = (childbuffer ? from_ascii("") : _("FILE MISSING: "))
1362 + from_utf8(onlyFileName(fname)) + " (" + from_utf8(fname) + ")";
1363 b.pushItem(cpit, str, output_active);
1369 if (checkForRecursiveInclude(childbuffer))
1371 buffer().pushIncludedBuffer(childbuffer);
1372 // Update the child's tocBackend. The outliner uses the master's, but
1373 // the navigation menu uses the child's.
1374 childbuffer->tocBackend().update(output_active, utype);
1375 // Include Tocs from children
1376 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1378 buffer().popIncludedBuffer();
1379 // Copy missing outliner names (though the user has been warned against
1380 // having different document class and module selection between master
1382 for (auto const & name
1383 : childbuffer->params().documentClass().outlinerNames())
1384 backend.addName(name.first, translateIfPossible(name.second));
1389 void InsetInclude::updateCommand()
1394 docstring old_label = label_->getParam("name");
1395 label_->updateLabel(old_label);
1396 // the label might have been adapted (duplicate)
1397 docstring new_label = label_->getParam("name");
1398 if (old_label == new_label)
1401 // update listings parameters...
1402 InsetCommandParams p(INCLUDE_CODE);
1404 InsetListingsParams par(to_utf8(params()["lstparams"]));
1405 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1406 p["lstparams"] = from_utf8(par.params());
1411 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1413 file_exist_ = includedFileExist();
1414 Buffer const * const childbuffer = loadIfNeeded();
1416 if (!checkForRecursiveInclude(childbuffer))
1417 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1418 button_.update(screenLabel(), true, false, recursion_error_);
1422 button_.update(screenLabel(), true, false, !file_exist_);
1424 if (!isListings(params()))
1428 label_->updateBuffer(it, utype, deleted);
1430 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1431 if (par.getParamValue("caption").empty()) {
1432 listings_label_ = buffer().B_("Program Listing");
1435 Buffer const & master = *buffer().masterBuffer();
1436 Counters & counters = master.params().documentClass().counters();
1437 docstring const cnt = from_ascii("listing");
1438 listings_label_ = master.B_("Program Listing");
1439 if (counters.hasCounter(cnt)) {
1440 counters.step(cnt, utype);
1441 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1446 bool InsetInclude::includedFileExist() const
1448 // check whether the included file exist
1449 string incFileName = ltrim(to_utf8(params()["filename"]));
1451 support::makeAbsPath(incFileName,
1452 support::onlyPath(buffer().absFileName()));