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/FileNameList.h"
59 #include "support/filetools.h"
60 #include "support/gettext.h"
61 #include "support/lassert.h"
62 #include "support/lstrings.h" // contains
63 #include "support/lyxalgo.h"
64 #include "support/mutex.h"
65 #include "support/ExceptionMessage.h"
67 #include "support/bind.h"
70 using namespace lyx::support;
74 namespace Alert = frontend::Alert;
79 docstring const uniqueID()
81 static unsigned int seed = 1000;
83 Mutex::Locker lock(&mutex);
84 return "file" + convert<docstring>(++seed);
88 /// the type of inclusion
90 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
94 Types type(string const & s)
98 if (s == "verbatiminput")
100 if (s == "verbatiminput*")
102 if (s == "lstinputlisting" || s == "inputminted")
110 Types type(InsetCommandParams const & params)
112 return type(params.getCmdName());
116 bool isListings(InsetCommandParams const & params)
118 return type(params) == LISTINGS;
122 bool isVerbatim(InsetCommandParams const & params)
124 Types const t = type(params);
125 return t == VERB || t == VERBAST;
129 bool isInputOrInclude(InsetCommandParams const & params)
131 Types const t = type(params);
132 return t == INPUT || t == INCLUDE;
136 FileName const masterFileName(Buffer const & buffer)
138 return buffer.masterBuffer()->fileName();
142 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
145 string const parentFileName(Buffer const & buffer)
147 return buffer.absFileName();
151 FileName const includedFileName(Buffer const & buffer,
152 InsetCommandParams const & params)
154 return makeAbsPath(to_utf8(params["filename"]),
155 onlyPath(parentFileName(buffer)));
159 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
161 if (label_str.empty())
163 InsetCommandParams icp(LABEL_CODE);
164 icp["name"] = label_str;
165 return new InsetLabel(buf, icp);
169 char_type replaceCommaInBraces(docstring & params)
171 // Code point from private use area
172 char_type private_char = 0xE000;
174 for (char_type & c : params) {
179 else if (c == ',' && count)
188 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
189 : InsetCommand(buf, p), include_label(uniqueID()),
190 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
191 set_label_(false), label_(0), child_buffer_(0)
193 preview_->connect([=](){ fileChanged(); });
195 if (isListings(params())) {
196 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
197 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
198 } else if (isInputOrInclude(params()) && buf)
203 InsetInclude::InsetInclude(InsetInclude const & other)
204 : InsetCommand(other), include_label(other.include_label),
205 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
206 set_label_(false), label_(0), child_buffer_(0)
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(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 //pass everything else up the chain
322 InsetCommand::doDispatch(cur, cmd);
328 void InsetInclude::editIncluded(string const & file)
330 string const ext = support::getExtension(file);
332 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
335 // tex file or other text file in verbatim mode
336 theFormats().edit(buffer(),
337 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
342 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
343 FuncStatus & flag) const
345 switch (cmd.action()) {
347 case LFUN_INSET_EDIT:
348 flag.setEnabled(true);
351 case LFUN_INSET_MODIFY:
352 if (cmd.getArg(0) == "changetype")
353 return InsetCommand::getStatus(cur, cmd, flag);
355 flag.setEnabled(true);
359 return InsetCommand::getStatus(cur, cmd, flag);
364 void InsetInclude::setParams(InsetCommandParams const & p)
366 // invalidate the cache
369 InsetCommand::setParams(p);
372 if (preview_->monitoring())
373 preview_->stopMonitoring();
375 if (type(params()) == INPUT)
376 add_preview(*preview_, *this, buffer());
380 bool InsetInclude::isChildIncluded() const
382 std::list<std::string> includeonlys =
383 buffer().params().getIncludedChildren();
384 if (includeonlys.empty())
386 return (std::find(includeonlys.begin(),
388 to_utf8(params()["filename"])) != includeonlys.end());
392 docstring InsetInclude::screenLabel() const
396 switch (type(params())) {
398 temp = buffer().B_("Input");
401 temp = buffer().B_("Verbatim Input");
404 temp = buffer().B_("Verbatim Input*");
407 if (isChildIncluded())
408 temp = buffer().B_("Include");
410 temp += buffer().B_("Include (excluded)");
413 temp = listings_label_;
416 LASSERT(false, temp = buffer().B_("Unknown"));
422 if (params()["filename"].empty())
425 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
431 Buffer * InsetInclude::getChildBuffer() const
433 Buffer * childBuffer = loadIfNeeded();
435 // FIXME RECURSIVE INCLUDE
436 // This isn't sufficient, as the inclusion could be downstream.
437 // But it'll have to do for now.
438 return (childBuffer == &buffer()) ? 0 : childBuffer;
442 Buffer * InsetInclude::loadIfNeeded() const
444 // This is for background export and preview. We don't even want to
445 // try to load the cloned child document again.
446 if (buffer().isClone())
447 return child_buffer_;
449 // Don't try to load it again if we failed before.
450 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
453 FileName const included_file = includedFileName(buffer(), params());
454 // Use cached Buffer if possible.
455 if (child_buffer_ != 0) {
456 if (theBufferList().isLoaded(child_buffer_)
457 // additional sanity check: make sure the Buffer really is
458 // associated with the file we want.
459 && child_buffer_ == theBufferList().getBuffer(included_file))
460 return child_buffer_;
461 // Buffer vanished, so invalidate cache and try to reload.
465 if (!isLyXFileName(included_file.absFileName()))
468 Buffer * child = theBufferList().getBuffer(included_file);
470 // the readonly flag can/will be wrong, not anymore I think.
471 if (!included_file.exists())
474 child = theBufferList().newBuffer(included_file.absFileName());
476 // Buffer creation is not possible.
479 // Set parent before loading, such that macros can be tracked
480 child->setParent(&buffer());
482 if (child->loadLyXFile() != Buffer::ReadSuccess) {
483 failedtoload_ = true;
485 //close the buffer we just opened
486 theBufferList().release(child);
490 if (!child->errorList("Parse").empty()) {
491 // FIXME: Do something.
494 // The file was already loaded, so, simply
495 // inform parent buffer about local macros.
496 Buffer const * parent = &buffer();
497 child->setParent(parent);
499 child->listMacroNames(macros);
500 MacroNameSet::const_iterator cit = macros.begin();
501 MacroNameSet::const_iterator end = macros.end();
502 for (; cit != end; ++cit)
503 parent->usermacros.insert(*cit);
506 // Cache the child buffer.
507 child_buffer_ = child;
512 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
514 string incfile = to_utf8(params()["filename"]);
516 // Do nothing if no file name has been specified
520 FileName const included_file = includedFileName(buffer(), params());
522 // Check we're not trying to include ourselves.
523 // FIXME RECURSIVE INCLUDE
524 // This isn't sufficient, as the inclusion could be downstream.
525 // But it'll have to do for now.
526 if (isInputOrInclude(params()) &&
527 buffer().absFileName() == included_file.absFileName())
529 Alert::error(_("Recursive input"),
530 bformat(_("Attempted to include file %1$s in itself! "
531 "Ignoring inclusion."), from_utf8(incfile)));
535 Buffer const * const masterBuffer = buffer().masterBuffer();
537 // if incfile is relative, make it relative to the master
539 if (!FileName::isAbsolute(incfile)) {
541 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
542 from_utf8(masterBuffer->filePath())));
545 string exppath = incfile;
546 if (!runparams.export_folder.empty()) {
547 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
548 FileName(exppath).onlyPath().createPath();
551 // write it to a file (so far the complete file)
555 if (type(params()) == LISTINGS) {
556 exportfile = exppath;
557 mangled = DocFileName(included_file).mangledFileName();
559 exportfile = changeExtension(exppath, ".tex");
560 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
566 else if (!runparams.silent)
567 ; // no warning wanted
568 else if (!isValidLaTeXFileName(incfile)) {
569 frontend::Alert::warning(_("Invalid filename"),
570 _("The following filename will cause troubles "
571 "when running the exported file through LaTeX: ") +
573 } else if (!isValidDVIFileName(incfile)) {
574 frontend::Alert::warning(_("Problematic filename for DVI"),
575 _("The following filename can cause troubles "
576 "when running the exported file through LaTeX "
577 "and opening the resulting DVI: ") +
578 from_utf8(incfile), true);
581 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
582 buffer().temppath() : masterBuffer->temppath()));
584 LYXERR(Debug::LATEX, "incfile:" << incfile);
585 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
586 LYXERR(Debug::LATEX, "writefile:" << writefile);
588 string const tex_format = flavor2format(runparams.flavor);
590 switch (type(params())) {
593 incfile = latex_path(incfile);
595 os << '\\' << from_ascii(params().getCmdName()) << '{'
596 << from_utf8(incfile) << '}';
600 runparams.exportdata->addExternalFile(tex_format, writefile,
603 // \input wants file with extension (default is .tex)
604 if (!isLyXFileName(included_file.absFileName())) {
605 incfile = latex_path(incfile);
607 os << '\\' << from_ascii(params().getCmdName())
608 << '{' << from_utf8(incfile) << '}';
610 incfile = changeExtension(incfile, ".tex");
611 incfile = latex_path(incfile);
613 os << '\\' << from_ascii(params().getCmdName())
614 << '{' << from_utf8(incfile) << '}';
619 // Here, listings and minted have sligthly different behaviors.
620 // Using listings, it is always possible to have a caption,
621 // even for non-floats. Using minted, only floats can have a
622 // caption. So, with minted we use the following strategy.
623 // If a caption was specified but the float parameter was not,
624 // we ourselves add a caption above the listing (because the
625 // listing comes from a file and might span several pages).
626 // Otherwise, if float was specified, the floating listing
627 // environment provided by minted is used. In either case, the
628 // label parameter is taken as the label by which the float
629 // can be referenced, otherwise it will have the meaning
630 // intended by minted. In this last case, the label will
631 // serve as a sort of caption that, however, will be shown
632 // by minted only if the frame parameter is also specified.
633 bool const use_minted = buffer().params().use_minted;
634 runparams.exportdata->addExternalFile(tex_format, writefile,
636 string const opt = to_utf8(params()["lstparams"]);
637 // opt is set in QInclude dialog and should have passed validation.
638 InsetListingsParams lstparams(opt);
639 docstring parameters = from_utf8(lstparams.params());
644 bool isfloat = lstparams.isFloat();
645 // We are going to split parameters at commas, so
646 // replace commas that are not parameter separators
647 // with a code point from the private use area
648 char_type comma = replaceCommaInBraces(parameters);
649 // Get float placement, language, caption, and
650 // label, then remove the relative options if minted.
651 vector<docstring> opts =
652 getVectorFromString(parameters, from_ascii(","), false);
653 vector<docstring> latexed_opts;
654 for (size_t i = 0; i < opts.size(); ++i) {
655 // Restore replaced commas
656 opts[i] = subst(opts[i], comma, ',');
657 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
658 if (prefixIs(opts[i], from_ascii("float=")))
659 placement = opts[i].substr(6);
660 opts.erase(opts.begin() + i--);
661 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
662 language = opts[i].substr(9);
663 opts.erase(opts.begin() + i--);
664 } else if (prefixIs(opts[i], from_ascii("caption="))) {
665 caption = params().prepareCommand(runparams, trim(opts[i].substr(8), "{}"),
666 ParamInfo::HANDLING_LATEXIFY);
667 opts.erase(opts.begin() + i--);
669 latexed_opts.push_back(from_ascii("caption=") + caption);
670 } else if (prefixIs(opts[i], from_ascii("label="))) {
671 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
672 ParamInfo::HANDLING_ESCAPE);
673 opts.erase(opts.begin() + i--);
675 latexed_opts.push_back(from_ascii("label={") + label + "}");
677 if (use_minted && !label.empty()) {
678 if (isfloat || !caption.empty())
679 label = trim(label, "{}");
681 opts.push_back(from_ascii("label=") + label);
684 if (!latexed_opts.empty())
685 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
686 parameters = getStringFromVector(opts, from_ascii(","));
687 if (language.empty())
688 language = from_ascii("TeX");
689 if (use_minted && isfloat) {
690 os << breakln << "\\begin{listing}";
691 if (!placement.empty())
692 os << '[' << placement << "]";
694 } else if (use_minted && !caption.empty()) {
695 os << breakln << "\\lyxmintcaption[t]{" << caption;
697 os << "\\label{" << label << "}";
700 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
701 if (!parameters.empty())
702 os << "[" << parameters << "]";
704 os << '{' << ascii_lowercase(language) << '}';
705 os << '{' << incfile << '}';
706 if (use_minted && isfloat) {
707 if (!caption.empty())
708 os << breakln << "\\caption{" << caption << "}";
710 os << breakln << "\\label{" << label << "}";
711 os << breakln << "\\end{listing}\n";
716 runparams.exportdata->addExternalFile(tex_format, writefile,
719 // \include don't want extension and demands that the
720 // file really have .tex
721 incfile = changeExtension(incfile, string());
722 incfile = latex_path(incfile);
724 os << '\\' << from_ascii(params().getCmdName()) << '{'
725 << from_utf8(incfile) << '}';
732 if (runparams.inComment || runparams.dryrun)
733 // Don't try to load or copy the file if we're
734 // in a comment or doing a dryrun
737 if (isInputOrInclude(params()) &&
738 isLyXFileName(included_file.absFileName())) {
739 // if it's a LyX file and we're inputting or including,
740 // try to load it so we can write the associated latex
742 Buffer * tmp = loadIfNeeded();
744 if (!runparams.silent) {
745 docstring text = bformat(_("Could not load included "
747 "Please, check whether it actually exists."),
748 included_file.displayName());
749 throw ExceptionMessage(ErrorException, _("Error: "),
755 if (!runparams.silent) {
756 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
758 docstring text = bformat(_("Included file `%1$s'\n"
759 "has textclass `%2$s'\n"
760 "while parent file has textclass `%3$s'."),
761 included_file.displayName(),
762 from_utf8(tmp->params().documentClass().name()),
763 from_utf8(masterBuffer->params().documentClass().name()));
764 Alert::warning(_("Different textclasses"), text, true);
767 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
768 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
769 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
770 docstring text = bformat(_("Included file `%1$s'\n"
771 "has use-non-TeX-fonts set to `%2$s'\n"
772 "while parent file has use-non-TeX-fonts set to `%3$s'."),
773 included_file.displayName(),
775 from_utf8(master_tf));
776 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
779 // Make sure modules used in child are all included in master
780 // FIXME It might be worth loading the children's modules into the master
781 // over in BufferParams rather than doing this check.
782 LayoutModuleList const masterModules = masterBuffer->params().getModules();
783 LayoutModuleList const childModules = tmp->params().getModules();
784 LayoutModuleList::const_iterator it = childModules.begin();
785 LayoutModuleList::const_iterator end = childModules.end();
786 for (; it != end; ++it) {
787 string const module = *it;
788 LayoutModuleList::const_iterator found =
789 find(masterModules.begin(), masterModules.end(), module);
790 if (found == masterModules.end()) {
791 docstring text = bformat(_("Included file `%1$s'\n"
792 "uses module `%2$s'\n"
793 "which is not used in parent file."),
794 included_file.displayName(), from_utf8(module));
795 Alert::warning(_("Module not found"), text, true);
800 tmp->markDepClean(masterBuffer->temppath());
802 // Don't assume the child's format is latex
803 string const inc_format = tmp->params().bufferFormat();
804 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
805 theFormats().extension(inc_format)));
807 // FIXME: handle non existing files
808 // The included file might be written in a different encoding
810 Encoding const * const oldEnc = runparams.encoding;
811 Language const * const oldLang = runparams.master_language;
812 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
813 // the children must be encoded in plain utf8!
814 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
815 encodings.fromLyXName("utf8-plain")
816 : &tmp->params().encoding();
817 runparams.master_language = buffer().params().language;
818 runparams.par_begin = 0;
819 runparams.par_end = tmp->paragraphs().size();
820 runparams.is_child = true;
821 Buffer::ExportStatus retval =
822 tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
823 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
824 if (retval == Buffer::ExportKilled && buffer().isClone() &&
825 buffer().isExporting()) {
826 // We really shouldn't get here, I don't think.
827 LYXERR0("No conversion exception?");
828 throw ConversionException();
830 else if (retval != Buffer::ExportSuccess) {
831 if (!runparams.silent) {
832 docstring msg = bformat(_("Included file `%1$s' "
833 "was not exported correctly.\n "
834 "LaTeX export is probably incomplete."),
835 included_file.displayName());
836 ErrorList const & el = tmp->errorList("Export");
838 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
839 msg, el.begin()->error, el.begin()->description);
840 throw ExceptionMessage(ErrorException, _("Error: "), msg);
843 runparams.encoding = oldEnc;
844 runparams.master_language = oldLang;
845 runparams.is_child = false;
847 // If needed, use converters to produce a latex file from the child
848 if (tmpwritefile != writefile) {
850 Converters::RetVal const retval =
851 theConverters().convert(tmp, tmpwritefile, writefile,
852 included_file, inc_format, tex_format, el);
853 if (retval == Converters::KILLED && buffer().isClone() &&
854 buffer().isExporting()) {
855 // We really shouldn't get here, I don't think.
856 LYXERR0("No conversion exception?");
857 throw ConversionException();
858 } else if (retval != Converters::SUCCESS && !runparams.silent) {
859 docstring msg = bformat(_("Included file `%1$s' "
860 "was not exported correctly.\n "
861 "LaTeX export is probably incomplete."),
862 included_file.displayName());
864 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
865 msg, el.begin()->error, el.begin()->description);
866 throw ExceptionMessage(ErrorException, _("Error: "), msg);
870 // In this case, it's not a LyX file, so we copy the file
871 // to the temp dir, so that .aux files etc. are not created
872 // in the original dir. Files included by this file will be
873 // found via either the environment variable TEXINPUTS, or
874 // input@path, see ../Buffer.cpp.
875 unsigned long const checksum_in = included_file.checksum();
876 unsigned long const checksum_out = writefile.checksum();
878 if (checksum_in != checksum_out) {
879 if (!included_file.copyTo(writefile)) {
882 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
883 "into the temporary directory."),
884 from_utf8(included_file.absFileName()))));
892 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
897 // For verbatim and listings, we just include the contents of the file as-is.
898 // In the case of listings, we wrap it in <pre>.
899 bool const listing = isListings(params());
900 if (listing || isVerbatim(params())) {
902 xs << html::StartTag("pre");
903 // FIXME: We don't know the encoding of the file, default to UTF-8.
904 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
906 xs << html::EndTag("pre");
910 // We don't (yet) know how to Input or Include non-LyX files.
911 // (If we wanted to get really arcane, we could run some tex2html
912 // converter on the included file. But that's just masochistic.)
913 FileName const included_file = includedFileName(buffer(), params());
914 if (!isLyXFileName(included_file.absFileName())) {
916 frontend::Alert::warning(_("Unsupported Inclusion"),
917 bformat(_("LyX does not know how to include non-LyX files when "
918 "generating HTML output. Offending file:\n%1$s"),
919 params()["filename"]));
923 // In the other cases, we will generate the HTML and include it.
925 // Check we're not trying to include ourselves.
926 // FIXME RECURSIVE INCLUDE
927 if (buffer().absFileName() == included_file.absFileName()) {
928 Alert::error(_("Recursive input"),
929 bformat(_("Attempted to include file %1$s in itself! "
930 "Ignoring inclusion."), params()["filename"]));
934 Buffer const * const ibuf = loadIfNeeded();
938 // are we generating only some paragraphs, or all of them?
939 bool const all_pars = !rp.dryrun ||
940 (rp.par_begin == 0 &&
941 rp.par_end == (int)buffer().text().paragraphs().size());
943 OutputParams op = rp;
947 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
949 xs << XHTMLStream::ESCAPE_NONE
950 << "<!-- Included file: "
951 << from_utf8(included_file.absFileName())
952 << XHTMLStream::ESCAPE_NONE
958 int InsetInclude::plaintext(odocstringstream & os,
959 OutputParams const & op, size_t) const
961 // just write the filename if we're making a tooltip or toc entry,
962 // or are generating this for advanced search
963 if (op.for_tooltip || op.for_toc || op.for_search) {
964 os << '[' << screenLabel() << '\n'
965 << getParam("filename") << "\n]";
966 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
969 if (isVerbatim(params()) || isListings(params())) {
970 os << '[' << screenLabel() << '\n'
971 // FIXME: We don't know the encoding of the file, default to UTF-8.
972 << includedFileName(buffer(), params()).fileContents("UTF-8")
974 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
977 Buffer const * const ibuf = loadIfNeeded();
979 docstring const str = '[' + screenLabel() + ']';
983 writePlaintextFile(*ibuf, os, op);
988 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
990 string incfile = to_utf8(params()["filename"]);
992 // Do nothing if no file name has been specified
996 string const included_file = includedFileName(buffer(), params()).absFileName();
998 // Check we're not trying to include ourselves.
999 // FIXME RECURSIVE INCLUDE
1000 // This isn't sufficient, as the inclusion could be downstream.
1001 // But it'll have to do for now.
1002 if (buffer().absFileName() == included_file) {
1003 Alert::error(_("Recursive input"),
1004 bformat(_("Attempted to include file %1$s in itself! "
1005 "Ignoring inclusion."), from_utf8(incfile)));
1009 string exppath = incfile;
1010 if (!runparams.export_folder.empty()) {
1011 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
1012 FileName(exppath).onlyPath().createPath();
1015 // write it to a file (so far the complete file)
1016 string const exportfile = changeExtension(exppath, ".sgml");
1017 DocFileName writefile(changeExtension(included_file, ".sgml"));
1019 Buffer * tmp = loadIfNeeded();
1021 string const mangled = writefile.mangledFileName();
1022 writefile = makeAbsPath(mangled,
1023 buffer().masterBuffer()->temppath());
1024 if (!runparams.nice)
1027 LYXERR(Debug::LATEX, "incfile:" << incfile);
1028 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
1029 LYXERR(Debug::LATEX, "writefile:" << writefile);
1031 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
1034 runparams.exportdata->addExternalFile("docbook", writefile,
1036 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1039 if (isVerbatim(params()) || isListings(params())) {
1040 os << "<inlinegraphic fileref=\""
1041 << '&' << include_label << ';'
1042 << "\" format=\"linespecific\">";
1044 os << '&' << include_label << ';';
1050 void InsetInclude::validate(LaTeXFeatures & features) const
1052 LATTEST(&buffer() == &features.buffer());
1054 string incfile = to_utf8(params()["filename"]);
1055 string const included_file =
1056 includedFileName(buffer(), params()).absFileName();
1059 if (isLyXFileName(included_file))
1060 writefile = changeExtension(included_file, ".sgml");
1062 writefile = included_file;
1064 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1065 incfile = DocFileName(writefile).mangledFileName();
1066 writefile = makeAbsPath(incfile,
1067 buffer().masterBuffer()->temppath()).absFileName();
1070 features.includeFile(include_label, writefile);
1072 features.useInsetLayout(getLayout());
1073 if (isVerbatim(params()))
1074 features.require("verbatim");
1075 else if (isListings(params())) {
1076 if (buffer().params().use_minted) {
1077 features.require("minted");
1078 string const opts = to_utf8(params()["lstparams"]);
1079 InsetListingsParams lstpars(opts);
1080 if (!lstpars.isFloat() && contains(opts, "caption="))
1081 features.require("lyxmintcaption");
1083 features.require("listings");
1086 // Here we must do the fun stuff...
1087 // Load the file in the include if it needs
1089 Buffer * const tmp = loadIfNeeded();
1091 // the file is loaded
1092 // make sure the buffer isn't us
1093 // FIXME RECURSIVE INCLUDES
1094 // This is not sufficient, as recursive includes could be
1095 // more than a file away. But it will do for now.
1096 if (tmp && tmp != &buffer()) {
1097 // We must temporarily change features.buffer,
1098 // otherwise it would always be the master buffer,
1099 // and nested includes would not work.
1100 features.setBuffer(*tmp);
1101 // Maybe this is already a child
1102 bool const is_child =
1103 features.runparams().is_child;
1104 features.runparams().is_child = true;
1105 tmp->validate(features);
1106 features.runparams().is_child = is_child;
1107 features.setBuffer(buffer());
1113 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1115 Buffer * child = loadIfNeeded();
1118 // FIXME RECURSIVE INCLUDE
1119 // This isn't sufficient, as the inclusion could be downstream.
1120 // But it'll have to do for now.
1121 if (child == &buffer())
1123 child->collectBibKeys(checkedFiles);
1127 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1129 LBUFERR(mi.base.bv);
1131 bool use_preview = false;
1132 if (RenderPreview::previewText()) {
1133 graphics::PreviewImage const * pimage =
1134 preview_->getPreviewImage(mi.base.bv->buffer());
1135 use_preview = pimage && pimage->image();
1139 preview_->metrics(mi, dim);
1143 button_.update(screenLabel(), true, false);
1145 button_.metrics(mi, dim);
1148 Box b(0, dim.wid, -dim.asc, dim.des);
1153 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1155 LBUFERR(pi.base.bv);
1157 bool use_preview = false;
1158 if (RenderPreview::previewText()) {
1159 graphics::PreviewImage const * pimage =
1160 preview_->getPreviewImage(pi.base.bv->buffer());
1161 use_preview = pimage && pimage->image();
1165 preview_->draw(pi, x, y);
1167 button_.draw(pi, x, y);
1171 void InsetInclude::write(ostream & os) const
1173 params().Write(os, &buffer());
1177 string InsetInclude::contextMenuName() const
1179 return "context-include";
1183 Inset::DisplayType InsetInclude::display() const
1185 return type(params()) == INPUT ? Inline : AlignCenter;
1189 docstring InsetInclude::layoutName() const
1191 if (isListings(params()))
1192 return from_ascii("IncludeListings");
1193 return InsetCommand::layoutName();
1201 void InsetInclude::fileChanged() const
1203 Buffer const * const buffer = updateFrontend();
1207 preview_->removePreview(*buffer);
1208 add_preview(*preview_, *this, *buffer);
1209 preview_->startLoading(*buffer);
1215 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1217 FileName const included_file = includedFileName(buffer, params);
1219 return type(params) == INPUT && params.preview() &&
1220 included_file.isReadableFile();
1224 docstring latexString(InsetInclude const & inset)
1226 odocstringstream ods;
1228 // We don't need to set runparams.encoding since this will be done
1229 // by latex() anyway.
1230 OutputParams runparams(0);
1231 runparams.flavor = OutputParams::LATEX;
1232 runparams.for_preview = true;
1233 inset.latex(os, runparams);
1239 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1240 Buffer const & buffer)
1242 InsetCommandParams const & params = inset.params();
1243 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1244 renderer.setAbsFile(includedFileName(buffer, params));
1245 docstring const snippet = latexString(inset);
1246 renderer.addPreview(snippet, buffer);
1253 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1254 graphics::PreviewLoader & ploader) const
1256 Buffer const & buffer = ploader.buffer();
1257 if (!preview_wanted(params(), buffer))
1259 preview_->setAbsFile(includedFileName(buffer, params()));
1260 docstring const snippet = latexString(*this);
1261 preview_->addPreview(snippet, ploader);
1265 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1266 UpdateType utype, TocBackend & backend) const
1268 if (isListings(params())) {
1270 label_->addToToc(cpit, output_active, utype, backend);
1271 TocBuilder & b = backend.builder("listing");
1272 b.pushItem(cpit, screenLabel(), output_active);
1273 InsetListingsParams p(to_utf8(params()["lstparams"]));
1274 b.argumentItem(from_utf8(p.getParamValue("caption")));
1277 Buffer const * const childbuffer = getChildBuffer();
1279 TocBuilder & b = backend.builder("child");
1280 docstring str = childbuffer ? childbuffer->fileName().displayName()
1282 b.pushItem(cpit, str, output_active);
1288 // Update the child's tocBackend. The outliner uses the master's, but
1289 // the navigation menu uses the child's.
1290 childbuffer->tocBackend().update(output_active, utype);
1291 // Include Tocs from children
1292 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1294 //Copy missing outliner names (though the user has been warned against
1295 //having different document class and module selection between master
1297 for (pair<string, docstring> const & name
1298 : childbuffer->params().documentClass().outlinerNames())
1299 backend.addName(name.first, translateIfPossible(name.second));
1304 void InsetInclude::updateCommand()
1309 docstring old_label = label_->getParam("name");
1310 label_->updateLabel(old_label);
1311 // the label might have been adapted (duplicate)
1312 docstring new_label = label_->getParam("name");
1313 if (old_label == new_label)
1316 // update listings parameters...
1317 InsetCommandParams p(INCLUDE_CODE);
1319 InsetListingsParams par(to_utf8(params()["lstparams"]));
1320 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1321 p["lstparams"] = from_utf8(par.params());
1326 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1328 button_.update(screenLabel(), true, false);
1330 Buffer const * const childbuffer = getChildBuffer();
1332 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1335 if (!isListings(params()))
1339 label_->updateBuffer(it, utype);
1341 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1342 if (par.getParamValue("caption").empty()) {
1343 listings_label_ = buffer().B_("Program Listing");
1346 Buffer const & master = *buffer().masterBuffer();
1347 Counters & counters = master.params().documentClass().counters();
1348 docstring const cnt = from_ascii("listing");
1349 listings_label_ = master.B_("Program Listing");
1350 if (counters.hasCounter(cnt)) {
1351 counters.step(cnt, utype);
1352 listings_label_ += " " + convert<docstring>(counters.value(cnt));