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)
194 preview_->connect([=](){ fileChanged(); });
196 if (isListings(params())) {
197 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
198 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
199 } else if (isInputOrInclude(params()) && buf)
204 InsetInclude::InsetInclude(InsetInclude const & other)
205 : InsetCommand(other), include_label(other.include_label),
206 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
207 set_label_(false), label_(nullptr), child_buffer_(nullptr),
208 file_exist_(other.file_exist_)
210 preview_->connect([=](){ fileChanged(); });
213 label_ = new InsetLabel(*other.label_);
217 InsetInclude::~InsetInclude()
223 void InsetInclude::setBuffer(Buffer & buffer)
225 InsetCommand::setBuffer(buffer);
227 label_->setBuffer(buffer);
231 void InsetInclude::setChildBuffer(Buffer * buffer)
233 child_buffer_ = buffer;
237 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
240 // This is only correct for the case of listings, but it'll do for now.
241 // In the other cases, this second parameter should just be empty.
242 static ParamInfo param_info_;
243 if (param_info_.empty()) {
244 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
245 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
246 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
252 bool InsetInclude::isCompatibleCommand(string const & s)
254 return type(s) != NONE;
258 bool InsetInclude::needsCProtection(bool const /*maintext*/, bool const fragile) const
260 // We need to \cprotect all types in fragile context
265 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
267 switch (cmd.action()) {
269 case LFUN_INSET_EDIT: {
270 editIncluded(ltrim(to_utf8(params()["filename"])));
274 case LFUN_INSET_MODIFY: {
275 // It should be OK just to invalidate the cache in setParams()
277 // child_buffer_ = 0;
278 InsetCommandParams p(INCLUDE_CODE);
279 if (cmd.getArg(0) == "changetype") {
281 InsetCommand::doDispatch(cur, cmd);
284 InsetCommand::string2params(to_utf8(cmd.argument()), p);
285 if (!p.getCmdName().empty()) {
287 InsetListingsParams new_params(to_utf8(p["lstparams"]));
288 docstring const new_label =
289 from_utf8(new_params.getParamValue("label"));
291 if (new_label.empty()) {
297 old_label = label_->getParam("name");
299 label_ = createLabel(buffer_, new_label);
300 label_->setBuffer(buffer());
303 if (new_label != old_label) {
304 label_->updateLabelAndRefs(new_label, &cur);
305 // the label might have been adapted (duplicate)
306 if (new_label != label_->getParam("name")) {
307 new_params.addParam("label", "{" +
308 to_utf8(label_->getParam("name")) + "}", true);
309 p["lstparams"] = from_utf8(new_params.params());
316 cur.forceBufferUpdate();
318 cur.noScreenUpdate();
322 case LFUN_MOUSE_RELEASE: {
323 if (cmd.modifier() == ControlModifier) {
324 FileName const incfile = includedFileName(buffer(), params());
325 string const & incname = incfile.absFileName();
326 editIncluded(incname);
332 //pass everything else up the chain
334 InsetCommand::doDispatch(cur, cmd);
340 void InsetInclude::editIncluded(string const & f)
342 if (isLyXFileName(f)) {
343 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, f);
346 // tex file or other text file in verbatim mode
347 theFormats().edit(buffer(),
348 support::makeAbsPath(f, support::onlyPath(buffer().absFileName())),
353 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
354 FuncStatus & flag) const
356 switch (cmd.action()) {
358 case LFUN_INSET_EDIT:
359 flag.setEnabled(true);
362 case LFUN_INSET_MODIFY:
363 if (cmd.getArg(0) == "changetype")
364 return InsetCommand::getStatus(cur, cmd, flag);
366 flag.setEnabled(true);
370 return InsetCommand::getStatus(cur, cmd, flag);
375 void InsetInclude::setParams(InsetCommandParams const & p)
377 // invalidate the cache
378 child_buffer_ = nullptr;
380 // reset in order to allow loading new file
381 failedtoload_ = false;
383 InsetCommand::setParams(p);
386 if (preview_->monitoring())
387 preview_->stopMonitoring();
389 if (type(params()) == INPUT)
390 add_preview(*preview_, *this, buffer());
394 bool InsetInclude::isChildIncluded() const
396 std::list<std::string> includeonlys =
397 buffer().params().getIncludedChildren();
398 if (includeonlys.empty())
400 return (std::find(includeonlys.begin(),
402 ltrim(to_utf8(params()["filename"]))) != includeonlys.end());
406 docstring InsetInclude::screenLabel() const
408 docstring pre = file_exist_ ? docstring() : _("FILE MISSING:");
412 switch (type(params())) {
414 temp = buffer().B_("Input");
417 temp = buffer().B_("Verbatim");
420 temp = buffer().B_("Verbatim*");
423 if (isChildIncluded())
424 temp = buffer().B_("Include");
426 temp += buffer().B_("Include (excluded)");
429 temp = listings_label_;
432 LASSERT(false, temp = buffer().B_("Unknown"));
438 if (ltrim(params()["filename"]).empty())
441 temp += from_utf8(onlyFileName(ltrim(to_utf8(params()["filename"]))));
443 return pre.empty() ? temp : pre + from_ascii(" ") + temp;
447 Buffer * InsetInclude::getChildBuffer() const
449 Buffer * childBuffer = loadIfNeeded();
451 // FIXME RECURSIVE INCLUDE
452 // This isn't sufficient, as the inclusion could be downstream.
453 // But it'll have to do for now.
454 return (childBuffer == &buffer()) ? nullptr : childBuffer;
458 Buffer * InsetInclude::loadIfNeeded() const
460 // This is for background export and preview. We don't even want to
461 // try to load the cloned child document again.
462 if (buffer().isClone())
463 return child_buffer_;
465 // Don't try to load it again if we failed before.
466 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
469 FileName const included_file = includedFileName(buffer(), params());
470 // Use cached Buffer if possible.
471 if (child_buffer_ != nullptr) {
472 if (theBufferList().isLoaded(child_buffer_)
473 // additional sanity check: make sure the Buffer really is
474 // associated with the file we want.
475 && child_buffer_ == theBufferList().getBuffer(included_file))
476 return child_buffer_;
477 // Buffer vanished, so invalidate cache and try to reload.
478 child_buffer_ = nullptr;
481 if (!isLyXFileName(included_file.absFileName()))
484 Buffer * child = theBufferList().getBuffer(included_file);
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 // Set parent before loading, such that macros can be tracked
498 child->setParent(&buffer());
500 if (child->loadLyXFile() != Buffer::ReadSuccess) {
501 failedtoload_ = true;
502 child->setParent(nullptr);
503 //close the buffer we just opened
504 theBufferList().release(child);
508 if (!child->errorList("Parse").empty()) {
509 // FIXME: Do something.
512 // The file was already loaded, so, simply
513 // inform parent buffer about local macros.
514 Buffer const * parent = &buffer();
515 child->setParent(parent);
517 child->listMacroNames(macros);
518 MacroNameSet::const_iterator cit = macros.begin();
519 MacroNameSet::const_iterator end = macros.end();
520 for (; cit != end; ++cit)
521 parent->usermacros.insert(*cit);
524 // Cache the child buffer.
525 child_buffer_ = child;
530 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
532 string incfile = ltrim(to_utf8(params()["filename"]));
534 // Warn if no file name has been specified
535 if (incfile.empty()) {
536 frontend::Alert::warning(_("No file name specified"),
537 _("An included file name is empty.\n"
538 "Ignoring Inclusion"),
542 // Warn if file doesn't exist
543 if (!includedFileExist()) {
544 frontend::Alert::warning(_("Included file not found"),
545 bformat(_("The included file\n"
547 "has not been found. LyX will ignore the inclusion."),
553 FileName const included_file = includedFileName(buffer(), params());
555 // Check we're not trying to include ourselves.
556 // FIXME RECURSIVE INCLUDE
557 // This isn't sufficient, as the inclusion could be downstream.
558 // But it'll have to do for now.
559 if (isInputOrInclude(params()) &&
560 buffer().absFileName() == included_file.absFileName())
562 Alert::error(_("Recursive input"),
563 bformat(_("Attempted to include file %1$s in itself! "
564 "Ignoring inclusion."), from_utf8(incfile)));
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 sligthly 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 // if it's a LyX file and we're inputting or including,
772 // try to load it so we can write the associated latex
774 Buffer * tmp = loadIfNeeded();
776 if (!runparams.silent) {
777 docstring text = bformat(_("Could not load included "
779 "Please, check whether it actually exists."),
780 included_file.displayName());
781 throw ExceptionMessage(ErrorException, _("Error: "),
787 if (!runparams.silent) {
788 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
790 docstring text = bformat(_("Included file `%1$s'\n"
791 "has textclass `%2$s'\n"
792 "while parent file has textclass `%3$s'."),
793 included_file.displayName(),
794 from_utf8(tmp->params().documentClass().name()),
795 from_utf8(masterBuffer->params().documentClass().name()));
796 Alert::warning(_("Different textclasses"), text, true);
799 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
800 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
801 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
802 docstring text = bformat(_("Included file `%1$s'\n"
803 "has use-non-TeX-fonts set to `%2$s'\n"
804 "while parent file has use-non-TeX-fonts set to `%3$s'."),
805 included_file.displayName(),
807 from_utf8(master_tf));
808 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
810 else if (tmp->params().inputenc != masterBuffer->params().inputenc) {
811 docstring text = bformat(_("Included file `%1$s'\n"
812 "uses input encoding \"%2$s\" [%3$s]\n"
813 "while parent file uses input encoding \"%4$s\" [%5$s]."),
814 included_file.displayName(),
815 _(tmp->params().inputenc),
816 from_utf8(tmp->params().encoding().guiName()),
817 _(masterBuffer->params().inputenc),
818 from_utf8(masterBuffer->params().encoding().guiName()));
819 Alert::warning(_("Different LaTeX input encodings"), text, true);
822 // Make sure modules used in child are all included in master
823 // FIXME It might be worth loading the children's modules into the master
824 // over in BufferParams rather than doing this check.
825 LayoutModuleList const masterModules = masterBuffer->params().getModules();
826 LayoutModuleList const childModules = tmp->params().getModules();
827 LayoutModuleList::const_iterator it = childModules.begin();
828 LayoutModuleList::const_iterator end = childModules.end();
829 for (; it != end; ++it) {
830 string const module = *it;
831 LayoutModuleList::const_iterator found =
832 find(masterModules.begin(), masterModules.end(), module);
833 if (found == masterModules.end()) {
834 docstring text = bformat(_("Included file `%1$s'\n"
835 "uses module `%2$s'\n"
836 "which is not used in parent file."),
837 included_file.displayName(), from_utf8(module));
838 Alert::warning(_("Module not found"), text, true);
843 tmp->markDepClean(masterBuffer->temppath());
845 // Don't assume the child's format is latex
846 string const inc_format = tmp->params().bufferFormat();
847 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
848 theFormats().extension(inc_format)));
850 // FIXME: handle non existing files
851 // The included file might be written in a different encoding
853 Encoding const * const oldEnc = runparams.encoding;
854 Language const * const oldLang = runparams.master_language;
855 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
856 // the children must be encoded in plain utf8!
857 if (masterBuffer->params().useNonTeXFonts)
858 runparams.encoding = encodings.fromLyXName("utf8-plain");
860 runparams.encoding = oldEnc;
861 else runparams.encoding = &tmp->params().encoding();
862 runparams.master_language = buffer().params().language;
863 runparams.par_begin = 0;
864 runparams.par_end = tmp->paragraphs().size();
865 runparams.is_child = true;
866 Buffer::ExportStatus retval =
867 tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
868 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
869 if (retval == Buffer::ExportKilled && buffer().isClone() &&
870 buffer().isExporting()) {
871 // We really shouldn't get here, I don't think.
872 LYXERR0("No conversion exception?");
873 throw ConversionException();
875 else if (retval != Buffer::ExportSuccess) {
876 if (!runparams.silent) {
877 docstring msg = bformat(_("Included file `%1$s' "
878 "was not exported correctly.\n "
879 "LaTeX export is probably incomplete."),
880 included_file.displayName());
881 ErrorList const & el = tmp->errorList("Export");
883 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
884 msg, el.begin()->error, el.begin()->description);
885 throw ExceptionMessage(ErrorException, _("Error: "), msg);
888 runparams.encoding = oldEnc;
889 runparams.master_language = oldLang;
890 runparams.is_child = false;
892 // If needed, use converters to produce a latex file from the child
893 if (tmpwritefile != writefile) {
895 Converters::RetVal const conv_retval =
896 theConverters().convert(tmp, tmpwritefile, writefile,
897 included_file, inc_format, tex_format, el);
898 if (conv_retval == Converters::KILLED && buffer().isClone() &&
899 buffer().isExporting()) {
900 // We really shouldn't get here, I don't think.
901 LYXERR0("No conversion exception?");
902 throw ConversionException();
903 } else if (conv_retval != Converters::SUCCESS && !runparams.silent) {
904 docstring msg = bformat(_("Included file `%1$s' "
905 "was not exported correctly.\n "
906 "LaTeX export is probably incomplete."),
907 included_file.displayName());
909 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
910 msg, el.begin()->error, el.begin()->description);
911 throw ExceptionMessage(ErrorException, _("Error: "), msg);
915 // In this case, it's not a LyX file, so we copy the file
916 // to the temp dir, so that .aux files etc. are not created
917 // in the original dir. Files included by this file will be
918 // found via either the environment variable TEXINPUTS, or
919 // input@path, see ../Buffer.cpp.
920 unsigned long const checksum_in = included_file.checksum();
921 unsigned long const checksum_out = writefile.checksum();
923 if (checksum_in != checksum_out) {
924 if (!included_file.copyTo(writefile)) {
927 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
928 "into the temporary directory."),
929 from_utf8(included_file.absFileName()))));
937 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
942 // For verbatim and listings, we just include the contents of the file as-is.
943 // In the case of listings, we wrap it in <pre>.
944 bool const listing = isListings(params());
945 if (listing || isVerbatim(params())) {
947 xs << html::StartTag("pre");
948 // FIXME: We don't know the encoding of the file, default to UTF-8.
949 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
951 xs << html::EndTag("pre");
955 // We don't (yet) know how to Input or Include non-LyX files.
956 // (If we wanted to get really arcane, we could run some tex2html
957 // converter on the included file. But that's just masochistic.)
958 FileName const included_file = includedFileName(buffer(), params());
959 if (!isLyXFileName(included_file.absFileName())) {
961 frontend::Alert::warning(_("Unsupported Inclusion"),
962 bformat(_("LyX does not know how to include non-LyX files when "
963 "generating HTML output. Offending file:\n%1$s"),
964 ltrim(params()["filename"])));
968 // In the other cases, we will generate the HTML and include it.
970 // Check we're not trying to include ourselves.
971 // FIXME RECURSIVE INCLUDE
972 if (buffer().absFileName() == included_file.absFileName()) {
973 Alert::error(_("Recursive input"),
974 bformat(_("Attempted to include file %1$s in itself! "
975 "Ignoring inclusion."), ltrim(params()["filename"])));
979 Buffer const * const ibuf = loadIfNeeded();
983 // are we generating only some paragraphs, or all of them?
984 bool const all_pars = !rp.dryrun ||
985 (rp.par_begin == 0 &&
986 rp.par_end == (int)buffer().text().paragraphs().size());
988 OutputParams op = rp;
992 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
994 xs << XHTMLStream::ESCAPE_NONE
995 << "<!-- Included file: "
996 << from_utf8(included_file.absFileName())
997 << 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() + ']';
1033 writePlaintextFile(*ibuf, os, op);
1038 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
1040 string incfile = ltrim(to_utf8(params()["filename"]));
1042 // Do nothing if no file name has been specified
1043 if (incfile.empty())
1046 string const included_file = includedFileName(buffer(), params()).absFileName();
1048 // Check we're not trying to include ourselves.
1049 // FIXME RECURSIVE INCLUDE
1050 // This isn't sufficient, as the inclusion could be downstream.
1051 // But it'll have to do for now.
1052 if (buffer().absFileName() == included_file) {
1053 Alert::error(_("Recursive input"),
1054 bformat(_("Attempted to include file %1$s in itself! "
1055 "Ignoring inclusion."), from_utf8(incfile)));
1059 string exppath = incfile;
1060 if (!runparams.export_folder.empty()) {
1061 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
1062 FileName(exppath).onlyPath().createPath();
1065 // write it to a file (so far the complete file)
1066 string const exportfile = changeExtension(exppath, ".sgml");
1067 DocFileName writefile(changeExtension(included_file, ".sgml"));
1069 Buffer * tmp = loadIfNeeded();
1071 string const mangled = writefile.mangledFileName();
1072 writefile = makeAbsPath(mangled,
1073 buffer().masterBuffer()->temppath());
1074 if (!runparams.nice)
1077 LYXERR(Debug::LATEX, "incfile:" << incfile);
1078 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
1079 LYXERR(Debug::LATEX, "writefile:" << writefile);
1081 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
1084 runparams.exportdata->addExternalFile("docbook", writefile,
1086 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1089 if (isVerbatim(params()) || isListings(params())) {
1090 os << "<inlinegraphic fileref=\""
1091 << '&' << include_label << ';'
1092 << "\" format=\"linespecific\">";
1094 os << '&' << include_label << ';';
1100 void InsetInclude::validate(LaTeXFeatures & features) const
1102 LATTEST(&buffer() == &features.buffer());
1104 string incfile = ltrim(to_utf8(params()["filename"]));
1105 string const included_file =
1106 includedFileName(buffer(), params()).absFileName();
1109 if (isLyXFileName(included_file))
1110 writefile = changeExtension(included_file, ".sgml");
1112 writefile = included_file;
1114 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1115 incfile = DocFileName(writefile).mangledFileName();
1116 writefile = makeAbsPath(incfile,
1117 buffer().masterBuffer()->temppath()).absFileName();
1120 features.includeFile(include_label, writefile);
1122 features.useInsetLayout(getLayout());
1123 if (isVerbatim(params()))
1124 features.require("verbatim");
1125 else if (isListings(params())) {
1126 if (buffer().params().use_minted) {
1127 features.require("minted");
1128 string const opts = to_utf8(params()["lstparams"]);
1129 InsetListingsParams lstpars(opts);
1130 if (!lstpars.isFloat() && contains(opts, "caption="))
1131 features.require("lyxmintcaption");
1133 features.require("listings");
1136 // Here we must do the fun stuff...
1137 // Load the file in the include if it needs
1139 Buffer * const tmp = loadIfNeeded();
1141 // the file is loaded
1142 // make sure the buffer isn't us
1143 // FIXME RECURSIVE INCLUDES
1144 // This is not sufficient, as recursive includes could be
1145 // more than a file away. But it will do for now.
1146 if (tmp && tmp != &buffer()) {
1147 // We must temporarily change features.buffer,
1148 // otherwise it would always be the master buffer,
1149 // and nested includes would not work.
1150 features.setBuffer(*tmp);
1151 // Maybe this is already a child
1152 bool const is_child =
1153 features.runparams().is_child;
1154 features.runparams().is_child = true;
1155 tmp->validate(features);
1156 features.runparams().is_child = is_child;
1157 features.setBuffer(buffer());
1163 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1165 Buffer * child = loadIfNeeded();
1168 // FIXME RECURSIVE INCLUDE
1169 // This isn't sufficient, as the inclusion could be downstream.
1170 // But it'll have to do for now.
1171 if (child == &buffer())
1173 child->collectBibKeys(checkedFiles);
1177 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1179 LBUFERR(mi.base.bv);
1181 bool use_preview = false;
1182 if (RenderPreview::previewText()) {
1183 graphics::PreviewImage const * pimage =
1184 preview_->getPreviewImage(mi.base.bv->buffer());
1185 use_preview = pimage && pimage->image();
1189 preview_->metrics(mi, dim);
1193 button_.update(screenLabel(), true, false, !file_exist_);
1195 button_.metrics(mi, dim);
1198 Box b(0, dim.wid, -dim.asc, dim.des);
1203 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1205 LBUFERR(pi.base.bv);
1207 bool use_preview = false;
1208 if (RenderPreview::previewText()) {
1209 graphics::PreviewImage const * pimage =
1210 preview_->getPreviewImage(pi.base.bv->buffer());
1211 use_preview = pimage && pimage->image();
1215 preview_->draw(pi, x, y);
1217 button_.draw(pi, x, y);
1221 void InsetInclude::write(ostream & os) const
1223 params().Write(os, &buffer());
1227 string InsetInclude::contextMenuName() const
1229 return "context-include";
1233 Inset::DisplayType InsetInclude::display() const
1235 return type(params()) == INPUT ? Inline : AlignCenter;
1239 docstring InsetInclude::layoutName() const
1241 if (isListings(params()))
1242 return from_ascii("IncludeListings");
1243 return InsetCommand::layoutName();
1251 void InsetInclude::fileChanged() const
1253 Buffer const * const buffer = updateFrontend();
1257 preview_->removePreview(*buffer);
1258 add_preview(*preview_, *this, *buffer);
1259 preview_->startLoading(*buffer);
1265 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1267 FileName const included_file = includedFileName(buffer, params);
1269 return type(params) == INPUT && params.preview() &&
1270 included_file.isReadableFile();
1274 docstring latexString(InsetInclude const & inset)
1276 odocstringstream ods;
1278 // We don't need to set runparams.encoding since this will be done
1279 // by latex() anyway.
1280 OutputParams runparams(nullptr);
1281 runparams.flavor = OutputParams::LATEX;
1282 runparams.for_preview = true;
1283 inset.latex(os, runparams);
1289 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1290 Buffer const & buffer)
1292 InsetCommandParams const & params = inset.params();
1293 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1294 renderer.setAbsFile(includedFileName(buffer, params));
1295 docstring const snippet = latexString(inset);
1296 renderer.addPreview(snippet, buffer);
1303 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1304 graphics::PreviewLoader & ploader) const
1306 Buffer const & buffer = ploader.buffer();
1307 if (!preview_wanted(params(), buffer))
1309 preview_->setAbsFile(includedFileName(buffer, params()));
1310 docstring const snippet = latexString(*this);
1311 preview_->addPreview(snippet, ploader);
1315 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1316 UpdateType utype, TocBackend & backend) const
1318 if (isListings(params())) {
1320 label_->addToToc(cpit, output_active, utype, backend);
1321 TocBuilder & b = backend.builder("listing");
1322 b.pushItem(cpit, screenLabel(), output_active);
1323 InsetListingsParams p(to_utf8(params()["lstparams"]));
1324 b.argumentItem(from_utf8(p.getParamValue("caption")));
1326 } else if (isVerbatim(params())) {
1327 TocBuilder & b = backend.builder("child");
1328 b.pushItem(cpit, screenLabel(), output_active);
1331 Buffer const * const childbuffer = getChildBuffer();
1333 TocBuilder & b = backend.builder("child");
1334 docstring str = childbuffer ? childbuffer->fileName().displayName()
1336 b.pushItem(cpit, str, output_active);
1342 // Update the child's tocBackend. The outliner uses the master's, but
1343 // the navigation menu uses the child's.
1344 childbuffer->tocBackend().update(output_active, utype);
1345 // Include Tocs from children
1346 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
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();
1384 button_.update(screenLabel(), true, false, !file_exist_);
1386 Buffer const * const childbuffer = getChildBuffer();
1388 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1391 if (!isListings(params()))
1395 label_->updateBuffer(it, utype, deleted);
1397 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1398 if (par.getParamValue("caption").empty()) {
1399 listings_label_ = buffer().B_("Program Listing");
1402 Buffer const & master = *buffer().masterBuffer();
1403 Counters & counters = master.params().documentClass().counters();
1404 docstring const cnt = from_ascii("listing");
1405 listings_label_ = master.B_("Program Listing");
1406 if (counters.hasCounter(cnt)) {
1407 counters.step(cnt, utype);
1408 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1413 bool InsetInclude::includedFileExist() const
1415 // check whether the included file exist
1416 string incFileName = ltrim(to_utf8(params()["filename"]));
1418 support::makeAbsPath(incFileName,
1419 support::onlyPath(buffer().absFileName()));