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/mutex.h"
65 #include "support/ExceptionMessage.h"
68 using namespace lyx::support;
72 namespace Alert = frontend::Alert;
77 docstring const uniqueID()
79 static unsigned int seed = 1000;
81 Mutex::Locker lock(&mutex);
82 return "file" + convert<docstring>(++seed);
86 /// the type of inclusion
88 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
92 Types type(string const & s)
96 if (s == "verbatiminput")
98 if (s == "verbatiminput*")
100 if (s == "lstinputlisting" || s == "inputminted")
108 Types type(InsetCommandParams const & params)
110 return type(params.getCmdName());
114 bool isListings(InsetCommandParams const & params)
116 return type(params) == LISTINGS;
120 bool isVerbatim(InsetCommandParams const & params)
122 Types const t = type(params);
123 return t == VERB || t == VERBAST;
127 bool isInputOrInclude(InsetCommandParams const & params)
129 Types const t = type(params);
130 return t == INPUT || t == INCLUDE;
134 FileName const masterFileName(Buffer const & buffer)
136 return buffer.masterBuffer()->fileName();
140 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
143 string const parentFileName(Buffer const & buffer)
145 return buffer.absFileName();
149 FileName const includedFileName(Buffer const & buffer,
150 InsetCommandParams const & params)
152 return makeAbsPath(ltrim(to_utf8(params["filename"])),
153 onlyPath(parentFileName(buffer)));
157 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
159 if (label_str.empty())
161 InsetCommandParams icp(LABEL_CODE);
162 icp["name"] = label_str;
163 return new InsetLabel(buf, icp);
167 char_type replaceCommaInBraces(docstring & params)
169 // Code point from private use area
170 char_type private_char = 0xE000;
172 for (char_type & c : params) {
177 else if (c == ',' && count)
186 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
187 : InsetCommand(buf, p), include_label(uniqueID()),
188 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
189 set_label_(false), label_(nullptr), child_buffer_(nullptr), file_exist_(false),
190 recursion_error_(false)
192 preview_->connect([=](){ fileChanged(); });
194 if (isListings(params())) {
195 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
196 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
197 } else if (isInputOrInclude(params()) && buf)
202 InsetInclude::InsetInclude(InsetInclude const & other)
203 : InsetCommand(other), include_label(other.include_label),
204 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
205 set_label_(false), label_(nullptr), child_buffer_(nullptr),
206 file_exist_(other.file_exist_),recursion_error_(other.recursion_error_)
208 preview_->connect([=](){ fileChanged(); });
211 label_ = new InsetLabel(*other.label_);
215 InsetInclude::~InsetInclude()
221 void InsetInclude::setBuffer(Buffer & buffer)
223 InsetCommand::setBuffer(buffer);
225 label_->setBuffer(buffer);
229 void InsetInclude::setChildBuffer(Buffer * buffer)
231 child_buffer_ = buffer;
235 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
238 // This is only correct for the case of listings, but it'll do for now.
239 // In the other cases, this second parameter should just be empty.
240 static ParamInfo param_info_;
241 if (param_info_.empty()) {
242 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
243 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
244 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
250 bool InsetInclude::isCompatibleCommand(string const & s)
252 return type(s) != NONE;
256 bool InsetInclude::needsCProtection(bool const /*maintext*/, bool const fragile) const
258 // We need to \cprotect all types in fragile context
263 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
265 switch (cmd.action()) {
267 case LFUN_INSET_EDIT: {
268 editIncluded(ltrim(to_utf8(params()["filename"])));
272 case LFUN_INSET_MODIFY: {
273 // It should be OK just to invalidate the cache in setParams()
275 // child_buffer_ = 0;
276 InsetCommandParams p(INCLUDE_CODE);
277 if (cmd.getArg(0) == "changetype") {
279 InsetCommand::doDispatch(cur, cmd);
282 InsetCommand::string2params(to_utf8(cmd.argument()), p);
283 if (!p.getCmdName().empty()) {
285 InsetListingsParams new_params(to_utf8(p["lstparams"]));
286 docstring const new_label =
287 from_utf8(new_params.getParamValue("label"));
289 if (new_label.empty()) {
295 old_label = label_->getParam("name");
297 label_ = createLabel(buffer_, new_label);
298 label_->setBuffer(buffer());
301 if (new_label != old_label) {
302 label_->updateLabelAndRefs(new_label, &cur);
303 // the label might have been adapted (duplicate)
304 if (new_label != label_->getParam("name")) {
305 new_params.addParam("label", "{" +
306 to_utf8(label_->getParam("name")) + "}", true);
307 p["lstparams"] = from_utf8(new_params.params());
314 cur.forceBufferUpdate();
316 cur.noScreenUpdate();
320 case LFUN_MOUSE_RELEASE: {
321 if (cmd.modifier() == ControlModifier) {
322 FileName const incfile = includedFileName(buffer(), params());
323 string const & incname = incfile.absFileName();
324 editIncluded(incname);
330 //pass everything else up the chain
332 InsetCommand::doDispatch(cur, cmd);
338 void InsetInclude::editIncluded(string const & f)
340 if (isLyXFileName(f)) {
341 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, f);
344 // tex file or other text file in verbatim mode
345 theFormats().edit(buffer(),
346 support::makeAbsPath(f, support::onlyPath(buffer().absFileName())),
351 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
352 FuncStatus & flag) const
354 switch (cmd.action()) {
356 case LFUN_INSET_EDIT:
357 flag.setEnabled(true);
360 case LFUN_INSET_MODIFY:
361 if (cmd.getArg(0) == "changetype")
362 return InsetCommand::getStatus(cur, cmd, flag);
364 flag.setEnabled(true);
368 return InsetCommand::getStatus(cur, cmd, flag);
373 void InsetInclude::setParams(InsetCommandParams const & p)
375 // invalidate the cache
376 child_buffer_ = nullptr;
378 // reset in order to allow loading new file
379 failedtoload_ = false;
380 recursion_error_ = false;
382 InsetCommand::setParams(p);
385 if (preview_->monitoring())
386 preview_->stopMonitoring();
388 if (type(params()) == INPUT)
389 add_preview(*preview_, *this, buffer());
393 bool InsetInclude::isChildIncluded() const
395 std::list<std::string> includeonlys =
396 buffer().params().getIncludedChildren();
397 if (includeonlys.empty())
399 return (std::find(includeonlys.begin(),
401 ltrim(to_utf8(params()["filename"]))) != includeonlys.end());
405 docstring InsetInclude::screenLabel() const
407 docstring pre = file_exist_ ? docstring() : _("FILE MISSING:");
411 switch (type(params())) {
413 temp = buffer().B_("Input");
416 temp = buffer().B_("Verbatim");
419 temp = buffer().B_("Verbatim*");
422 if (isChildIncluded())
423 temp = buffer().B_("Include");
425 temp += buffer().B_("Include (excluded)");
428 temp = listings_label_;
431 LASSERT(false, temp = buffer().B_("Unknown"));
437 if (ltrim(params()["filename"]).empty())
440 temp += from_utf8(onlyFileName(ltrim(to_utf8(params()["filename"]))));
442 return pre.empty() ? temp : pre + from_ascii(" ") + temp;
446 Buffer * InsetInclude::loadIfNeeded() const
448 // This is for background export and preview. We don't even want to
449 // try to load the cloned child document again.
450 if (buffer().isClone())
451 return child_buffer_;
453 // Don't try to load it again if we failed before.
454 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
457 FileName const included_file = includedFileName(buffer(), params());
458 // Use cached Buffer if possible.
459 if (child_buffer_ != nullptr) {
460 if (theBufferList().isLoaded(child_buffer_)
461 // additional sanity check: make sure the Buffer really is
462 // associated with the file we want.
463 && child_buffer_ == theBufferList().getBuffer(included_file))
464 return child_buffer_;
465 // Buffer vanished, so invalidate cache and try to reload.
466 child_buffer_ = nullptr;
469 if (!isLyXFileName(included_file.absFileName()))
472 Buffer * child = theBufferList().getBuffer(included_file);
473 if (checkForRecursiveInclude(child))
477 // the readonly flag can/will be wrong, not anymore I think.
478 if (!included_file.exists()) {
479 failedtoload_ = true;
483 child = theBufferList().newBuffer(included_file.absFileName());
485 // Buffer creation is not possible.
488 buffer().pushIncludedBuffer(child);
489 // Set parent before loading, such that macros can be tracked
490 child->setParent(&buffer());
492 if (child->loadLyXFile() != Buffer::ReadSuccess) {
493 failedtoload_ = true;
494 child->setParent(nullptr);
495 //close the buffer we just opened
496 theBufferList().release(child);
497 buffer().popIncludedBuffer();
501 buffer().popIncludedBuffer();
502 if (!child->errorList("Parse").empty()) {
503 // FIXME: Do something.
506 // The file was already loaded, so, simply
507 // inform parent buffer about local macros.
508 Buffer const * parent = &buffer();
509 child->setParent(parent);
511 child->listMacroNames(macros);
512 MacroNameSet::const_iterator cit = macros.begin();
513 MacroNameSet::const_iterator end = macros.end();
514 for (; cit != end; ++cit)
515 parent->usermacros.insert(*cit);
518 // Cache the child buffer.
519 child_buffer_ = child;
524 bool InsetInclude::checkForRecursiveInclude(
525 Buffer const * cbuf, bool silent) const
527 if (recursion_error_)
530 if (!buffer().isBufferIncluded(cbuf))
534 docstring const msg = _("The file\n%1$s\n has attempted to include itself.\n"
535 "The document set will not work properly until this is fixed!");
536 frontend::Alert::warning(_("Recursive Include"),
537 bformat(msg, from_utf8(cbuf->fileName().absFileName())));
539 recursion_error_ = true;
544 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
546 string incfile = ltrim(to_utf8(params()["filename"]));
548 // Warn if no file name has been specified
549 if (incfile.empty()) {
550 frontend::Alert::warning(_("No file name specified"),
551 _("An included file name is empty.\n"
552 "Ignoring Inclusion"),
556 // Warn if file doesn't exist
557 if (!includedFileExist()) {
558 frontend::Alert::warning(_("Included file not found"),
559 bformat(_("The included file\n"
561 "has not been found. LyX will ignore the inclusion."),
567 FileName const included_file = includedFileName(buffer(), params());
568 Buffer const * const masterBuffer = buffer().masterBuffer();
570 // if incfile is relative, make it relative to the master
572 if (!FileName::isAbsolute(incfile)) {
574 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
575 from_utf8(masterBuffer->filePath())));
578 string exppath = incfile;
579 if (!runparams.export_folder.empty()) {
580 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
583 // write it to a file (so far the complete file)
587 if (type(params()) == LISTINGS) {
588 exportfile = exppath;
589 mangled = DocFileName(included_file).mangledFileName();
591 exportfile = changeExtension(exppath, ".tex");
592 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
598 else if (!runparams.silent)
599 ; // no warning wanted
600 else if (!isValidLaTeXFileName(incfile)) {
601 frontend::Alert::warning(_("Invalid filename"),
602 _("The following filename will cause troubles "
603 "when running the exported file through LaTeX: ") +
605 } else if (!isValidDVIFileName(incfile)) {
606 frontend::Alert::warning(_("Problematic filename for DVI"),
607 _("The following filename can cause troubles "
608 "when running the exported file through LaTeX "
609 "and opening the resulting DVI: ") +
610 from_utf8(incfile), true);
613 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
614 buffer().temppath() : masterBuffer->temppath()));
616 LYXERR(Debug::LATEX, "incfile:" << incfile);
617 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
618 LYXERR(Debug::LATEX, "writefile:" << writefile);
620 string const tex_format = flavor2format(runparams.flavor);
622 switch (type(params())) {
625 incfile = latex_path(incfile);
627 os << '\\' << from_ascii(params().getCmdName()) << '{'
628 << from_utf8(incfile) << '}';
632 runparams.exportdata->addExternalFile(tex_format, writefile,
635 // \input wants file with extension (default is .tex)
636 if (!isLyXFileName(included_file.absFileName())) {
637 incfile = latex_path(incfile);
639 os << '\\' << from_ascii(params().getCmdName())
640 << '{' << from_utf8(incfile) << '}';
642 incfile = changeExtension(incfile, ".tex");
643 incfile = latex_path(incfile);
645 os << '\\' << from_ascii(params().getCmdName())
646 << '{' << from_utf8(incfile) << '}';
651 // Here, listings and minted have slightly different behaviors.
652 // Using listings, it is always possible to have a caption,
653 // even for non-floats. Using minted, only floats can have a
654 // caption. So, with minted we use the following strategy.
655 // If a caption was specified but the float parameter was not,
656 // we ourselves add a caption above the listing (because the
657 // listing comes from a file and might span several pages).
658 // Otherwise, if float was specified, the floating listing
659 // environment provided by minted is used. In either case, the
660 // label parameter is taken as the label by which the float
661 // can be referenced, otherwise it will have the meaning
662 // intended by minted. In this last case, the label will
663 // serve as a sort of caption that, however, will be shown
664 // by minted only if the frame parameter is also specified.
665 bool const use_minted = buffer().params().use_minted;
666 runparams.exportdata->addExternalFile(tex_format, writefile,
668 string const opt = to_utf8(params()["lstparams"]);
669 // opt is set in QInclude dialog and should have passed validation.
670 InsetListingsParams lstparams(opt);
671 docstring parameters = from_utf8(lstparams.params());
676 bool isfloat = lstparams.isFloat();
677 // We are going to split parameters at commas, so
678 // replace commas that are not parameter separators
679 // with a code point from the private use area
680 char_type comma = replaceCommaInBraces(parameters);
681 // Get float placement, language, caption, and
682 // label, then remove the relative options if minted.
683 vector<docstring> opts =
684 getVectorFromString(parameters, from_ascii(","), false);
685 vector<docstring> latexed_opts;
686 for (size_t i = 0; i < opts.size(); ++i) {
687 // Restore replaced commas
688 opts[i] = subst(opts[i], comma, ',');
689 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
690 if (prefixIs(opts[i], from_ascii("float=")))
691 placement = opts[i].substr(6);
692 opts.erase(opts.begin() + i--);
693 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
694 language = opts[i].substr(9);
695 opts.erase(opts.begin() + i--);
696 } else if (prefixIs(opts[i], from_ascii("caption="))) {
697 caption = params().prepareCommand(runparams, trim(opts[i].substr(8), "{}"),
698 ParamInfo::HANDLING_LATEXIFY);
699 opts.erase(opts.begin() + i--);
701 latexed_opts.push_back(from_ascii("caption={") + caption + "}");
702 } else if (prefixIs(opts[i], from_ascii("label="))) {
703 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
704 ParamInfo::HANDLING_ESCAPE);
705 opts.erase(opts.begin() + i--);
707 latexed_opts.push_back(from_ascii("label={") + label + "}");
709 if (use_minted && !label.empty()) {
710 if (isfloat || !caption.empty())
711 label = trim(label, "{}");
713 opts.push_back(from_ascii("label=") + label);
716 if (!latexed_opts.empty())
717 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
718 parameters = getStringFromVector(opts, from_ascii(","));
719 if (language.empty())
720 language = from_ascii("TeX");
721 if (use_minted && isfloat) {
722 os << breakln << "\\begin{listing}";
723 if (!placement.empty())
724 os << '[' << placement << "]";
726 } else if (use_minted && !caption.empty()) {
727 os << breakln << "\\lyxmintcaption[t]{" << caption;
729 os << "\\label{" << label << "}";
732 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
733 if (!parameters.empty())
734 os << "[" << parameters << "]";
736 os << '{' << ascii_lowercase(language) << '}';
737 os << '{' << incfile << '}';
738 if (use_minted && isfloat) {
739 if (!caption.empty())
740 os << breakln << "\\caption{" << caption << "}";
742 os << breakln << "\\label{" << label << "}";
743 os << breakln << "\\end{listing}\n";
748 runparams.exportdata->addExternalFile(tex_format, writefile,
751 // \include don't want extension and demands that the
752 // file really have .tex
753 incfile = changeExtension(incfile, string());
754 incfile = latex_path(incfile);
756 os << '\\' << from_ascii(params().getCmdName()) << '{'
757 << from_utf8(incfile) << '}';
764 if (runparams.inComment || runparams.dryrun)
765 // Don't try to load or copy the file if we're
766 // in a comment or doing a dryrun
769 if (!isInputOrInclude(params()) ||
770 !isLyXFileName(included_file.absFileName())) {
771 // In this case, it's not a LyX file, so we copy the file
772 // to the temp dir, so that .aux files etc. are not created
773 // in the original dir. Files included by this file will be
774 // found via either the environment variable TEXINPUTS, or
775 // input@path, see ../Buffer.cpp.
776 unsigned long const checksum_in = included_file.checksum();
777 unsigned long const checksum_out = writefile.checksum();
778 if (checksum_in != checksum_out) {
779 if (!included_file.copyTo(writefile)) {
782 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
783 "into the temporary directory."),
784 from_utf8(included_file.absFileName()))));
791 // it's a LyX file and we're inputting or including, so
792 // try to load it so we can write the associated latex
793 Buffer * tmp = loadIfNeeded();
795 if (!runparams.silent) {
796 docstring text = bformat(_("Could not load included "
798 "Please, check whether it actually exists."),
799 included_file.displayName());
800 throw ExceptionMessage(ErrorException, _("Error: "),
806 if (recursion_error_)
809 if (!runparams.silent) {
810 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
812 docstring text = bformat(_("Included file `%1$s'\n"
813 "has textclass `%2$s'\n"
814 "while parent file has textclass `%3$s'."),
815 included_file.displayName(),
816 from_utf8(tmp->params().documentClass().name()),
817 from_utf8(masterBuffer->params().documentClass().name()));
818 Alert::warning(_("Different textclasses"), text, true);
821 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
822 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
823 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
824 docstring text = bformat(_("Included file `%1$s'\n"
825 "has use-non-TeX-fonts set to `%2$s'\n"
826 "while parent file has use-non-TeX-fonts set to `%3$s'."),
827 included_file.displayName(),
829 from_utf8(master_tf));
830 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
832 else if (tmp->params().inputenc != masterBuffer->params().inputenc) {
833 docstring text = bformat(_("Included file `%1$s'\n"
834 "uses input encoding \"%2$s\" [%3$s]\n"
835 "while parent file uses input encoding \"%4$s\" [%5$s]."),
836 included_file.displayName(),
837 _(tmp->params().inputenc),
838 from_utf8(tmp->params().encoding().guiName()),
839 _(masterBuffer->params().inputenc),
840 from_utf8(masterBuffer->params().encoding().guiName()));
841 Alert::warning(_("Different LaTeX input encodings"), text, true);
844 // Make sure modules used in child are all included in master
845 // FIXME It might be worth loading the children's modules into the master
846 // over in BufferParams rather than doing this check.
847 LayoutModuleList const masterModules = masterBuffer->params().getModules();
848 LayoutModuleList const childModules = tmp->params().getModules();
849 LayoutModuleList::const_iterator it = childModules.begin();
850 LayoutModuleList::const_iterator end = childModules.end();
851 for (; it != end; ++it) {
852 string const module = *it;
853 LayoutModuleList::const_iterator found =
854 find(masterModules.begin(), masterModules.end(), module);
855 if (found == masterModules.end()) {
856 docstring text = bformat(_("Included file `%1$s'\n"
857 "uses module `%2$s'\n"
858 "which is not used in parent file."),
859 included_file.displayName(), from_utf8(module));
860 Alert::warning(_("Module not found"), text, true);
865 tmp->markDepClean(masterBuffer->temppath());
867 // Don't assume the child's format is latex
868 string const inc_format = tmp->params().bufferFormat();
869 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
870 theFormats().extension(inc_format)));
872 // FIXME: handle non existing files
873 // The included file might be written in a different encoding
875 Encoding const * const oldEnc = runparams.encoding;
876 Language const * const oldLang = runparams.master_language;
877 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
878 // the children must be encoded in plain utf8!
879 if (masterBuffer->params().useNonTeXFonts)
880 runparams.encoding = encodings.fromLyXName("utf8-plain");
882 runparams.encoding = oldEnc;
883 else runparams.encoding = &tmp->params().encoding();
884 runparams.master_language = buffer().params().language;
885 runparams.par_begin = 0;
886 runparams.par_end = tmp->paragraphs().size();
887 runparams.is_child = true;
888 Buffer::ExportStatus retval =
889 tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
890 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
891 if (retval == Buffer::ExportKilled && buffer().isClone() &&
892 buffer().isExporting()) {
893 // We really shouldn't get here, I don't think.
894 LYXERR0("No conversion exception?");
895 throw ConversionException();
897 else if (retval != Buffer::ExportSuccess) {
898 if (!runparams.silent) {
899 docstring msg = bformat(_("Included file `%1$s' "
900 "was not exported correctly.\n "
901 "LaTeX export is probably incomplete."),
902 included_file.displayName());
903 ErrorList const & el = tmp->errorList("Export");
905 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
906 msg, el.begin()->error, el.begin()->description);
907 throw ExceptionMessage(ErrorException, _("Error: "), msg);
910 runparams.encoding = oldEnc;
911 runparams.master_language = oldLang;
912 runparams.is_child = false;
914 // If needed, use converters to produce a latex file from the child
915 if (tmpwritefile != writefile) {
917 Converters::RetVal const conv_retval =
918 theConverters().convert(tmp, tmpwritefile, writefile,
919 included_file, inc_format, tex_format, el);
920 if (conv_retval == Converters::KILLED && buffer().isClone() &&
921 buffer().isExporting()) {
922 // We really shouldn't get here, I don't think.
923 LYXERR0("No conversion exception?");
924 throw ConversionException();
925 } else if (conv_retval != Converters::SUCCESS && !runparams.silent) {
926 docstring msg = bformat(_("Included file `%1$s' "
927 "was not exported correctly.\n "
928 "LaTeX export is probably incomplete."),
929 included_file.displayName());
931 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
932 msg, el.begin()->error, el.begin()->description);
933 throw ExceptionMessage(ErrorException, _("Error: "), msg);
939 docstring InsetInclude::xhtml(XMLStream & xs, OutputParams const & rp) const
944 // For verbatim and listings, we just include the contents of the file as-is.
945 // In the case of listings, we wrap it in <pre>.
946 bool const listing = isListings(params());
947 if (listing || isVerbatim(params())) {
949 xs << xml::StartTag("pre");
950 // FIXME: We don't know the encoding of the file, default to UTF-8.
951 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
953 xs << xml::EndTag("pre");
957 // We don't (yet) know how to Input or Include non-LyX files.
958 // (If we wanted to get really arcane, we could run some tex2html
959 // converter on the included file. But that's just masochistic.)
960 FileName const included_file = includedFileName(buffer(), params());
961 if (!isLyXFileName(included_file.absFileName())) {
963 frontend::Alert::warning(_("Unsupported Inclusion"),
964 bformat(_("LyX does not know how to include non-LyX files when "
965 "generating HTML output. Offending file:\n%1$s"),
966 ltrim(params()["filename"])));
970 // In the other cases, we will generate the HTML and include it.
972 Buffer const * const ibuf = loadIfNeeded();
976 if (recursion_error_)
979 // are we generating only some paragraphs, or all of them?
980 bool const all_pars = !rp.dryrun ||
981 (rp.par_begin == 0 &&
982 rp.par_end == (int)buffer().text().paragraphs().size());
984 OutputParams op = rp;
988 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
990 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
991 xs << from_utf8(included_file.absFileName());
992 xs << XMLStream::ESCAPE_NONE << " -->";
999 int InsetInclude::plaintext(odocstringstream & os,
1000 OutputParams const & op, size_t) const
1002 // just write the filename if we're making a tooltip or toc entry,
1003 // or are generating this for advanced search
1004 if (op.for_tooltip || op.for_toc || op.for_search) {
1005 os << '[' << screenLabel() << '\n'
1006 << ltrim(getParam("filename")) << "\n]";
1007 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1010 if (isVerbatim(params()) || isListings(params())) {
1011 if (op.for_search) {
1012 os << '[' << screenLabel() << ']';
1015 os << '[' << screenLabel() << '\n'
1016 // FIXME: We don't know the encoding of the file, default to UTF-8.
1017 << includedFileName(buffer(), params()).fileContents("UTF-8")
1020 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1023 Buffer const * const ibuf = loadIfNeeded();
1025 docstring const str = '[' + screenLabel() + ']';
1030 if (recursion_error_)
1033 writePlaintextFile(*ibuf, os, op);
1038 void InsetInclude::docbook(XMLStream & xs, OutputParams const & rp) const
1043 // For verbatim and listings, we just include the contents of the file as-is.
1044 bool const verbatim = isVerbatim(params());
1045 bool const listing = isListings(params());
1046 if (listing || verbatim) {
1048 xs << xml::StartTag("programlisting");
1050 xs << xml::StartTag("literallayout");
1052 // FIXME: We don't know the encoding of the file, default to UTF-8.
1053 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
1056 xs << xml::EndTag("programlisting");
1058 xs << xml::EndTag("literallayout");
1063 // We don't know how to input or include non-LyX files. Input it as a comment.
1064 FileName const included_file = includedFileName(buffer(), params());
1065 if (!isLyXFileName(included_file.absFileName())) {
1067 frontend::Alert::warning(_("Unsupported Inclusion"),
1068 bformat(_("LyX does not know how to process included non-LyX files when "
1069 "generating DocBook output. The content of the file will be output as a "
1070 "comment. Offending file:\n%1$s"),
1071 ltrim(params()["filename"])));
1073 // Read the file, output it wrapped into comments.
1074 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
1075 xs << from_utf8(included_file.absFileName());
1076 xs << XMLStream::ESCAPE_NONE << " -->";
1078 xs << XMLStream::ESCAPE_NONE << "<!-- ";
1079 xs << included_file.fileContents("UTF-8");
1080 xs << XMLStream::ESCAPE_NONE << " -->";
1082 xs << XMLStream::ESCAPE_NONE << "<!-- End of included file: ";
1083 xs << from_utf8(included_file.absFileName());
1084 xs << XMLStream::ESCAPE_NONE << " -->";
1087 // In the other cases, we generate the DocBook version and include it.
1088 Buffer const * const ibuf = loadIfNeeded();
1092 if (recursion_error_)
1095 // are we generating only some paragraphs, or all of them?
1096 bool const all_pars = !rp.dryrun ||
1097 (rp.par_begin == 0 &&
1098 rp.par_end == (int) buffer().text().paragraphs().size());
1100 OutputParams op = rp;
1104 op.inInclude = true;
1105 op.docbook_in_par = false;
1106 ibuf->writeDocBookSource(xs.os(), op, Buffer::IncludedFile);
1108 xs << XMLStream::ESCAPE_NONE << "<!-- Included file: ";
1109 xs << from_utf8(included_file.absFileName());
1110 xs << XMLStream::ESCAPE_NONE << " -->";
1115 void InsetInclude::validate(LaTeXFeatures & features) const
1117 LATTEST(&buffer() == &features.buffer());
1119 string incfile = ltrim(to_utf8(params()["filename"]));
1120 string const included_file =
1121 includedFileName(buffer(), params()).absFileName();
1124 if (isLyXFileName(included_file))
1125 writefile = changeExtension(included_file, ".sgml");
1127 writefile = included_file;
1129 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1130 incfile = DocFileName(writefile).mangledFileName();
1131 writefile = makeAbsPath(incfile,
1132 buffer().masterBuffer()->temppath()).absFileName();
1135 features.includeFile(include_label, writefile);
1137 features.useInsetLayout(getLayout());
1138 if (isVerbatim(params()))
1139 features.require("verbatim");
1140 else if (isListings(params())) {
1141 if (buffer().params().use_minted) {
1142 features.require("minted");
1143 string const opts = to_utf8(params()["lstparams"]);
1144 InsetListingsParams lstpars(opts);
1145 if (!lstpars.isFloat() && contains(opts, "caption="))
1146 features.require("lyxmintcaption");
1148 features.require("listings");
1151 // Here we must do the fun stuff...
1152 // Load the file in the include if it needs
1154 Buffer * const tmp = loadIfNeeded();
1158 // the file is loaded
1159 if (checkForRecursiveInclude(tmp))
1161 buffer().pushIncludedBuffer(tmp);
1163 // We must temporarily change features.buffer,
1164 // otherwise it would always be the master buffer,
1165 // and nested includes would not work.
1166 features.setBuffer(*tmp);
1167 // Maybe this is already a child
1168 bool const is_child =
1169 features.runparams().is_child;
1170 features.runparams().is_child = true;
1171 tmp->validate(features);
1172 features.runparams().is_child = is_child;
1173 features.setBuffer(buffer());
1175 buffer().popIncludedBuffer();
1179 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1181 Buffer * ibuf = loadIfNeeded();
1185 if (checkForRecursiveInclude(ibuf))
1187 buffer().pushIncludedBuffer(ibuf);
1188 ibuf->collectBibKeys(checkedFiles);
1189 buffer().popIncludedBuffer();
1193 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1195 LBUFERR(mi.base.bv);
1197 bool use_preview = false;
1198 if (RenderPreview::previewText()) {
1199 graphics::PreviewImage const * pimage =
1200 preview_->getPreviewImage(mi.base.bv->buffer());
1201 use_preview = pimage && pimage->image();
1205 preview_->metrics(mi, dim);
1209 button_.update(screenLabel(), true, false, !file_exist_ || recursion_error_);
1211 button_.metrics(mi, dim);
1214 Box b(0, dim.wid, -dim.asc, dim.des);
1219 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1221 LBUFERR(pi.base.bv);
1223 bool use_preview = false;
1224 if (RenderPreview::previewText()) {
1225 graphics::PreviewImage const * pimage =
1226 preview_->getPreviewImage(pi.base.bv->buffer());
1227 use_preview = pimage && pimage->image();
1231 preview_->draw(pi, x, y);
1233 button_.draw(pi, x, y);
1237 void InsetInclude::write(ostream & os) const
1239 params().Write(os, &buffer());
1243 string InsetInclude::contextMenuName() const
1245 return "context-include";
1249 Inset::RowFlags InsetInclude::rowFlags() const
1251 return type(params()) == INPUT ? Inline : Display;
1255 docstring InsetInclude::layoutName() const
1257 if (isListings(params()))
1258 return from_ascii("IncludeListings");
1259 return InsetCommand::layoutName();
1267 void InsetInclude::fileChanged() const
1269 Buffer const * const buffer = updateFrontend();
1273 preview_->removePreview(*buffer);
1274 add_preview(*preview_, *this, *buffer);
1275 preview_->startLoading(*buffer);
1281 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1283 FileName const included_file = includedFileName(buffer, params);
1285 return type(params) == INPUT && params.preview() &&
1286 included_file.isReadableFile();
1290 docstring latexString(InsetInclude const & inset)
1292 odocstringstream ods;
1294 // We don't need to set runparams.encoding since this will be done
1295 // by latex() anyway.
1296 OutputParams runparams(nullptr);
1297 runparams.flavor = OutputParams::LATEX;
1298 runparams.for_preview = true;
1299 inset.latex(os, runparams);
1305 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1306 Buffer const & buffer)
1308 InsetCommandParams const & params = inset.params();
1309 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1310 renderer.setAbsFile(includedFileName(buffer, params));
1311 docstring const snippet = latexString(inset);
1312 renderer.addPreview(snippet, buffer);
1319 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1320 graphics::PreviewLoader & ploader) const
1322 Buffer const & buffer = ploader.buffer();
1323 if (!preview_wanted(params(), buffer))
1325 preview_->setAbsFile(includedFileName(buffer, params()));
1326 docstring const snippet = latexString(*this);
1327 preview_->addPreview(snippet, ploader);
1331 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1332 UpdateType utype, TocBackend & backend) const
1334 if (isListings(params())) {
1336 label_->addToToc(cpit, output_active, utype, backend);
1337 TocBuilder & b = backend.builder("listing");
1338 b.pushItem(cpit, screenLabel(), output_active);
1339 InsetListingsParams p(to_utf8(params()["lstparams"]));
1340 b.argumentItem(from_utf8(p.getParamValue("caption")));
1342 } else if (isVerbatim(params())) {
1343 TocBuilder & b = backend.builder("child");
1344 b.pushItem(cpit, screenLabel(), output_active);
1347 Buffer const * const childbuffer = loadIfNeeded();
1349 TocBuilder & b = backend.builder("child");
1350 string const fname = ltrim(to_utf8(params()["filename"]));
1351 // mark non-existent childbuffer with FILE MISSING
1352 docstring const str = (childbuffer ? from_ascii("") : _("FILE MISSING: "))
1353 + from_utf8(onlyFileName(fname)) + " (" + from_utf8(fname) + ")";
1354 b.pushItem(cpit, str, output_active);
1360 if (checkForRecursiveInclude(childbuffer))
1362 buffer().pushIncludedBuffer(childbuffer);
1363 // Update the child's tocBackend. The outliner uses the master's, but
1364 // the navigation menu uses the child's.
1365 childbuffer->tocBackend().update(output_active, utype);
1366 // Include Tocs from children
1367 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1369 buffer().popIncludedBuffer();
1370 // Copy missing outliner names (though the user has been warned against
1371 // having different document class and module selection between master
1373 for (auto const & name
1374 : childbuffer->params().documentClass().outlinerNames())
1375 backend.addName(name.first, translateIfPossible(name.second));
1380 void InsetInclude::updateCommand()
1385 docstring old_label = label_->getParam("name");
1386 label_->updateLabel(old_label);
1387 // the label might have been adapted (duplicate)
1388 docstring new_label = label_->getParam("name");
1389 if (old_label == new_label)
1392 // update listings parameters...
1393 InsetCommandParams p(INCLUDE_CODE);
1395 InsetListingsParams par(to_utf8(params()["lstparams"]));
1396 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1397 p["lstparams"] = from_utf8(par.params());
1402 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1404 file_exist_ = includedFileExist();
1405 Buffer const * const childbuffer = loadIfNeeded();
1407 if (!checkForRecursiveInclude(childbuffer))
1408 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1409 button_.update(screenLabel(), true, false, recursion_error_);
1413 button_.update(screenLabel(), true, false, !file_exist_);
1415 if (!isListings(params()))
1419 label_->updateBuffer(it, utype, deleted);
1421 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1422 if (par.getParamValue("caption").empty()) {
1423 listings_label_ = buffer().B_("Program Listing");
1426 Buffer const & master = *buffer().masterBuffer();
1427 Counters & counters = master.params().documentClass().counters();
1428 docstring const cnt = from_ascii("listing");
1429 listings_label_ = master.B_("Program Listing");
1430 if (counters.hasCounter(cnt)) {
1431 counters.step(cnt, utype);
1432 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1437 bool InsetInclude::includedFileExist() const
1439 // check whether the included file exist
1440 string incFileName = ltrim(to_utf8(params()["filename"]));
1442 support::makeAbsPath(incFileName,
1443 support::onlyPath(buffer().absFileName()));