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"
23 #include "DispatchResult.h"
25 #include "ErrorList.h"
28 #include "FuncRequest.h"
29 #include "FuncStatus.h"
30 #include "LaTeXFeatures.h"
31 #include "LayoutFile.h"
32 #include "LayoutModuleList.h"
35 #include "MetricsInfo.h"
36 #include "output_plaintext.h"
37 #include "output_xhtml.h"
38 #include "OutputParams.h"
39 #include "texstream.h"
40 #include "TextClass.h"
41 #include "TocBackend.h"
43 #include "frontends/alert.h"
44 #include "frontends/Painter.h"
46 #include "graphics/PreviewImage.h"
47 #include "graphics/PreviewLoader.h"
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetListingsParams.h"
51 #include "insets/RenderPreview.h"
53 #include "mathed/MacroTable.h"
55 #include "support/convert.h"
56 #include "support/debug.h"
57 #include "support/docstream.h"
58 #include "support/FileName.h"
59 #include "support/FileNameList.h"
60 #include "support/filetools.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/lstrings.h" // contains
64 #include "support/lyxalgo.h"
65 #include "support/mutex.h"
66 #include "support/ExceptionMessage.h"
68 #include "support/bind.h"
71 using namespace lyx::support;
75 namespace Alert = frontend::Alert;
80 docstring const uniqueID()
82 static unsigned int seed = 1000;
84 Mutex::Locker lock(&mutex);
85 return "file" + convert<docstring>(++seed);
89 /// the type of inclusion
91 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
95 Types type(string const & s)
99 if (s == "verbatiminput")
101 if (s == "verbatiminput*")
103 if (s == "lstinputlisting" || s == "inputminted")
111 Types type(InsetCommandParams const & params)
113 return type(params.getCmdName());
117 bool isListings(InsetCommandParams const & params)
119 return type(params) == LISTINGS;
123 bool isVerbatim(InsetCommandParams const & params)
125 Types const t = type(params);
126 return t == VERB || t == VERBAST;
130 bool isInputOrInclude(InsetCommandParams const & params)
132 Types const t = type(params);
133 return t == INPUT || t == INCLUDE;
137 FileName const masterFileName(Buffer const & buffer)
139 return buffer.masterBuffer()->fileName();
143 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
146 string const parentFileName(Buffer const & buffer)
148 return buffer.absFileName();
152 FileName const includedFileName(Buffer const & buffer,
153 InsetCommandParams const & params)
155 return makeAbsPath(ltrim(to_utf8(params["filename"])),
156 onlyPath(parentFileName(buffer)));
160 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
162 if (label_str.empty())
164 InsetCommandParams icp(LABEL_CODE);
165 icp["name"] = label_str;
166 return new InsetLabel(buf, icp);
170 char_type replaceCommaInBraces(docstring & params)
172 // Code point from private use area
173 char_type private_char = 0xE000;
175 for (char_type & c : params) {
180 else if (c == ',' && count)
189 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
190 : InsetCommand(buf, p), include_label(uniqueID()),
191 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
192 set_label_(false), label_(nullptr), child_buffer_(nullptr), file_exist_(false),
193 recursion_error_(false)
195 preview_->connect([=](){ fileChanged(); });
197 if (isListings(params())) {
198 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
199 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
200 } else if (isInputOrInclude(params()) && buf)
205 InsetInclude::InsetInclude(InsetInclude const & other)
206 : InsetCommand(other), include_label(other.include_label),
207 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
208 set_label_(false), label_(nullptr), child_buffer_(nullptr),
209 file_exist_(other.file_exist_),recursion_error_(other.recursion_error_)
211 preview_->connect([=](){ fileChanged(); });
214 label_ = new InsetLabel(*other.label_);
218 InsetInclude::~InsetInclude()
224 void InsetInclude::setBuffer(Buffer & buffer)
226 InsetCommand::setBuffer(buffer);
228 label_->setBuffer(buffer);
232 void InsetInclude::setChildBuffer(Buffer * buffer)
234 child_buffer_ = buffer;
238 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
241 // This is only correct for the case of listings, but it'll do for now.
242 // In the other cases, this second parameter should just be empty.
243 static ParamInfo param_info_;
244 if (param_info_.empty()) {
245 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
246 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
247 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
253 bool InsetInclude::isCompatibleCommand(string const & s)
255 return type(s) != NONE;
259 bool InsetInclude::needsCProtection(bool const /*maintext*/, bool const fragile) const
261 // We need to \cprotect all types in fragile context
266 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
268 switch (cmd.action()) {
270 case LFUN_INSET_EDIT: {
271 editIncluded(ltrim(to_utf8(params()["filename"])));
275 case LFUN_INSET_MODIFY: {
276 // It should be OK just to invalidate the cache in setParams()
278 // child_buffer_ = 0;
279 InsetCommandParams p(INCLUDE_CODE);
280 if (cmd.getArg(0) == "changetype") {
282 InsetCommand::doDispatch(cur, cmd);
285 InsetCommand::string2params(to_utf8(cmd.argument()), p);
286 if (!p.getCmdName().empty()) {
288 InsetListingsParams new_params(to_utf8(p["lstparams"]));
289 docstring const new_label =
290 from_utf8(new_params.getParamValue("label"));
292 if (new_label.empty()) {
298 old_label = label_->getParam("name");
300 label_ = createLabel(buffer_, new_label);
301 label_->setBuffer(buffer());
304 if (new_label != old_label) {
305 label_->updateLabelAndRefs(new_label, &cur);
306 // the label might have been adapted (duplicate)
307 if (new_label != label_->getParam("name")) {
308 new_params.addParam("label", "{" +
309 to_utf8(label_->getParam("name")) + "}", true);
310 p["lstparams"] = from_utf8(new_params.params());
317 cur.forceBufferUpdate();
319 cur.noScreenUpdate();
323 case LFUN_MOUSE_RELEASE: {
324 if (cmd.modifier() == ControlModifier) {
325 FileName const incfile = includedFileName(buffer(), params());
326 string const & incname = incfile.absFileName();
327 editIncluded(incname);
333 //pass everything else up the chain
335 InsetCommand::doDispatch(cur, cmd);
341 void InsetInclude::editIncluded(string const & f)
343 if (isLyXFileName(f)) {
344 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, f);
347 // tex file or other text file in verbatim mode
348 theFormats().edit(buffer(),
349 support::makeAbsPath(f, support::onlyPath(buffer().absFileName())),
354 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
355 FuncStatus & flag) const
357 switch (cmd.action()) {
359 case LFUN_INSET_EDIT:
360 flag.setEnabled(true);
363 case LFUN_INSET_MODIFY:
364 if (cmd.getArg(0) == "changetype")
365 return InsetCommand::getStatus(cur, cmd, flag);
367 flag.setEnabled(true);
371 return InsetCommand::getStatus(cur, cmd, flag);
376 void InsetInclude::setParams(InsetCommandParams const & p)
378 // invalidate the cache
379 child_buffer_ = nullptr;
381 // reset in order to allow loading new file
382 failedtoload_ = false;
383 recursion_error_ = false;
385 InsetCommand::setParams(p);
388 if (preview_->monitoring())
389 preview_->stopMonitoring();
391 if (type(params()) == INPUT)
392 add_preview(*preview_, *this, buffer());
396 bool InsetInclude::isChildIncluded() const
398 std::list<std::string> includeonlys =
399 buffer().params().getIncludedChildren();
400 if (includeonlys.empty())
402 return (std::find(includeonlys.begin(),
404 ltrim(to_utf8(params()["filename"]))) != includeonlys.end());
408 docstring InsetInclude::screenLabel() const
410 docstring pre = file_exist_ ? docstring() : _("FILE MISSING:");
414 switch (type(params())) {
416 temp = buffer().B_("Input");
419 temp = buffer().B_("Verbatim");
422 temp = buffer().B_("Verbatim*");
425 if (isChildIncluded())
426 temp = buffer().B_("Include");
428 temp += buffer().B_("Include (excluded)");
431 temp = listings_label_;
434 LASSERT(false, temp = buffer().B_("Unknown"));
440 if (ltrim(params()["filename"]).empty())
443 temp += from_utf8(onlyFileName(ltrim(to_utf8(params()["filename"]))));
445 return pre.empty() ? temp : pre + from_ascii(" ") + temp;
449 Buffer * InsetInclude::getChildBuffer() const
451 return loadIfNeeded();
455 Buffer * InsetInclude::loadIfNeeded() const
457 // This is for background export and preview. We don't even want to
458 // try to load the cloned child document again.
459 if (buffer().isClone())
460 return child_buffer_;
462 // Don't try to load it again if we failed before.
463 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
466 FileName const included_file = includedFileName(buffer(), params());
467 // Use cached Buffer if possible.
468 if (child_buffer_ != nullptr) {
469 if (theBufferList().isLoaded(child_buffer_)
470 // additional sanity check: make sure the Buffer really is
471 // associated with the file we want.
472 && child_buffer_ == theBufferList().getBuffer(included_file))
473 return child_buffer_;
474 // Buffer vanished, so invalidate cache and try to reload.
475 child_buffer_ = nullptr;
478 if (!isLyXFileName(included_file.absFileName()))
481 Buffer * child = theBufferList().getBuffer(included_file);
482 if (checkForRecursiveInclude(child))
486 // the readonly flag can/will be wrong, not anymore I think.
487 if (!included_file.exists()) {
488 failedtoload_ = true;
492 child = theBufferList().newBuffer(included_file.absFileName());
494 // Buffer creation is not possible.
497 buffer().pushIncludedBuffer(child);
498 // Set parent before loading, such that macros can be tracked
499 child->setParent(&buffer());
501 if (child->loadLyXFile() != Buffer::ReadSuccess) {
502 failedtoload_ = true;
503 child->setParent(nullptr);
504 //close the buffer we just opened
505 theBufferList().release(child);
506 buffer().popIncludedBuffer();
510 buffer().popIncludedBuffer();
511 if (!child->errorList("Parse").empty()) {
512 // FIXME: Do something.
515 // The file was already loaded, so, simply
516 // inform parent buffer about local macros.
517 Buffer const * parent = &buffer();
518 child->setParent(parent);
520 child->listMacroNames(macros);
521 MacroNameSet::const_iterator cit = macros.begin();
522 MacroNameSet::const_iterator end = macros.end();
523 for (; cit != end; ++cit)
524 parent->usermacros.insert(*cit);
527 // Cache the child buffer.
528 child_buffer_ = child;
533 bool InsetInclude::checkForRecursiveInclude(
534 Buffer const * cbuf, bool silent) const
536 if (recursion_error_)
539 if (!buffer().isBufferIncluded(cbuf))
543 docstring const msg = _("The file\n%1$s\n has attempted to include itself.\n"
544 "The document set will not work properly until this is fixed!");
545 frontend::Alert::warning(_("Recursive Include"),
546 bformat(msg, from_utf8(cbuf->fileName().absFileName())));
548 recursion_error_ = true;
553 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
555 string incfile = ltrim(to_utf8(params()["filename"]));
557 // Warn if no file name has been specified
558 if (incfile.empty()) {
559 frontend::Alert::warning(_("No file name specified"),
560 _("An included file name is empty.\n"
561 "Ignoring Inclusion"),
565 // Warn if file doesn't exist
566 if (!includedFileExist()) {
567 frontend::Alert::warning(_("Included file not found"),
568 bformat(_("The included file\n"
570 "has not been found. LyX will ignore the inclusion."),
576 FileName const included_file = includedFileName(buffer(), params());
577 Buffer const * const masterBuffer = buffer().masterBuffer();
579 // if incfile is relative, make it relative to the master
581 if (!FileName::isAbsolute(incfile)) {
583 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
584 from_utf8(masterBuffer->filePath())));
587 string exppath = incfile;
588 if (!runparams.export_folder.empty()) {
589 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
592 // write it to a file (so far the complete file)
596 if (type(params()) == LISTINGS) {
597 exportfile = exppath;
598 mangled = DocFileName(included_file).mangledFileName();
600 exportfile = changeExtension(exppath, ".tex");
601 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
607 else if (!runparams.silent)
608 ; // no warning wanted
609 else if (!isValidLaTeXFileName(incfile)) {
610 frontend::Alert::warning(_("Invalid filename"),
611 _("The following filename will cause troubles "
612 "when running the exported file through LaTeX: ") +
614 } else if (!isValidDVIFileName(incfile)) {
615 frontend::Alert::warning(_("Problematic filename for DVI"),
616 _("The following filename can cause troubles "
617 "when running the exported file through LaTeX "
618 "and opening the resulting DVI: ") +
619 from_utf8(incfile), true);
622 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
623 buffer().temppath() : masterBuffer->temppath()));
625 LYXERR(Debug::LATEX, "incfile:" << incfile);
626 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
627 LYXERR(Debug::LATEX, "writefile:" << writefile);
629 string const tex_format = flavor2format(runparams.flavor);
631 switch (type(params())) {
634 incfile = latex_path(incfile);
636 os << '\\' << from_ascii(params().getCmdName()) << '{'
637 << from_utf8(incfile) << '}';
641 runparams.exportdata->addExternalFile(tex_format, writefile,
644 // \input wants file with extension (default is .tex)
645 if (!isLyXFileName(included_file.absFileName())) {
646 incfile = latex_path(incfile);
648 os << '\\' << from_ascii(params().getCmdName())
649 << '{' << from_utf8(incfile) << '}';
651 incfile = changeExtension(incfile, ".tex");
652 incfile = latex_path(incfile);
654 os << '\\' << from_ascii(params().getCmdName())
655 << '{' << from_utf8(incfile) << '}';
660 // Here, listings and minted have sligthly different behaviors.
661 // Using listings, it is always possible to have a caption,
662 // even for non-floats. Using minted, only floats can have a
663 // caption. So, with minted we use the following strategy.
664 // If a caption was specified but the float parameter was not,
665 // we ourselves add a caption above the listing (because the
666 // listing comes from a file and might span several pages).
667 // Otherwise, if float was specified, the floating listing
668 // environment provided by minted is used. In either case, the
669 // label parameter is taken as the label by which the float
670 // can be referenced, otherwise it will have the meaning
671 // intended by minted. In this last case, the label will
672 // serve as a sort of caption that, however, will be shown
673 // by minted only if the frame parameter is also specified.
674 bool const use_minted = buffer().params().use_minted;
675 runparams.exportdata->addExternalFile(tex_format, writefile,
677 string const opt = to_utf8(params()["lstparams"]);
678 // opt is set in QInclude dialog and should have passed validation.
679 InsetListingsParams lstparams(opt);
680 docstring parameters = from_utf8(lstparams.params());
685 bool isfloat = lstparams.isFloat();
686 // We are going to split parameters at commas, so
687 // replace commas that are not parameter separators
688 // with a code point from the private use area
689 char_type comma = replaceCommaInBraces(parameters);
690 // Get float placement, language, caption, and
691 // label, then remove the relative options if minted.
692 vector<docstring> opts =
693 getVectorFromString(parameters, from_ascii(","), false);
694 vector<docstring> latexed_opts;
695 for (size_t i = 0; i < opts.size(); ++i) {
696 // Restore replaced commas
697 opts[i] = subst(opts[i], comma, ',');
698 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
699 if (prefixIs(opts[i], from_ascii("float=")))
700 placement = opts[i].substr(6);
701 opts.erase(opts.begin() + i--);
702 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
703 language = opts[i].substr(9);
704 opts.erase(opts.begin() + i--);
705 } else if (prefixIs(opts[i], from_ascii("caption="))) {
706 caption = params().prepareCommand(runparams, trim(opts[i].substr(8), "{}"),
707 ParamInfo::HANDLING_LATEXIFY);
708 opts.erase(opts.begin() + i--);
710 latexed_opts.push_back(from_ascii("caption={") + caption + "}");
711 } else if (prefixIs(opts[i], from_ascii("label="))) {
712 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
713 ParamInfo::HANDLING_ESCAPE);
714 opts.erase(opts.begin() + i--);
716 latexed_opts.push_back(from_ascii("label={") + label + "}");
718 if (use_minted && !label.empty()) {
719 if (isfloat || !caption.empty())
720 label = trim(label, "{}");
722 opts.push_back(from_ascii("label=") + label);
725 if (!latexed_opts.empty())
726 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
727 parameters = getStringFromVector(opts, from_ascii(","));
728 if (language.empty())
729 language = from_ascii("TeX");
730 if (use_minted && isfloat) {
731 os << breakln << "\\begin{listing}";
732 if (!placement.empty())
733 os << '[' << placement << "]";
735 } else if (use_minted && !caption.empty()) {
736 os << breakln << "\\lyxmintcaption[t]{" << caption;
738 os << "\\label{" << label << "}";
741 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
742 if (!parameters.empty())
743 os << "[" << parameters << "]";
745 os << '{' << ascii_lowercase(language) << '}';
746 os << '{' << incfile << '}';
747 if (use_minted && isfloat) {
748 if (!caption.empty())
749 os << breakln << "\\caption{" << caption << "}";
751 os << breakln << "\\label{" << label << "}";
752 os << breakln << "\\end{listing}\n";
757 runparams.exportdata->addExternalFile(tex_format, writefile,
760 // \include don't want extension and demands that the
761 // file really have .tex
762 incfile = changeExtension(incfile, string());
763 incfile = latex_path(incfile);
765 os << '\\' << from_ascii(params().getCmdName()) << '{'
766 << from_utf8(incfile) << '}';
773 if (runparams.inComment || runparams.dryrun)
774 // Don't try to load or copy the file if we're
775 // in a comment or doing a dryrun
778 if (!isInputOrInclude(params()) ||
779 !isLyXFileName(included_file.absFileName())) {
780 // In this case, it's not a LyX file, so we copy the file
781 // to the temp dir, so that .aux files etc. are not created
782 // in the original dir. Files included by this file will be
783 // found via either the environment variable TEXINPUTS, or
784 // input@path, see ../Buffer.cpp.
785 unsigned long const checksum_in = included_file.checksum();
786 unsigned long const checksum_out = writefile.checksum();
787 if (checksum_in != checksum_out) {
788 if (!included_file.copyTo(writefile)) {
791 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
792 "into the temporary directory."),
793 from_utf8(included_file.absFileName()))));
800 // it's a LyX file and we're inputting or including, so
801 // try to load it so we can write the associated latex
802 Buffer * tmp = loadIfNeeded();
804 if (!runparams.silent) {
805 docstring text = bformat(_("Could not load included "
807 "Please, check whether it actually exists."),
808 included_file.displayName());
809 throw ExceptionMessage(ErrorException, _("Error: "),
815 if (recursion_error_)
818 if (!runparams.silent) {
819 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
821 docstring text = bformat(_("Included file `%1$s'\n"
822 "has textclass `%2$s'\n"
823 "while parent file has textclass `%3$s'."),
824 included_file.displayName(),
825 from_utf8(tmp->params().documentClass().name()),
826 from_utf8(masterBuffer->params().documentClass().name()));
827 Alert::warning(_("Different textclasses"), text, true);
830 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
831 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
832 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
833 docstring text = bformat(_("Included file `%1$s'\n"
834 "has use-non-TeX-fonts set to `%2$s'\n"
835 "while parent file has use-non-TeX-fonts set to `%3$s'."),
836 included_file.displayName(),
838 from_utf8(master_tf));
839 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
841 else if (tmp->params().inputenc != masterBuffer->params().inputenc) {
842 docstring text = bformat(_("Included file `%1$s'\n"
843 "uses input encoding \"%2$s\" [%3$s]\n"
844 "while parent file uses input encoding \"%4$s\" [%5$s]."),
845 included_file.displayName(),
846 _(tmp->params().inputenc),
847 from_utf8(tmp->params().encoding().guiName()),
848 _(masterBuffer->params().inputenc),
849 from_utf8(masterBuffer->params().encoding().guiName()));
850 Alert::warning(_("Different LaTeX input encodings"), text, true);
853 // Make sure modules used in child are all included in master
854 // FIXME It might be worth loading the children's modules into the master
855 // over in BufferParams rather than doing this check.
856 LayoutModuleList const masterModules = masterBuffer->params().getModules();
857 LayoutModuleList const childModules = tmp->params().getModules();
858 LayoutModuleList::const_iterator it = childModules.begin();
859 LayoutModuleList::const_iterator end = childModules.end();
860 for (; it != end; ++it) {
861 string const module = *it;
862 LayoutModuleList::const_iterator found =
863 find(masterModules.begin(), masterModules.end(), module);
864 if (found == masterModules.end()) {
865 docstring text = bformat(_("Included file `%1$s'\n"
866 "uses module `%2$s'\n"
867 "which is not used in parent file."),
868 included_file.displayName(), from_utf8(module));
869 Alert::warning(_("Module not found"), text, true);
874 tmp->markDepClean(masterBuffer->temppath());
876 // Don't assume the child's format is latex
877 string const inc_format = tmp->params().bufferFormat();
878 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
879 theFormats().extension(inc_format)));
881 // FIXME: handle non existing files
882 // The included file might be written in a different encoding
884 Encoding const * const oldEnc = runparams.encoding;
885 Language const * const oldLang = runparams.master_language;
886 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
887 // the children must be encoded in plain utf8!
888 if (masterBuffer->params().useNonTeXFonts)
889 runparams.encoding = encodings.fromLyXName("utf8-plain");
891 runparams.encoding = oldEnc;
892 else runparams.encoding = &tmp->params().encoding();
893 runparams.master_language = buffer().params().language;
894 runparams.par_begin = 0;
895 runparams.par_end = tmp->paragraphs().size();
896 runparams.is_child = true;
897 Buffer::ExportStatus retval =
898 tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
899 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
900 if (retval == Buffer::ExportKilled && buffer().isClone() &&
901 buffer().isExporting()) {
902 // We really shouldn't get here, I don't think.
903 LYXERR0("No conversion exception?");
904 throw ConversionException();
906 else if (retval != Buffer::ExportSuccess) {
907 if (!runparams.silent) {
908 docstring msg = bformat(_("Included file `%1$s' "
909 "was not exported correctly.\n "
910 "LaTeX export is probably incomplete."),
911 included_file.displayName());
912 ErrorList const & el = tmp->errorList("Export");
914 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
915 msg, el.begin()->error, el.begin()->description);
916 throw ExceptionMessage(ErrorException, _("Error: "), msg);
919 runparams.encoding = oldEnc;
920 runparams.master_language = oldLang;
921 runparams.is_child = false;
923 // If needed, use converters to produce a latex file from the child
924 if (tmpwritefile != writefile) {
926 Converters::RetVal const conv_retval =
927 theConverters().convert(tmp, tmpwritefile, writefile,
928 included_file, inc_format, tex_format, el);
929 if (conv_retval == Converters::KILLED && buffer().isClone() &&
930 buffer().isExporting()) {
931 // We really shouldn't get here, I don't think.
932 LYXERR0("No conversion exception?");
933 throw ConversionException();
934 } else if (conv_retval != Converters::SUCCESS && !runparams.silent) {
935 docstring msg = bformat(_("Included file `%1$s' "
936 "was not exported correctly.\n "
937 "LaTeX export is probably incomplete."),
938 included_file.displayName());
940 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
941 msg, el.begin()->error, el.begin()->description);
942 throw ExceptionMessage(ErrorException, _("Error: "), msg);
948 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
953 // For verbatim and listings, we just include the contents of the file as-is.
954 // In the case of listings, we wrap it in <pre>.
955 bool const listing = isListings(params());
956 if (listing || isVerbatim(params())) {
958 xs << html::StartTag("pre");
959 // FIXME: We don't know the encoding of the file, default to UTF-8.
960 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
962 xs << html::EndTag("pre");
966 // We don't (yet) know how to Input or Include non-LyX files.
967 // (If we wanted to get really arcane, we could run some tex2html
968 // converter on the included file. But that's just masochistic.)
969 FileName const included_file = includedFileName(buffer(), params());
970 if (!isLyXFileName(included_file.absFileName())) {
972 frontend::Alert::warning(_("Unsupported Inclusion"),
973 bformat(_("LyX does not know how to include non-LyX files when "
974 "generating HTML output. Offending file:\n%1$s"),
975 ltrim(params()["filename"])));
979 // In the other cases, we will generate the HTML and include it.
981 Buffer const * const ibuf = loadIfNeeded();
985 if (recursion_error_)
988 // are we generating only some paragraphs, or all of them?
989 bool const all_pars = !rp.dryrun ||
990 (rp.par_begin == 0 &&
991 rp.par_end == (int)buffer().text().paragraphs().size());
993 OutputParams op = rp;
997 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
999 xs << XHTMLStream::ESCAPE_NONE
1000 << "<!-- Included file: "
1001 << from_utf8(included_file.absFileName())
1002 << XHTMLStream::ESCAPE_NONE
1009 int InsetInclude::plaintext(odocstringstream & os,
1010 OutputParams const & op, size_t) const
1012 // just write the filename if we're making a tooltip or toc entry,
1013 // or are generating this for advanced search
1014 if (op.for_tooltip || op.for_toc || op.for_search) {
1015 os << '[' << screenLabel() << '\n'
1016 << ltrim(getParam("filename")) << "\n]";
1017 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1020 if (isVerbatim(params()) || isListings(params())) {
1021 if (op.for_search) {
1022 os << '[' << screenLabel() << ']';
1025 os << '[' << screenLabel() << '\n'
1026 // FIXME: We don't know the encoding of the file, default to UTF-8.
1027 << includedFileName(buffer(), params()).fileContents("UTF-8")
1030 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1033 Buffer const * const ibuf = loadIfNeeded();
1035 docstring const str = '[' + screenLabel() + ']';
1040 if (recursion_error_)
1043 writePlaintextFile(*ibuf, os, op);
1048 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
1050 string incfile = ltrim(to_utf8(params()["filename"]));
1052 // Do nothing if no file name has been specified
1053 if (incfile.empty())
1056 string const included_file = includedFileName(buffer(), params()).absFileName();
1057 string exppath = incfile;
1058 if (!runparams.export_folder.empty()) {
1059 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
1060 FileName(exppath).onlyPath().createPath();
1063 // write it to a file (so far the complete file)
1064 string const exportfile = changeExtension(exppath, ".sgml");
1065 DocFileName writefile(changeExtension(included_file, ".sgml"));
1067 Buffer * tmp = loadIfNeeded();
1069 if (recursion_error_)
1072 string const mangled = writefile.mangledFileName();
1073 writefile = makeAbsPath(mangled,
1074 buffer().masterBuffer()->temppath());
1075 if (!runparams.nice)
1078 LYXERR(Debug::LATEX, "incfile:" << incfile);
1079 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
1080 LYXERR(Debug::LATEX, "writefile:" << writefile);
1082 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
1085 runparams.exportdata->addExternalFile("docbook", writefile,
1087 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1090 if (isVerbatim(params()) || isListings(params())) {
1091 os << "<inlinegraphic fileref=\""
1092 << '&' << include_label << ';'
1093 << "\" format=\"linespecific\">";
1095 os << '&' << include_label << ';';
1101 void InsetInclude::validate(LaTeXFeatures & features) const
1103 LATTEST(&buffer() == &features.buffer());
1105 string incfile = ltrim(to_utf8(params()["filename"]));
1106 string const included_file =
1107 includedFileName(buffer(), params()).absFileName();
1110 if (isLyXFileName(included_file))
1111 writefile = changeExtension(included_file, ".sgml");
1113 writefile = included_file;
1115 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1116 incfile = DocFileName(writefile).mangledFileName();
1117 writefile = makeAbsPath(incfile,
1118 buffer().masterBuffer()->temppath()).absFileName();
1121 features.includeFile(include_label, writefile);
1123 features.useInsetLayout(getLayout());
1124 if (isVerbatim(params()))
1125 features.require("verbatim");
1126 else if (isListings(params())) {
1127 if (buffer().params().use_minted) {
1128 features.require("minted");
1129 string const opts = to_utf8(params()["lstparams"]);
1130 InsetListingsParams lstpars(opts);
1131 if (!lstpars.isFloat() && contains(opts, "caption="))
1132 features.require("lyxmintcaption");
1134 features.require("listings");
1137 // Here we must do the fun stuff...
1138 // Load the file in the include if it needs
1140 Buffer * const tmp = loadIfNeeded();
1144 // the file is loaded
1145 if (checkForRecursiveInclude(tmp))
1147 buffer().pushIncludedBuffer(tmp);
1149 // We must temporarily change features.buffer,
1150 // otherwise it would always be the master buffer,
1151 // and nested includes would not work.
1152 features.setBuffer(*tmp);
1153 // Maybe this is already a child
1154 bool const is_child =
1155 features.runparams().is_child;
1156 features.runparams().is_child = true;
1157 tmp->validate(features);
1158 features.runparams().is_child = is_child;
1159 features.setBuffer(buffer());
1161 buffer().popIncludedBuffer();
1165 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1167 Buffer * ibuf = loadIfNeeded();
1171 if (checkForRecursiveInclude(ibuf))
1173 buffer().pushIncludedBuffer(ibuf);
1174 ibuf->collectBibKeys(checkedFiles);
1175 buffer().popIncludedBuffer();
1179 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1181 LBUFERR(mi.base.bv);
1183 bool use_preview = false;
1184 if (RenderPreview::previewText()) {
1185 graphics::PreviewImage const * pimage =
1186 preview_->getPreviewImage(mi.base.bv->buffer());
1187 use_preview = pimage && pimage->image();
1191 preview_->metrics(mi, dim);
1195 button_.update(screenLabel(), true, false, !file_exist_ || recursion_error_);
1197 button_.metrics(mi, dim);
1200 Box b(0, dim.wid, -dim.asc, dim.des);
1205 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1207 LBUFERR(pi.base.bv);
1209 bool use_preview = false;
1210 if (RenderPreview::previewText()) {
1211 graphics::PreviewImage const * pimage =
1212 preview_->getPreviewImage(pi.base.bv->buffer());
1213 use_preview = pimage && pimage->image();
1217 preview_->draw(pi, x, y);
1219 button_.draw(pi, x, y);
1223 void InsetInclude::write(ostream & os) const
1225 params().Write(os, &buffer());
1229 string InsetInclude::contextMenuName() const
1231 return "context-include";
1235 Inset::DisplayType InsetInclude::display() const
1237 return type(params()) == INPUT ? Inline : AlignCenter;
1241 docstring InsetInclude::layoutName() const
1243 if (isListings(params()))
1244 return from_ascii("IncludeListings");
1245 return InsetCommand::layoutName();
1253 void InsetInclude::fileChanged() const
1255 Buffer const * const buffer = updateFrontend();
1259 preview_->removePreview(*buffer);
1260 add_preview(*preview_, *this, *buffer);
1261 preview_->startLoading(*buffer);
1267 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1269 FileName const included_file = includedFileName(buffer, params);
1271 return type(params) == INPUT && params.preview() &&
1272 included_file.isReadableFile();
1276 docstring latexString(InsetInclude const & inset)
1278 odocstringstream ods;
1280 // We don't need to set runparams.encoding since this will be done
1281 // by latex() anyway.
1282 OutputParams runparams(nullptr);
1283 runparams.flavor = OutputParams::LATEX;
1284 runparams.for_preview = true;
1285 inset.latex(os, runparams);
1291 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1292 Buffer const & buffer)
1294 InsetCommandParams const & params = inset.params();
1295 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1296 renderer.setAbsFile(includedFileName(buffer, params));
1297 docstring const snippet = latexString(inset);
1298 renderer.addPreview(snippet, buffer);
1305 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1306 graphics::PreviewLoader & ploader) const
1308 Buffer const & buffer = ploader.buffer();
1309 if (!preview_wanted(params(), buffer))
1311 preview_->setAbsFile(includedFileName(buffer, params()));
1312 docstring const snippet = latexString(*this);
1313 preview_->addPreview(snippet, ploader);
1317 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1318 UpdateType utype, TocBackend & backend) const
1320 if (isListings(params())) {
1322 label_->addToToc(cpit, output_active, utype, backend);
1323 TocBuilder & b = backend.builder("listing");
1324 b.pushItem(cpit, screenLabel(), output_active);
1325 InsetListingsParams p(to_utf8(params()["lstparams"]));
1326 b.argumentItem(from_utf8(p.getParamValue("caption")));
1328 } else if (isVerbatim(params())) {
1329 TocBuilder & b = backend.builder("child");
1330 b.pushItem(cpit, screenLabel(), output_active);
1333 Buffer const * const childbuffer = getChildBuffer();
1335 TocBuilder & b = backend.builder("child");
1336 docstring str = childbuffer ? childbuffer->fileName().displayName()
1338 b.pushItem(cpit, str, output_active);
1344 if (checkForRecursiveInclude(childbuffer))
1346 buffer().pushIncludedBuffer(childbuffer);
1347 // Update the child's tocBackend. The outliner uses the master's, but
1348 // the navigation menu uses the child's.
1349 childbuffer->tocBackend().update(output_active, utype);
1350 // Include Tocs from children
1351 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1353 buffer().popIncludedBuffer();
1354 // Copy missing outliner names (though the user has been warned against
1355 // having different document class and module selection between master
1357 for (auto const & name
1358 : childbuffer->params().documentClass().outlinerNames())
1359 backend.addName(name.first, translateIfPossible(name.second));
1364 void InsetInclude::updateCommand()
1369 docstring old_label = label_->getParam("name");
1370 label_->updateLabel(old_label);
1371 // the label might have been adapted (duplicate)
1372 docstring new_label = label_->getParam("name");
1373 if (old_label == new_label)
1376 // update listings parameters...
1377 InsetCommandParams p(INCLUDE_CODE);
1379 InsetListingsParams par(to_utf8(params()["lstparams"]));
1380 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1381 p["lstparams"] = from_utf8(par.params());
1386 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1388 file_exist_ = includedFileExist();
1389 Buffer const * const childbuffer = getChildBuffer();
1391 if (!checkForRecursiveInclude(childbuffer))
1392 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1393 button_.update(screenLabel(), true, false, recursion_error_);
1397 button_.update(screenLabel(), true, false, !file_exist_);
1399 if (!isListings(params()))
1403 label_->updateBuffer(it, utype, deleted);
1405 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1406 if (par.getParamValue("caption").empty()) {
1407 listings_label_ = buffer().B_("Program Listing");
1410 Buffer const & master = *buffer().masterBuffer();
1411 Counters & counters = master.params().documentClass().counters();
1412 docstring const cnt = from_ascii("listing");
1413 listings_label_ = master.B_("Program Listing");
1414 if (counters.hasCounter(cnt)) {
1415 counters.step(cnt, utype);
1416 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1421 bool InsetInclude::includedFileExist() const
1423 // check whether the included file exist
1424 string incFileName = ltrim(to_utf8(params()["filename"]));
1426 support::makeAbsPath(incFileName,
1427 support::onlyPath(buffer().absFileName()));