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::loadIfNeeded() const
451 // This is for background export and preview. We don't even want to
452 // try to load the cloned child document again.
453 if (buffer().isClone())
454 return child_buffer_;
456 // Don't try to load it again if we failed before.
457 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
460 FileName const included_file = includedFileName(buffer(), params());
461 // Use cached Buffer if possible.
462 if (child_buffer_ != nullptr) {
463 if (theBufferList().isLoaded(child_buffer_)
464 // additional sanity check: make sure the Buffer really is
465 // associated with the file we want.
466 && child_buffer_ == theBufferList().getBuffer(included_file))
467 return child_buffer_;
468 // Buffer vanished, so invalidate cache and try to reload.
469 child_buffer_ = nullptr;
472 if (!isLyXFileName(included_file.absFileName()))
475 Buffer * child = theBufferList().getBuffer(included_file);
476 if (checkForRecursiveInclude(child))
480 // the readonly flag can/will be wrong, not anymore I think.
481 if (!included_file.exists()) {
482 failedtoload_ = true;
486 child = theBufferList().newBuffer(included_file.absFileName());
488 // Buffer creation is not possible.
491 buffer().pushIncludedBuffer(child);
492 // Set parent before loading, such that macros can be tracked
493 child->setParent(&buffer());
495 if (child->loadLyXFile() != Buffer::ReadSuccess) {
496 failedtoload_ = true;
497 child->setParent(nullptr);
498 //close the buffer we just opened
499 theBufferList().release(child);
500 buffer().popIncludedBuffer();
504 buffer().popIncludedBuffer();
505 if (!child->errorList("Parse").empty()) {
506 // FIXME: Do something.
509 // The file was already loaded, so, simply
510 // inform parent buffer about local macros.
511 Buffer const * parent = &buffer();
512 child->setParent(parent);
514 child->listMacroNames(macros);
515 MacroNameSet::const_iterator cit = macros.begin();
516 MacroNameSet::const_iterator end = macros.end();
517 for (; cit != end; ++cit)
518 parent->usermacros.insert(*cit);
521 // Cache the child buffer.
522 child_buffer_ = child;
527 bool InsetInclude::checkForRecursiveInclude(
528 Buffer const * cbuf, bool silent) const
530 if (recursion_error_)
533 if (!buffer().isBufferIncluded(cbuf))
537 docstring const msg = _("The file\n%1$s\n has attempted to include itself.\n"
538 "The document set will not work properly until this is fixed!");
539 frontend::Alert::warning(_("Recursive Include"),
540 bformat(msg, from_utf8(cbuf->fileName().absFileName())));
542 recursion_error_ = true;
547 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
549 string incfile = ltrim(to_utf8(params()["filename"]));
551 // Warn if no file name has been specified
552 if (incfile.empty()) {
553 frontend::Alert::warning(_("No file name specified"),
554 _("An included file name is empty.\n"
555 "Ignoring Inclusion"),
559 // Warn if file doesn't exist
560 if (!includedFileExist()) {
561 frontend::Alert::warning(_("Included file not found"),
562 bformat(_("The included file\n"
564 "has not been found. LyX will ignore the inclusion."),
570 FileName const included_file = includedFileName(buffer(), params());
571 Buffer const * const masterBuffer = buffer().masterBuffer();
573 // if incfile is relative, make it relative to the master
575 if (!FileName::isAbsolute(incfile)) {
577 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
578 from_utf8(masterBuffer->filePath())));
581 string exppath = incfile;
582 if (!runparams.export_folder.empty()) {
583 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
586 // write it to a file (so far the complete file)
590 if (type(params()) == LISTINGS) {
591 exportfile = exppath;
592 mangled = DocFileName(included_file).mangledFileName();
594 exportfile = changeExtension(exppath, ".tex");
595 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
601 else if (!runparams.silent)
602 ; // no warning wanted
603 else if (!isValidLaTeXFileName(incfile)) {
604 frontend::Alert::warning(_("Invalid filename"),
605 _("The following filename will cause troubles "
606 "when running the exported file through LaTeX: ") +
608 } else if (!isValidDVIFileName(incfile)) {
609 frontend::Alert::warning(_("Problematic filename for DVI"),
610 _("The following filename can cause troubles "
611 "when running the exported file through LaTeX "
612 "and opening the resulting DVI: ") +
613 from_utf8(incfile), true);
616 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
617 buffer().temppath() : masterBuffer->temppath()));
619 LYXERR(Debug::LATEX, "incfile:" << incfile);
620 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
621 LYXERR(Debug::LATEX, "writefile:" << writefile);
623 string const tex_format = flavor2format(runparams.flavor);
625 switch (type(params())) {
628 incfile = latex_path(incfile);
630 os << '\\' << from_ascii(params().getCmdName()) << '{'
631 << from_utf8(incfile) << '}';
635 runparams.exportdata->addExternalFile(tex_format, writefile,
638 // \input wants file with extension (default is .tex)
639 if (!isLyXFileName(included_file.absFileName())) {
640 incfile = latex_path(incfile);
642 os << '\\' << from_ascii(params().getCmdName())
643 << '{' << from_utf8(incfile) << '}';
645 incfile = changeExtension(incfile, ".tex");
646 incfile = latex_path(incfile);
648 os << '\\' << from_ascii(params().getCmdName())
649 << '{' << from_utf8(incfile) << '}';
654 // Here, listings and minted have sligthly different behaviors.
655 // Using listings, it is always possible to have a caption,
656 // even for non-floats. Using minted, only floats can have a
657 // caption. So, with minted we use the following strategy.
658 // If a caption was specified but the float parameter was not,
659 // we ourselves add a caption above the listing (because the
660 // listing comes from a file and might span several pages).
661 // Otherwise, if float was specified, the floating listing
662 // environment provided by minted is used. In either case, the
663 // label parameter is taken as the label by which the float
664 // can be referenced, otherwise it will have the meaning
665 // intended by minted. In this last case, the label will
666 // serve as a sort of caption that, however, will be shown
667 // by minted only if the frame parameter is also specified.
668 bool const use_minted = buffer().params().use_minted;
669 runparams.exportdata->addExternalFile(tex_format, writefile,
671 string const opt = to_utf8(params()["lstparams"]);
672 // opt is set in QInclude dialog and should have passed validation.
673 InsetListingsParams lstparams(opt);
674 docstring parameters = from_utf8(lstparams.params());
679 bool isfloat = lstparams.isFloat();
680 // We are going to split parameters at commas, so
681 // replace commas that are not parameter separators
682 // with a code point from the private use area
683 char_type comma = replaceCommaInBraces(parameters);
684 // Get float placement, language, caption, and
685 // label, then remove the relative options if minted.
686 vector<docstring> opts =
687 getVectorFromString(parameters, from_ascii(","), false);
688 vector<docstring> latexed_opts;
689 for (size_t i = 0; i < opts.size(); ++i) {
690 // Restore replaced commas
691 opts[i] = subst(opts[i], comma, ',');
692 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
693 if (prefixIs(opts[i], from_ascii("float=")))
694 placement = opts[i].substr(6);
695 opts.erase(opts.begin() + i--);
696 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
697 language = opts[i].substr(9);
698 opts.erase(opts.begin() + i--);
699 } else if (prefixIs(opts[i], from_ascii("caption="))) {
700 caption = params().prepareCommand(runparams, trim(opts[i].substr(8), "{}"),
701 ParamInfo::HANDLING_LATEXIFY);
702 opts.erase(opts.begin() + i--);
704 latexed_opts.push_back(from_ascii("caption={") + caption + "}");
705 } else if (prefixIs(opts[i], from_ascii("label="))) {
706 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
707 ParamInfo::HANDLING_ESCAPE);
708 opts.erase(opts.begin() + i--);
710 latexed_opts.push_back(from_ascii("label={") + label + "}");
712 if (use_minted && !label.empty()) {
713 if (isfloat || !caption.empty())
714 label = trim(label, "{}");
716 opts.push_back(from_ascii("label=") + label);
719 if (!latexed_opts.empty())
720 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
721 parameters = getStringFromVector(opts, from_ascii(","));
722 if (language.empty())
723 language = from_ascii("TeX");
724 if (use_minted && isfloat) {
725 os << breakln << "\\begin{listing}";
726 if (!placement.empty())
727 os << '[' << placement << "]";
729 } else if (use_minted && !caption.empty()) {
730 os << breakln << "\\lyxmintcaption[t]{" << caption;
732 os << "\\label{" << label << "}";
735 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
736 if (!parameters.empty())
737 os << "[" << parameters << "]";
739 os << '{' << ascii_lowercase(language) << '}';
740 os << '{' << incfile << '}';
741 if (use_minted && isfloat) {
742 if (!caption.empty())
743 os << breakln << "\\caption{" << caption << "}";
745 os << breakln << "\\label{" << label << "}";
746 os << breakln << "\\end{listing}\n";
751 runparams.exportdata->addExternalFile(tex_format, writefile,
754 // \include don't want extension and demands that the
755 // file really have .tex
756 incfile = changeExtension(incfile, string());
757 incfile = latex_path(incfile);
759 os << '\\' << from_ascii(params().getCmdName()) << '{'
760 << from_utf8(incfile) << '}';
767 if (runparams.inComment || runparams.dryrun)
768 // Don't try to load or copy the file if we're
769 // in a comment or doing a dryrun
772 if (!isInputOrInclude(params()) ||
773 !isLyXFileName(included_file.absFileName())) {
774 // In this case, it's not a LyX file, so we copy the file
775 // to the temp dir, so that .aux files etc. are not created
776 // in the original dir. Files included by this file will be
777 // found via either the environment variable TEXINPUTS, or
778 // input@path, see ../Buffer.cpp.
779 unsigned long const checksum_in = included_file.checksum();
780 unsigned long const checksum_out = writefile.checksum();
781 if (checksum_in != checksum_out) {
782 if (!included_file.copyTo(writefile)) {
785 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
786 "into the temporary directory."),
787 from_utf8(included_file.absFileName()))));
794 // it's a LyX file and we're inputting or including, so
795 // try to load it so we can write the associated latex
796 Buffer * tmp = loadIfNeeded();
798 if (!runparams.silent) {
799 docstring text = bformat(_("Could not load included "
801 "Please, check whether it actually exists."),
802 included_file.displayName());
803 throw ExceptionMessage(ErrorException, _("Error: "),
809 if (recursion_error_)
812 if (!runparams.silent) {
813 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
815 docstring text = bformat(_("Included file `%1$s'\n"
816 "has textclass `%2$s'\n"
817 "while parent file has textclass `%3$s'."),
818 included_file.displayName(),
819 from_utf8(tmp->params().documentClass().name()),
820 from_utf8(masterBuffer->params().documentClass().name()));
821 Alert::warning(_("Different textclasses"), text, true);
824 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
825 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
826 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
827 docstring text = bformat(_("Included file `%1$s'\n"
828 "has use-non-TeX-fonts set to `%2$s'\n"
829 "while parent file has use-non-TeX-fonts set to `%3$s'."),
830 included_file.displayName(),
832 from_utf8(master_tf));
833 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
835 else if (tmp->params().inputenc != masterBuffer->params().inputenc) {
836 docstring text = bformat(_("Included file `%1$s'\n"
837 "uses input encoding \"%2$s\" [%3$s]\n"
838 "while parent file uses input encoding \"%4$s\" [%5$s]."),
839 included_file.displayName(),
840 _(tmp->params().inputenc),
841 from_utf8(tmp->params().encoding().guiName()),
842 _(masterBuffer->params().inputenc),
843 from_utf8(masterBuffer->params().encoding().guiName()));
844 Alert::warning(_("Different LaTeX input encodings"), text, true);
847 // Make sure modules used in child are all included in master
848 // FIXME It might be worth loading the children's modules into the master
849 // over in BufferParams rather than doing this check.
850 LayoutModuleList const masterModules = masterBuffer->params().getModules();
851 LayoutModuleList const childModules = tmp->params().getModules();
852 LayoutModuleList::const_iterator it = childModules.begin();
853 LayoutModuleList::const_iterator end = childModules.end();
854 for (; it != end; ++it) {
855 string const module = *it;
856 LayoutModuleList::const_iterator found =
857 find(masterModules.begin(), masterModules.end(), module);
858 if (found == masterModules.end()) {
859 docstring text = bformat(_("Included file `%1$s'\n"
860 "uses module `%2$s'\n"
861 "which is not used in parent file."),
862 included_file.displayName(), from_utf8(module));
863 Alert::warning(_("Module not found"), text, true);
868 tmp->markDepClean(masterBuffer->temppath());
870 // Don't assume the child's format is latex
871 string const inc_format = tmp->params().bufferFormat();
872 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
873 theFormats().extension(inc_format)));
875 // FIXME: handle non existing files
876 // The included file might be written in a different encoding
878 Encoding const * const oldEnc = runparams.encoding;
879 Language const * const oldLang = runparams.master_language;
880 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
881 // the children must be encoded in plain utf8!
882 if (masterBuffer->params().useNonTeXFonts)
883 runparams.encoding = encodings.fromLyXName("utf8-plain");
885 runparams.encoding = oldEnc;
886 else runparams.encoding = &tmp->params().encoding();
887 runparams.master_language = buffer().params().language;
888 runparams.par_begin = 0;
889 runparams.par_end = tmp->paragraphs().size();
890 runparams.is_child = true;
891 Buffer::ExportStatus retval =
892 tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
893 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
894 if (retval == Buffer::ExportKilled && buffer().isClone() &&
895 buffer().isExporting()) {
896 // We really shouldn't get here, I don't think.
897 LYXERR0("No conversion exception?");
898 throw ConversionException();
900 else if (retval != Buffer::ExportSuccess) {
901 if (!runparams.silent) {
902 docstring msg = bformat(_("Included file `%1$s' "
903 "was not exported correctly.\n "
904 "LaTeX export is probably incomplete."),
905 included_file.displayName());
906 ErrorList const & el = tmp->errorList("Export");
908 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
909 msg, el.begin()->error, el.begin()->description);
910 throw ExceptionMessage(ErrorException, _("Error: "), msg);
913 runparams.encoding = oldEnc;
914 runparams.master_language = oldLang;
915 runparams.is_child = false;
917 // If needed, use converters to produce a latex file from the child
918 if (tmpwritefile != writefile) {
920 Converters::RetVal const conv_retval =
921 theConverters().convert(tmp, tmpwritefile, writefile,
922 included_file, inc_format, tex_format, el);
923 if (conv_retval == Converters::KILLED && buffer().isClone() &&
924 buffer().isExporting()) {
925 // We really shouldn't get here, I don't think.
926 LYXERR0("No conversion exception?");
927 throw ConversionException();
928 } else if (conv_retval != Converters::SUCCESS && !runparams.silent) {
929 docstring msg = bformat(_("Included file `%1$s' "
930 "was not exported correctly.\n "
931 "LaTeX export is probably incomplete."),
932 included_file.displayName());
934 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
935 msg, el.begin()->error, el.begin()->description);
936 throw ExceptionMessage(ErrorException, _("Error: "), msg);
942 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
947 // For verbatim and listings, we just include the contents of the file as-is.
948 // In the case of listings, we wrap it in <pre>.
949 bool const listing = isListings(params());
950 if (listing || isVerbatim(params())) {
952 xs << html::StartTag("pre");
953 // FIXME: We don't know the encoding of the file, default to UTF-8.
954 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
956 xs << html::EndTag("pre");
960 // We don't (yet) know how to Input or Include non-LyX files.
961 // (If we wanted to get really arcane, we could run some tex2html
962 // converter on the included file. But that's just masochistic.)
963 FileName const included_file = includedFileName(buffer(), params());
964 if (!isLyXFileName(included_file.absFileName())) {
966 frontend::Alert::warning(_("Unsupported Inclusion"),
967 bformat(_("LyX does not know how to include non-LyX files when "
968 "generating HTML output. Offending file:\n%1$s"),
969 ltrim(params()["filename"])));
973 // In the other cases, we will generate the HTML and include it.
975 Buffer const * const ibuf = loadIfNeeded();
979 if (recursion_error_)
982 // are we generating only some paragraphs, or all of them?
983 bool const all_pars = !rp.dryrun ||
984 (rp.par_begin == 0 &&
985 rp.par_end == (int)buffer().text().paragraphs().size());
987 OutputParams op = rp;
991 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
993 xs << XHTMLStream::ESCAPE_NONE
994 << "<!-- Included file: "
995 << from_utf8(included_file.absFileName())
996 << XHTMLStream::ESCAPE_NONE
1003 int InsetInclude::plaintext(odocstringstream & os,
1004 OutputParams const & op, size_t) const
1006 // just write the filename if we're making a tooltip or toc entry,
1007 // or are generating this for advanced search
1008 if (op.for_tooltip || op.for_toc || op.for_search) {
1009 os << '[' << screenLabel() << '\n'
1010 << ltrim(getParam("filename")) << "\n]";
1011 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1014 if (isVerbatim(params()) || isListings(params())) {
1015 if (op.for_search) {
1016 os << '[' << screenLabel() << ']';
1019 os << '[' << screenLabel() << '\n'
1020 // FIXME: We don't know the encoding of the file, default to UTF-8.
1021 << includedFileName(buffer(), params()).fileContents("UTF-8")
1024 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1027 Buffer const * const ibuf = loadIfNeeded();
1029 docstring const str = '[' + screenLabel() + ']';
1034 if (recursion_error_)
1037 writePlaintextFile(*ibuf, os, op);
1042 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
1044 string incfile = ltrim(to_utf8(params()["filename"]));
1046 // Do nothing if no file name has been specified
1047 if (incfile.empty())
1050 string const included_file = includedFileName(buffer(), params()).absFileName();
1051 string exppath = incfile;
1052 if (!runparams.export_folder.empty()) {
1053 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
1054 FileName(exppath).onlyPath().createPath();
1057 // write it to a file (so far the complete file)
1058 string const exportfile = changeExtension(exppath, ".sgml");
1059 DocFileName writefile(changeExtension(included_file, ".sgml"));
1061 Buffer * tmp = loadIfNeeded();
1063 if (recursion_error_)
1066 string const mangled = writefile.mangledFileName();
1067 writefile = makeAbsPath(mangled,
1068 buffer().masterBuffer()->temppath());
1069 if (!runparams.nice)
1072 LYXERR(Debug::LATEX, "incfile:" << incfile);
1073 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
1074 LYXERR(Debug::LATEX, "writefile:" << writefile);
1076 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
1079 runparams.exportdata->addExternalFile("docbook", writefile,
1081 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1084 if (isVerbatim(params()) || isListings(params())) {
1085 os << "<inlinegraphic fileref=\""
1086 << '&' << include_label << ';'
1087 << "\" format=\"linespecific\">";
1089 os << '&' << include_label << ';';
1095 void InsetInclude::validate(LaTeXFeatures & features) const
1097 LATTEST(&buffer() == &features.buffer());
1099 string incfile = ltrim(to_utf8(params()["filename"]));
1100 string const included_file =
1101 includedFileName(buffer(), params()).absFileName();
1104 if (isLyXFileName(included_file))
1105 writefile = changeExtension(included_file, ".sgml");
1107 writefile = included_file;
1109 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1110 incfile = DocFileName(writefile).mangledFileName();
1111 writefile = makeAbsPath(incfile,
1112 buffer().masterBuffer()->temppath()).absFileName();
1115 features.includeFile(include_label, writefile);
1117 features.useInsetLayout(getLayout());
1118 if (isVerbatim(params()))
1119 features.require("verbatim");
1120 else if (isListings(params())) {
1121 if (buffer().params().use_minted) {
1122 features.require("minted");
1123 string const opts = to_utf8(params()["lstparams"]);
1124 InsetListingsParams lstpars(opts);
1125 if (!lstpars.isFloat() && contains(opts, "caption="))
1126 features.require("lyxmintcaption");
1128 features.require("listings");
1131 // Here we must do the fun stuff...
1132 // Load the file in the include if it needs
1134 Buffer * const tmp = loadIfNeeded();
1138 // the file is loaded
1139 if (checkForRecursiveInclude(tmp))
1141 buffer().pushIncludedBuffer(tmp);
1143 // We must temporarily change features.buffer,
1144 // otherwise it would always be the master buffer,
1145 // and nested includes would not work.
1146 features.setBuffer(*tmp);
1147 // Maybe this is already a child
1148 bool const is_child =
1149 features.runparams().is_child;
1150 features.runparams().is_child = true;
1151 tmp->validate(features);
1152 features.runparams().is_child = is_child;
1153 features.setBuffer(buffer());
1155 buffer().popIncludedBuffer();
1159 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1161 Buffer * ibuf = loadIfNeeded();
1165 if (checkForRecursiveInclude(ibuf))
1167 buffer().pushIncludedBuffer(ibuf);
1168 ibuf->collectBibKeys(checkedFiles);
1169 buffer().popIncludedBuffer();
1173 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1175 LBUFERR(mi.base.bv);
1177 bool use_preview = false;
1178 if (RenderPreview::previewText()) {
1179 graphics::PreviewImage const * pimage =
1180 preview_->getPreviewImage(mi.base.bv->buffer());
1181 use_preview = pimage && pimage->image();
1185 preview_->metrics(mi, dim);
1189 button_.update(screenLabel(), true, false, !file_exist_ || recursion_error_);
1191 button_.metrics(mi, dim);
1194 Box b(0, dim.wid, -dim.asc, dim.des);
1199 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1201 LBUFERR(pi.base.bv);
1203 bool use_preview = false;
1204 if (RenderPreview::previewText()) {
1205 graphics::PreviewImage const * pimage =
1206 preview_->getPreviewImage(pi.base.bv->buffer());
1207 use_preview = pimage && pimage->image();
1211 preview_->draw(pi, x, y);
1213 button_.draw(pi, x, y);
1217 void InsetInclude::write(ostream & os) const
1219 params().Write(os, &buffer());
1223 string InsetInclude::contextMenuName() const
1225 return "context-include";
1229 Inset::DisplayType InsetInclude::display() const
1231 return type(params()) == INPUT ? Inline : AlignCenter;
1235 docstring InsetInclude::layoutName() const
1237 if (isListings(params()))
1238 return from_ascii("IncludeListings");
1239 return InsetCommand::layoutName();
1247 void InsetInclude::fileChanged() const
1249 Buffer const * const buffer = updateFrontend();
1253 preview_->removePreview(*buffer);
1254 add_preview(*preview_, *this, *buffer);
1255 preview_->startLoading(*buffer);
1261 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1263 FileName const included_file = includedFileName(buffer, params);
1265 return type(params) == INPUT && params.preview() &&
1266 included_file.isReadableFile();
1270 docstring latexString(InsetInclude const & inset)
1272 odocstringstream ods;
1274 // We don't need to set runparams.encoding since this will be done
1275 // by latex() anyway.
1276 OutputParams runparams(nullptr);
1277 runparams.flavor = OutputParams::LATEX;
1278 runparams.for_preview = true;
1279 inset.latex(os, runparams);
1285 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1286 Buffer const & buffer)
1288 InsetCommandParams const & params = inset.params();
1289 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1290 renderer.setAbsFile(includedFileName(buffer, params));
1291 docstring const snippet = latexString(inset);
1292 renderer.addPreview(snippet, buffer);
1299 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1300 graphics::PreviewLoader & ploader) const
1302 Buffer const & buffer = ploader.buffer();
1303 if (!preview_wanted(params(), buffer))
1305 preview_->setAbsFile(includedFileName(buffer, params()));
1306 docstring const snippet = latexString(*this);
1307 preview_->addPreview(snippet, ploader);
1311 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1312 UpdateType utype, TocBackend & backend) const
1314 if (isListings(params())) {
1316 label_->addToToc(cpit, output_active, utype, backend);
1317 TocBuilder & b = backend.builder("listing");
1318 b.pushItem(cpit, screenLabel(), output_active);
1319 InsetListingsParams p(to_utf8(params()["lstparams"]));
1320 b.argumentItem(from_utf8(p.getParamValue("caption")));
1322 } else if (isVerbatim(params())) {
1323 TocBuilder & b = backend.builder("child");
1324 b.pushItem(cpit, screenLabel(), output_active);
1327 Buffer const * const childbuffer = loadIfNeeded();
1329 TocBuilder & b = backend.builder("child");
1330 docstring str = childbuffer ? childbuffer->fileName().displayName()
1332 b.pushItem(cpit, str, output_active);
1338 if (checkForRecursiveInclude(childbuffer))
1340 buffer().pushIncludedBuffer(childbuffer);
1341 // Update the child's tocBackend. The outliner uses the master's, but
1342 // the navigation menu uses the child's.
1343 childbuffer->tocBackend().update(output_active, utype);
1344 // Include Tocs from children
1345 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1347 buffer().popIncludedBuffer();
1348 // Copy missing outliner names (though the user has been warned against
1349 // having different document class and module selection between master
1351 for (auto const & name
1352 : childbuffer->params().documentClass().outlinerNames())
1353 backend.addName(name.first, translateIfPossible(name.second));
1358 void InsetInclude::updateCommand()
1363 docstring old_label = label_->getParam("name");
1364 label_->updateLabel(old_label);
1365 // the label might have been adapted (duplicate)
1366 docstring new_label = label_->getParam("name");
1367 if (old_label == new_label)
1370 // update listings parameters...
1371 InsetCommandParams p(INCLUDE_CODE);
1373 InsetListingsParams par(to_utf8(params()["lstparams"]));
1374 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1375 p["lstparams"] = from_utf8(par.params());
1380 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
1382 file_exist_ = includedFileExist();
1383 Buffer const * const childbuffer = loadIfNeeded();
1385 if (!checkForRecursiveInclude(childbuffer))
1386 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1387 button_.update(screenLabel(), true, false, recursion_error_);
1391 button_.update(screenLabel(), true, false, !file_exist_);
1393 if (!isListings(params()))
1397 label_->updateBuffer(it, utype, deleted);
1399 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1400 if (par.getParamValue("caption").empty()) {
1401 listings_label_ = buffer().B_("Program Listing");
1404 Buffer const & master = *buffer().masterBuffer();
1405 Counters & counters = master.params().documentClass().counters();
1406 docstring const cnt = from_ascii("listing");
1407 listings_label_ = master.B_("Program Listing");
1408 if (counters.hasCounter(cnt)) {
1409 counters.step(cnt, utype);
1410 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1415 bool InsetInclude::includedFileExist() const
1417 // check whether the included file exist
1418 string incFileName = ltrim(to_utf8(params()["filename"]));
1420 support::makeAbsPath(incFileName,
1421 support::onlyPath(buffer().absFileName()));