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);
171 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
172 : InsetCommand(buf, p), include_label(uniqueID()),
173 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
174 set_label_(false), label_(0), child_buffer_(0)
176 preview_->connect([=](){ fileChanged(); });
178 if (isListings(params())) {
179 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
180 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
181 } else if (isInputOrInclude(params()) && buf)
186 InsetInclude::InsetInclude(InsetInclude const & other)
187 : InsetCommand(other), include_label(other.include_label),
188 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
189 set_label_(false), label_(0), child_buffer_(0)
191 preview_->connect([=](){ fileChanged(); });
194 label_ = new InsetLabel(*other.label_);
198 InsetInclude::~InsetInclude()
204 void InsetInclude::setBuffer(Buffer & buffer)
206 InsetCommand::setBuffer(buffer);
208 label_->setBuffer(buffer);
212 void InsetInclude::setChildBuffer(Buffer * buffer)
214 child_buffer_ = buffer;
218 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
221 // This is only correct for the case of listings, but it'll do for now.
222 // In the other cases, this second parameter should just be empty.
223 static ParamInfo param_info_;
224 if (param_info_.empty()) {
225 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
226 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
227 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
233 bool InsetInclude::isCompatibleCommand(string const & s)
235 return type(s) != NONE;
239 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
241 switch (cmd.action()) {
243 case LFUN_INSET_EDIT: {
244 editIncluded(to_utf8(params()["filename"]));
248 case LFUN_INSET_MODIFY: {
249 // It should be OK just to invalidate the cache in setParams()
251 // child_buffer_ = 0;
252 InsetCommandParams p(INCLUDE_CODE);
253 if (cmd.getArg(0) == "changetype") {
255 InsetCommand::doDispatch(cur, cmd);
258 InsetCommand::string2params(to_utf8(cmd.argument()), p);
259 if (!p.getCmdName().empty()) {
261 InsetListingsParams new_params(to_utf8(p["lstparams"]));
262 docstring const new_label =
263 from_utf8(new_params.getParamValue("label"));
265 if (new_label.empty()) {
271 old_label = label_->getParam("name");
273 label_ = createLabel(buffer_, new_label);
274 label_->setBuffer(buffer());
277 if (new_label != old_label) {
278 label_->updateLabelAndRefs(new_label, &cur);
279 // the label might have been adapted (duplicate)
280 if (new_label != label_->getParam("name")) {
281 new_params.addParam("label", "{" +
282 to_utf8(label_->getParam("name")) + "}", true);
283 p["lstparams"] = from_utf8(new_params.params());
290 cur.forceBufferUpdate();
292 cur.noScreenUpdate();
296 //pass everything else up the chain
298 InsetCommand::doDispatch(cur, cmd);
304 void InsetInclude::editIncluded(string const & file)
306 string const ext = support::getExtension(file);
308 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
311 // tex file or other text file in verbatim mode
312 theFormats().edit(buffer(),
313 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
318 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
319 FuncStatus & flag) const
321 switch (cmd.action()) {
323 case LFUN_INSET_EDIT:
324 flag.setEnabled(true);
327 case LFUN_INSET_MODIFY:
328 if (cmd.getArg(0) == "changetype")
329 return InsetCommand::getStatus(cur, cmd, flag);
331 flag.setEnabled(true);
335 return InsetCommand::getStatus(cur, cmd, flag);
340 void InsetInclude::setParams(InsetCommandParams const & p)
342 // invalidate the cache
345 InsetCommand::setParams(p);
348 if (preview_->monitoring())
349 preview_->stopMonitoring();
351 if (type(params()) == INPUT)
352 add_preview(*preview_, *this, buffer());
356 bool InsetInclude::isChildIncluded() const
358 std::list<std::string> includeonlys =
359 buffer().params().getIncludedChildren();
360 if (includeonlys.empty())
362 return (std::find(includeonlys.begin(),
364 to_utf8(params()["filename"])) != includeonlys.end());
368 docstring InsetInclude::screenLabel() const
372 switch (type(params())) {
374 temp = buffer().B_("Input");
377 temp = buffer().B_("Verbatim Input");
380 temp = buffer().B_("Verbatim Input*");
383 if (isChildIncluded())
384 temp = buffer().B_("Include");
386 temp += buffer().B_("Include (excluded)");
389 temp = listings_label_;
392 LASSERT(false, temp = buffer().B_("Unknown"));
398 if (params()["filename"].empty())
401 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
407 Buffer * InsetInclude::getChildBuffer() const
409 Buffer * childBuffer = loadIfNeeded();
411 // FIXME RECURSIVE INCLUDE
412 // This isn't sufficient, as the inclusion could be downstream.
413 // But it'll have to do for now.
414 return (childBuffer == &buffer()) ? 0 : childBuffer;
418 Buffer * InsetInclude::loadIfNeeded() const
420 // This is for background export and preview. We don't even want to
421 // try to load the cloned child document again.
422 if (buffer().isClone())
423 return child_buffer_;
425 // Don't try to load it again if we failed before.
426 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
429 FileName const included_file = includedFileName(buffer(), params());
430 // Use cached Buffer if possible.
431 if (child_buffer_ != 0) {
432 if (theBufferList().isLoaded(child_buffer_)
433 // additional sanity check: make sure the Buffer really is
434 // associated with the file we want.
435 && child_buffer_ == theBufferList().getBuffer(included_file))
436 return child_buffer_;
437 // Buffer vanished, so invalidate cache and try to reload.
441 if (!isLyXFileName(included_file.absFileName()))
444 Buffer * child = theBufferList().getBuffer(included_file);
446 // the readonly flag can/will be wrong, not anymore I think.
447 if (!included_file.exists())
450 child = theBufferList().newBuffer(included_file.absFileName());
452 // Buffer creation is not possible.
455 // Set parent before loading, such that macros can be tracked
456 child->setParent(&buffer());
458 if (child->loadLyXFile() != Buffer::ReadSuccess) {
459 failedtoload_ = true;
461 //close the buffer we just opened
462 theBufferList().release(child);
466 if (!child->errorList("Parse").empty()) {
467 // FIXME: Do something.
470 // The file was already loaded, so, simply
471 // inform parent buffer about local macros.
472 Buffer const * parent = &buffer();
473 child->setParent(parent);
475 child->listMacroNames(macros);
476 MacroNameSet::const_iterator cit = macros.begin();
477 MacroNameSet::const_iterator end = macros.end();
478 for (; cit != end; ++cit)
479 parent->usermacros.insert(*cit);
482 // Cache the child buffer.
483 child_buffer_ = child;
488 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
490 string incfile = to_utf8(params()["filename"]);
492 // Do nothing if no file name has been specified
496 FileName const included_file = includedFileName(buffer(), params());
498 // Check we're not trying to include ourselves.
499 // FIXME RECURSIVE INCLUDE
500 // This isn't sufficient, as the inclusion could be downstream.
501 // But it'll have to do for now.
502 if (isInputOrInclude(params()) &&
503 buffer().absFileName() == included_file.absFileName())
505 Alert::error(_("Recursive input"),
506 bformat(_("Attempted to include file %1$s in itself! "
507 "Ignoring inclusion."), from_utf8(incfile)));
511 Buffer const * const masterBuffer = buffer().masterBuffer();
513 // if incfile is relative, make it relative to the master
515 if (!FileName::isAbsolute(incfile)) {
517 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
518 from_utf8(masterBuffer->filePath())));
521 string exppath = incfile;
522 if (!runparams.export_folder.empty()) {
523 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
524 FileName(exppath).onlyPath().createPath();
527 // write it to a file (so far the complete file)
531 if (type(params()) == LISTINGS) {
532 exportfile = exppath;
533 mangled = DocFileName(included_file).mangledFileName();
535 exportfile = changeExtension(exppath, ".tex");
536 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
542 else if (!runparams.silent)
543 ; // no warning wanted
544 else if (!isValidLaTeXFileName(incfile)) {
545 frontend::Alert::warning(_("Invalid filename"),
546 _("The following filename will cause troubles "
547 "when running the exported file through LaTeX: ") +
549 } else if (!isValidDVIFileName(incfile)) {
550 frontend::Alert::warning(_("Problematic filename for DVI"),
551 _("The following filename can cause troubles "
552 "when running the exported file through LaTeX "
553 "and opening the resulting DVI: ") +
554 from_utf8(incfile), true);
557 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
558 buffer().temppath() : masterBuffer->temppath()));
560 LYXERR(Debug::LATEX, "incfile:" << incfile);
561 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
562 LYXERR(Debug::LATEX, "writefile:" << writefile);
564 string const tex_format = flavor2format(runparams.flavor);
566 switch (type(params())) {
569 incfile = latex_path(incfile);
571 os << '\\' << from_ascii(params().getCmdName()) << '{'
572 << from_utf8(incfile) << '}';
576 runparams.exportdata->addExternalFile(tex_format, writefile,
579 // \input wants file with extension (default is .tex)
580 if (!isLyXFileName(included_file.absFileName())) {
581 incfile = latex_path(incfile);
583 os << '\\' << from_ascii(params().getCmdName())
584 << '{' << from_utf8(incfile) << '}';
586 incfile = changeExtension(incfile, ".tex");
587 incfile = latex_path(incfile);
589 os << '\\' << from_ascii(params().getCmdName())
590 << '{' << from_utf8(incfile) << '}';
595 // Here, listings and minted have sligthly different behaviors.
596 // Using listings, it is always possible to have a caption,
597 // even for non-floats. Using minted, only floats can have a
598 // caption. So, with minted we use the following strategy.
599 // If a caption was specified but the float parameter was not,
600 // we ourselves add a caption above the listing (because the
601 // listing comes from a file and might span several pages).
602 // Otherwise, if float was specified, the floating listing
603 // environment provided by minted is used. In either case, the
604 // label parameter is taken as the label by which the float
605 // can be referenced, otherwise it will have the meaning
606 // intended by minted. In this last case, the label will
607 // serve as a sort of caption that, however, will be shown
608 // by minted only if the frame parameter is also specified.
609 bool const use_minted = buffer().params().use_minted;
610 runparams.exportdata->addExternalFile(tex_format, writefile,
612 string const opt = to_utf8(params()["lstparams"]);
613 // opt is set in QInclude dialog and should have passed validation.
614 InsetListingsParams lstparams(opt);
615 docstring parameters = from_utf8(lstparams.params());
620 bool isfloat = lstparams.isFloat();
621 // Get float placement, language, caption, and
622 // label, then remove the relative options if minted.
623 vector<docstring> opts =
624 getVectorFromString(parameters, from_ascii(","), false);
625 vector<docstring> latexed_opts;
626 for (size_t i = 0; i < opts.size(); ++i) {
627 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
628 if (prefixIs(opts[i], from_ascii("float=")))
629 placement = opts[i].substr(6);
630 opts.erase(opts.begin() + i--);
631 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
632 language = opts[i].substr(9);
633 opts.erase(opts.begin() + i--);
634 } else if (prefixIs(opts[i], from_ascii("caption="))) {
635 caption = params().prepareCommand(runparams, trim(opts[i].substr(8), "{}"),
636 ParamInfo::HANDLING_LATEXIFY);
637 opts.erase(opts.begin() + i--);
639 latexed_opts.push_back(from_ascii("caption=") + caption);
640 } else if (prefixIs(opts[i], from_ascii("label="))) {
641 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
642 ParamInfo::HANDLING_ESCAPE);
643 opts.erase(opts.begin() + i--);
645 latexed_opts.push_back(from_ascii("label={") + label + "}");
647 if (use_minted && !label.empty()) {
648 if (isfloat || !caption.empty())
649 label = trim(label, "{}");
651 opts.push_back(from_ascii("label=") + label);
654 if (!latexed_opts.empty())
655 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
656 parameters = getStringFromVector(opts, from_ascii(","));
657 if (language.empty())
658 language = from_ascii("TeX");
659 if (use_minted && isfloat) {
660 os << breakln << "\\begin{listing}";
661 if (!placement.empty())
662 os << '[' << placement << "]";
664 } else if (use_minted && !caption.empty()) {
665 os << breakln << "\\lyxmintcaption[t]{" << caption;
667 os << "\\label{" << label << "}";
670 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
671 if (!parameters.empty())
672 os << "[" << parameters << "]";
674 os << '{' << ascii_lowercase(language) << '}';
675 os << '{' << incfile << '}';
676 if (use_minted && isfloat) {
677 if (!caption.empty())
678 os << breakln << "\\caption{" << caption << "}";
680 os << breakln << "\\label{" << label << "}";
681 os << breakln << "\\end{listing}\n";
686 runparams.exportdata->addExternalFile(tex_format, writefile,
689 // \include don't want extension and demands that the
690 // file really have .tex
691 incfile = changeExtension(incfile, string());
692 incfile = latex_path(incfile);
694 os << '\\' << from_ascii(params().getCmdName()) << '{'
695 << from_utf8(incfile) << '}';
702 if (runparams.inComment || runparams.dryrun)
703 // Don't try to load or copy the file if we're
704 // in a comment or doing a dryrun
707 if (isInputOrInclude(params()) &&
708 isLyXFileName(included_file.absFileName())) {
709 // if it's a LyX file and we're inputting or including,
710 // try to load it so we can write the associated latex
712 Buffer * tmp = loadIfNeeded();
714 if (!runparams.silent) {
715 docstring text = bformat(_("Could not load included "
717 "Please, check whether it actually exists."),
718 included_file.displayName());
719 throw ExceptionMessage(ErrorException, _("Error: "),
725 if (!runparams.silent) {
726 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
728 docstring text = bformat(_("Included file `%1$s'\n"
729 "has textclass `%2$s'\n"
730 "while parent file has textclass `%3$s'."),
731 included_file.displayName(),
732 from_utf8(tmp->params().documentClass().name()),
733 from_utf8(masterBuffer->params().documentClass().name()));
734 Alert::warning(_("Different textclasses"), text, true);
737 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
738 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
739 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
740 docstring text = bformat(_("Included file `%1$s'\n"
741 "has use-non-TeX-fonts set to `%2$s'\n"
742 "while parent file has use-non-TeX-fonts set to `%3$s'."),
743 included_file.displayName(),
745 from_utf8(master_tf));
746 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
749 // Make sure modules used in child are all included in master
750 // FIXME It might be worth loading the children's modules into the master
751 // over in BufferParams rather than doing this check.
752 LayoutModuleList const masterModules = masterBuffer->params().getModules();
753 LayoutModuleList const childModules = tmp->params().getModules();
754 LayoutModuleList::const_iterator it = childModules.begin();
755 LayoutModuleList::const_iterator end = childModules.end();
756 for (; it != end; ++it) {
757 string const module = *it;
758 LayoutModuleList::const_iterator found =
759 find(masterModules.begin(), masterModules.end(), module);
760 if (found == masterModules.end()) {
761 docstring text = bformat(_("Included file `%1$s'\n"
762 "uses module `%2$s'\n"
763 "which is not used in parent file."),
764 included_file.displayName(), from_utf8(module));
765 Alert::warning(_("Module not found"), text);
770 tmp->markDepClean(masterBuffer->temppath());
772 // Don't assume the child's format is latex
773 string const inc_format = tmp->params().bufferFormat();
774 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
775 theFormats().extension(inc_format)));
777 // FIXME: handle non existing files
778 // The included file might be written in a different encoding
780 Encoding const * const oldEnc = runparams.encoding;
781 Language const * const oldLang = runparams.master_language;
782 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
783 // the children must be encoded in plain utf8!
784 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
785 encodings.fromLyXName("utf8-plain")
786 : &tmp->params().encoding();
787 runparams.master_language = buffer().params().language;
788 runparams.par_begin = 0;
789 runparams.par_end = tmp->paragraphs().size();
790 runparams.is_child = true;
791 Buffer::ExportStatus retval =
792 tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
793 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
794 if (retval == Buffer::ExportKilled && buffer().isClone() &&
795 buffer().isExporting()) {
796 // We really shouldn't get here, I don't think.
797 LYXERR0("No conversion exception?");
798 throw ConversionException();
800 else if (retval != Buffer::ExportSuccess) {
801 if (!runparams.silent) {
802 docstring msg = bformat(_("Included file `%1$s' "
803 "was not exported correctly.\n "
804 "LaTeX export is probably incomplete."),
805 included_file.displayName());
806 ErrorList const & el = tmp->errorList("Export");
808 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
809 msg, el.begin()->error,
810 el.begin()->description);
811 throw ExceptionMessage(ErrorException, _("Error: "),
815 runparams.encoding = oldEnc;
816 runparams.master_language = oldLang;
817 runparams.is_child = false;
819 // If needed, use converters to produce a latex file from the child
820 if (tmpwritefile != writefile) {
822 Converters::RetVal const retval =
823 theConverters().convert(tmp, tmpwritefile, writefile,
824 included_file, inc_format, tex_format, el);
825 if (retval == Converters::KILLED && buffer().isClone() &&
826 buffer().isExporting()) {
827 // We really shouldn't get here, I don't think.
828 LYXERR0("No conversion exception?");
829 throw ConversionException();
830 } else if (retval != Converters::SUCCESS && !runparams.silent) {
831 docstring msg = bformat(_("Included file `%1$s' "
832 "was not exported correctly.\n "
833 "LaTeX export is probably incomplete."),
834 included_file.displayName());
836 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
837 msg, el.begin()->error,
838 el.begin()->description);
839 throw ExceptionMessage(ErrorException, _("Error: "),
844 // In this case, it's not a LyX file, so we copy the file
845 // to the temp dir, so that .aux files etc. are not created
846 // in the original dir. Files included by this file will be
847 // found via either the environment variable TEXINPUTS, or
848 // input@path, see ../Buffer.cpp.
849 unsigned long const checksum_in = included_file.checksum();
850 unsigned long const checksum_out = writefile.checksum();
852 if (checksum_in != checksum_out) {
853 if (!included_file.copyTo(writefile)) {
856 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
857 "into the temporary directory."),
858 from_utf8(included_file.absFileName()))));
866 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
871 // For verbatim and listings, we just include the contents of the file as-is.
872 // In the case of listings, we wrap it in <pre>.
873 bool const listing = isListings(params());
874 if (listing || isVerbatim(params())) {
876 xs << html::StartTag("pre");
877 // FIXME: We don't know the encoding of the file, default to UTF-8.
878 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
880 xs << html::EndTag("pre");
884 // We don't (yet) know how to Input or Include non-LyX files.
885 // (If we wanted to get really arcane, we could run some tex2html
886 // converter on the included file. But that's just masochistic.)
887 FileName const included_file = includedFileName(buffer(), params());
888 if (!isLyXFileName(included_file.absFileName())) {
890 frontend::Alert::warning(_("Unsupported Inclusion"),
891 bformat(_("LyX does not know how to include non-LyX files when "
892 "generating HTML output. Offending file:\n%1$s"),
893 params()["filename"]));
897 // In the other cases, we will generate the HTML and include it.
899 // Check we're not trying to include ourselves.
900 // FIXME RECURSIVE INCLUDE
901 if (buffer().absFileName() == included_file.absFileName()) {
902 Alert::error(_("Recursive input"),
903 bformat(_("Attempted to include file %1$s in itself! "
904 "Ignoring inclusion."), params()["filename"]));
908 Buffer const * const ibuf = loadIfNeeded();
912 // are we generating only some paragraphs, or all of them?
913 bool const all_pars = !rp.dryrun ||
914 (rp.par_begin == 0 &&
915 rp.par_end == (int)buffer().text().paragraphs().size());
917 OutputParams op = rp;
921 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
923 xs << XHTMLStream::ESCAPE_NONE
924 << "<!-- Included file: "
925 << from_utf8(included_file.absFileName())
926 << XHTMLStream::ESCAPE_NONE
932 int InsetInclude::plaintext(odocstringstream & os,
933 OutputParams const & op, size_t) const
935 // just write the filename if we're making a tooltip or toc entry,
936 // or are generating this for advanced search
937 if (op.for_tooltip || op.for_toc || op.for_search) {
938 os << '[' << screenLabel() << '\n'
939 << getParam("filename") << "\n]";
940 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
943 if (isVerbatim(params()) || isListings(params())) {
944 os << '[' << screenLabel() << '\n'
945 // FIXME: We don't know the encoding of the file, default to UTF-8.
946 << includedFileName(buffer(), params()).fileContents("UTF-8")
948 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
951 Buffer const * const ibuf = loadIfNeeded();
953 docstring const str = '[' + screenLabel() + ']';
957 writePlaintextFile(*ibuf, os, op);
962 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
964 string incfile = to_utf8(params()["filename"]);
966 // Do nothing if no file name has been specified
970 string const included_file = includedFileName(buffer(), params()).absFileName();
972 // Check we're not trying to include ourselves.
973 // FIXME RECURSIVE INCLUDE
974 // This isn't sufficient, as the inclusion could be downstream.
975 // But it'll have to do for now.
976 if (buffer().absFileName() == included_file) {
977 Alert::error(_("Recursive input"),
978 bformat(_("Attempted to include file %1$s in itself! "
979 "Ignoring inclusion."), from_utf8(incfile)));
983 string exppath = incfile;
984 if (!runparams.export_folder.empty()) {
985 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
986 FileName(exppath).onlyPath().createPath();
989 // write it to a file (so far the complete file)
990 string const exportfile = changeExtension(exppath, ".sgml");
991 DocFileName writefile(changeExtension(included_file, ".sgml"));
993 Buffer * tmp = loadIfNeeded();
995 string const mangled = writefile.mangledFileName();
996 writefile = makeAbsPath(mangled,
997 buffer().masterBuffer()->temppath());
1001 LYXERR(Debug::LATEX, "incfile:" << incfile);
1002 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
1003 LYXERR(Debug::LATEX, "writefile:" << writefile);
1005 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
1008 runparams.exportdata->addExternalFile("docbook", writefile,
1010 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1013 if (isVerbatim(params()) || isListings(params())) {
1014 os << "<inlinegraphic fileref=\""
1015 << '&' << include_label << ';'
1016 << "\" format=\"linespecific\">";
1018 os << '&' << include_label << ';';
1024 void InsetInclude::validate(LaTeXFeatures & features) const
1026 LATTEST(&buffer() == &features.buffer());
1028 string incfile = to_utf8(params()["filename"]);
1029 string const included_file =
1030 includedFileName(buffer(), params()).absFileName();
1033 if (isLyXFileName(included_file))
1034 writefile = changeExtension(included_file, ".sgml");
1036 writefile = included_file;
1038 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1039 incfile = DocFileName(writefile).mangledFileName();
1040 writefile = makeAbsPath(incfile,
1041 buffer().masterBuffer()->temppath()).absFileName();
1044 features.includeFile(include_label, writefile);
1046 features.useInsetLayout(getLayout());
1047 if (isVerbatim(params()))
1048 features.require("verbatim");
1049 else if (isListings(params())) {
1050 if (buffer().params().use_minted) {
1051 features.require("minted");
1052 string const opts = to_utf8(params()["lstparams"]);
1053 InsetListingsParams lstpars(opts);
1054 if (!lstpars.isFloat() && contains(opts, "caption="))
1055 features.require("lyxmintcaption");
1057 features.require("listings");
1060 // Here we must do the fun stuff...
1061 // Load the file in the include if it needs
1063 Buffer * const tmp = loadIfNeeded();
1065 // the file is loaded
1066 // make sure the buffer isn't us
1067 // FIXME RECURSIVE INCLUDES
1068 // This is not sufficient, as recursive includes could be
1069 // more than a file away. But it will do for now.
1070 if (tmp && tmp != &buffer()) {
1071 // We must temporarily change features.buffer,
1072 // otherwise it would always be the master buffer,
1073 // and nested includes would not work.
1074 features.setBuffer(*tmp);
1075 // Maybe this is already a child
1076 bool const is_child =
1077 features.runparams().is_child;
1078 features.runparams().is_child = true;
1079 tmp->validate(features);
1080 features.runparams().is_child = is_child;
1081 features.setBuffer(buffer());
1087 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1089 Buffer * child = loadIfNeeded();
1092 // FIXME RECURSIVE INCLUDE
1093 // This isn't sufficient, as the inclusion could be downstream.
1094 // But it'll have to do for now.
1095 if (child == &buffer())
1097 child->collectBibKeys(checkedFiles);
1101 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1103 LBUFERR(mi.base.bv);
1105 bool use_preview = false;
1106 if (RenderPreview::previewText()) {
1107 graphics::PreviewImage const * pimage =
1108 preview_->getPreviewImage(mi.base.bv->buffer());
1109 use_preview = pimage && pimage->image();
1113 preview_->metrics(mi, dim);
1117 button_.update(screenLabel(), true, false);
1119 button_.metrics(mi, dim);
1122 Box b(0, dim.wid, -dim.asc, dim.des);
1127 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1129 LBUFERR(pi.base.bv);
1131 bool use_preview = false;
1132 if (RenderPreview::previewText()) {
1133 graphics::PreviewImage const * pimage =
1134 preview_->getPreviewImage(pi.base.bv->buffer());
1135 use_preview = pimage && pimage->image();
1139 preview_->draw(pi, x, y);
1141 button_.draw(pi, x, y);
1145 void InsetInclude::write(ostream & os) const
1147 params().Write(os, &buffer());
1151 string InsetInclude::contextMenuName() const
1153 return "context-include";
1157 Inset::DisplayType InsetInclude::display() const
1159 return type(params()) == INPUT ? Inline : AlignCenter;
1163 docstring InsetInclude::layoutName() const
1165 if (isListings(params()))
1166 return from_ascii("IncludeListings");
1167 return InsetCommand::layoutName();
1175 void InsetInclude::fileChanged() const
1177 Buffer const * const buffer = updateFrontend();
1181 preview_->removePreview(*buffer);
1182 add_preview(*preview_, *this, *buffer);
1183 preview_->startLoading(*buffer);
1189 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1191 FileName const included_file = includedFileName(buffer, params);
1193 return type(params) == INPUT && params.preview() &&
1194 included_file.isReadableFile();
1198 docstring latexString(InsetInclude const & inset)
1200 odocstringstream ods;
1202 // We don't need to set runparams.encoding since this will be done
1203 // by latex() anyway.
1204 OutputParams runparams(0);
1205 runparams.flavor = OutputParams::LATEX;
1206 runparams.for_preview = true;
1207 inset.latex(os, runparams);
1213 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1214 Buffer const & buffer)
1216 InsetCommandParams const & params = inset.params();
1217 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1218 renderer.setAbsFile(includedFileName(buffer, params));
1219 docstring const snippet = latexString(inset);
1220 renderer.addPreview(snippet, buffer);
1227 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1228 graphics::PreviewLoader & ploader) const
1230 Buffer const & buffer = ploader.buffer();
1231 if (!preview_wanted(params(), buffer))
1233 preview_->setAbsFile(includedFileName(buffer, params()));
1234 docstring const snippet = latexString(*this);
1235 preview_->addPreview(snippet, ploader);
1239 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1240 UpdateType utype, TocBackend & backend) const
1242 if (isListings(params())) {
1244 label_->addToToc(cpit, output_active, utype, backend);
1245 TocBuilder & b = backend.builder("listing");
1246 b.pushItem(cpit, screenLabel(), output_active);
1247 InsetListingsParams p(to_utf8(params()["lstparams"]));
1248 b.argumentItem(from_utf8(p.getParamValue("caption")));
1251 Buffer const * const childbuffer = getChildBuffer();
1253 TocBuilder & b = backend.builder("child");
1254 docstring str = childbuffer ? childbuffer->fileName().displayName()
1256 b.pushItem(cpit, str, output_active);
1262 // Update the child's tocBackend. The outliner uses the master's, but
1263 // the navigation menu uses the child's.
1264 childbuffer->tocBackend().update(output_active, utype);
1265 // Include Tocs from children
1266 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1268 //Copy missing outliner names (though the user has been warned against
1269 //having different document class and module selection between master
1271 for (pair<string, docstring> const & name
1272 : childbuffer->params().documentClass().outlinerNames())
1273 backend.addName(name.first, translateIfPossible(name.second));
1278 void InsetInclude::updateCommand()
1283 docstring old_label = label_->getParam("name");
1284 label_->updateLabel(old_label);
1285 // the label might have been adapted (duplicate)
1286 docstring new_label = label_->getParam("name");
1287 if (old_label == new_label)
1290 // update listings parameters...
1291 InsetCommandParams p(INCLUDE_CODE);
1293 InsetListingsParams par(to_utf8(params()["lstparams"]));
1294 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1295 p["lstparams"] = from_utf8(par.params());
1300 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1302 button_.update(screenLabel(), true, false);
1304 Buffer const * const childbuffer = getChildBuffer();
1306 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1309 if (!isListings(params()))
1313 label_->updateBuffer(it, utype);
1315 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1316 if (par.getParamValue("caption").empty()) {
1317 listings_label_ = buffer().B_("Program Listing");
1320 Buffer const & master = *buffer().masterBuffer();
1321 Counters & counters = master.params().documentClass().counters();
1322 docstring const cnt = from_ascii("listing");
1323 listings_label_ = master.B_("Program Listing");
1324 if (counters.hasCounter(cnt)) {
1325 counters.step(cnt, utype);
1326 listings_label_ += " " + convert<docstring>(counters.value(cnt));