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);
249 bool InsetInclude::isCompatibleCommand(string const & s)
251 return type(s) != NONE;
255 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
257 switch (cmd.action()) {
259 case LFUN_INSET_EDIT: {
260 editIncluded(to_utf8(params()["filename"]));
264 case LFUN_INSET_MODIFY: {
265 // It should be OK just to invalidate the cache in setParams()
267 // child_buffer_ = 0;
268 InsetCommandParams p(INCLUDE_CODE);
269 if (cmd.getArg(0) == "changetype") {
271 InsetCommand::doDispatch(cur, cmd);
274 InsetCommand::string2params(to_utf8(cmd.argument()), p);
275 if (!p.getCmdName().empty()) {
277 InsetListingsParams new_params(to_utf8(p["lstparams"]));
278 docstring const new_label =
279 from_utf8(new_params.getParamValue("label"));
281 if (new_label.empty()) {
287 old_label = label_->getParam("name");
289 label_ = createLabel(buffer_, new_label);
290 label_->setBuffer(buffer());
293 if (new_label != old_label) {
294 label_->updateLabelAndRefs(new_label, &cur);
295 // the label might have been adapted (duplicate)
296 if (new_label != label_->getParam("name")) {
297 new_params.addParam("label", "{" +
298 to_utf8(label_->getParam("name")) + "}", true);
299 p["lstparams"] = from_utf8(new_params.params());
306 cur.forceBufferUpdate();
308 cur.noScreenUpdate();
312 //pass everything else up the chain
314 InsetCommand::doDispatch(cur, cmd);
320 void InsetInclude::editIncluded(string const & file)
322 string const ext = support::getExtension(file);
324 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
327 // tex file or other text file in verbatim mode
328 theFormats().edit(buffer(),
329 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
334 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
335 FuncStatus & flag) const
337 switch (cmd.action()) {
339 case LFUN_INSET_EDIT:
340 flag.setEnabled(true);
343 case LFUN_INSET_MODIFY:
344 if (cmd.getArg(0) == "changetype")
345 return InsetCommand::getStatus(cur, cmd, flag);
347 flag.setEnabled(true);
351 return InsetCommand::getStatus(cur, cmd, flag);
356 void InsetInclude::setParams(InsetCommandParams const & p)
358 // invalidate the cache
361 InsetCommand::setParams(p);
364 if (preview_->monitoring())
365 preview_->stopMonitoring();
367 if (type(params()) == INPUT)
368 add_preview(*preview_, *this, buffer());
372 bool InsetInclude::isChildIncluded() const
374 std::list<std::string> includeonlys =
375 buffer().params().getIncludedChildren();
376 if (includeonlys.empty())
378 return (std::find(includeonlys.begin(),
380 to_utf8(params()["filename"])) != includeonlys.end());
384 docstring InsetInclude::screenLabel() const
388 switch (type(params())) {
390 temp = buffer().B_("Input");
393 temp = buffer().B_("Verbatim Input");
396 temp = buffer().B_("Verbatim Input*");
399 if (isChildIncluded())
400 temp = buffer().B_("Include");
402 temp += buffer().B_("Include (excluded)");
405 temp = listings_label_;
408 LASSERT(false, temp = buffer().B_("Unknown"));
414 if (params()["filename"].empty())
417 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
423 Buffer * InsetInclude::getChildBuffer() const
425 Buffer * childBuffer = loadIfNeeded();
427 // FIXME RECURSIVE INCLUDE
428 // This isn't sufficient, as the inclusion could be downstream.
429 // But it'll have to do for now.
430 return (childBuffer == &buffer()) ? 0 : childBuffer;
434 Buffer * InsetInclude::loadIfNeeded() const
436 // This is for background export and preview. We don't even want to
437 // try to load the cloned child document again.
438 if (buffer().isClone())
439 return child_buffer_;
441 // Don't try to load it again if we failed before.
442 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
445 FileName const included_file = includedFileName(buffer(), params());
446 // Use cached Buffer if possible.
447 if (child_buffer_ != 0) {
448 if (theBufferList().isLoaded(child_buffer_)
449 // additional sanity check: make sure the Buffer really is
450 // associated with the file we want.
451 && child_buffer_ == theBufferList().getBuffer(included_file))
452 return child_buffer_;
453 // Buffer vanished, so invalidate cache and try to reload.
457 if (!isLyXFileName(included_file.absFileName()))
460 Buffer * child = theBufferList().getBuffer(included_file);
462 // the readonly flag can/will be wrong, not anymore I think.
463 if (!included_file.exists())
466 child = theBufferList().newBuffer(included_file.absFileName());
468 // Buffer creation is not possible.
471 // Set parent before loading, such that macros can be tracked
472 child->setParent(&buffer());
474 if (child->loadLyXFile() != Buffer::ReadSuccess) {
475 failedtoload_ = true;
477 //close the buffer we just opened
478 theBufferList().release(child);
482 if (!child->errorList("Parse").empty()) {
483 // FIXME: Do something.
486 // The file was already loaded, so, simply
487 // inform parent buffer about local macros.
488 Buffer const * parent = &buffer();
489 child->setParent(parent);
491 child->listMacroNames(macros);
492 MacroNameSet::const_iterator cit = macros.begin();
493 MacroNameSet::const_iterator end = macros.end();
494 for (; cit != end; ++cit)
495 parent->usermacros.insert(*cit);
498 // Cache the child buffer.
499 child_buffer_ = child;
504 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
506 string incfile = to_utf8(params()["filename"]);
508 // Do nothing if no file name has been specified
512 FileName const included_file = includedFileName(buffer(), params());
514 // Check we're not trying to include ourselves.
515 // FIXME RECURSIVE INCLUDE
516 // This isn't sufficient, as the inclusion could be downstream.
517 // But it'll have to do for now.
518 if (isInputOrInclude(params()) &&
519 buffer().absFileName() == included_file.absFileName())
521 Alert::error(_("Recursive input"),
522 bformat(_("Attempted to include file %1$s in itself! "
523 "Ignoring inclusion."), from_utf8(incfile)));
527 Buffer const * const masterBuffer = buffer().masterBuffer();
529 // if incfile is relative, make it relative to the master
531 if (!FileName::isAbsolute(incfile)) {
533 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
534 from_utf8(masterBuffer->filePath())));
537 string exppath = incfile;
538 if (!runparams.export_folder.empty()) {
539 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
540 FileName(exppath).onlyPath().createPath();
543 // write it to a file (so far the complete file)
547 if (type(params()) == LISTINGS) {
548 exportfile = exppath;
549 mangled = DocFileName(included_file).mangledFileName();
551 exportfile = changeExtension(exppath, ".tex");
552 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
558 else if (!runparams.silent)
559 ; // no warning wanted
560 else if (!isValidLaTeXFileName(incfile)) {
561 frontend::Alert::warning(_("Invalid filename"),
562 _("The following filename will cause troubles "
563 "when running the exported file through LaTeX: ") +
565 } else if (!isValidDVIFileName(incfile)) {
566 frontend::Alert::warning(_("Problematic filename for DVI"),
567 _("The following filename can cause troubles "
568 "when running the exported file through LaTeX "
569 "and opening the resulting DVI: ") +
570 from_utf8(incfile), true);
573 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
574 buffer().temppath() : masterBuffer->temppath()));
576 LYXERR(Debug::LATEX, "incfile:" << incfile);
577 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
578 LYXERR(Debug::LATEX, "writefile:" << writefile);
580 string const tex_format = flavor2format(runparams.flavor);
582 switch (type(params())) {
585 incfile = latex_path(incfile);
587 os << '\\' << from_ascii(params().getCmdName()) << '{'
588 << from_utf8(incfile) << '}';
592 runparams.exportdata->addExternalFile(tex_format, writefile,
595 // \input wants file with extension (default is .tex)
596 if (!isLyXFileName(included_file.absFileName())) {
597 incfile = latex_path(incfile);
599 os << '\\' << from_ascii(params().getCmdName())
600 << '{' << from_utf8(incfile) << '}';
602 incfile = changeExtension(incfile, ".tex");
603 incfile = latex_path(incfile);
605 os << '\\' << from_ascii(params().getCmdName())
606 << '{' << from_utf8(incfile) << '}';
611 // Here, listings and minted have sligthly different behaviors.
612 // Using listings, it is always possible to have a caption,
613 // even for non-floats. Using minted, only floats can have a
614 // caption. So, with minted we use the following strategy.
615 // If a caption was specified but the float parameter was not,
616 // we ourselves add a caption above the listing (because the
617 // listing comes from a file and might span several pages).
618 // Otherwise, if float was specified, the floating listing
619 // environment provided by minted is used. In either case, the
620 // label parameter is taken as the label by which the float
621 // can be referenced, otherwise it will have the meaning
622 // intended by minted. In this last case, the label will
623 // serve as a sort of caption that, however, will be shown
624 // by minted only if the frame parameter is also specified.
625 bool const use_minted = buffer().params().use_minted;
626 runparams.exportdata->addExternalFile(tex_format, writefile,
628 string const opt = to_utf8(params()["lstparams"]);
629 // opt is set in QInclude dialog and should have passed validation.
630 InsetListingsParams lstparams(opt);
631 docstring parameters = from_utf8(lstparams.params());
636 bool isfloat = lstparams.isFloat();
637 // We are going to split parameters at commas, so
638 // replace commas that are not parameter separators
639 // with a code point from the private use area
640 char_type comma = replaceCommaInBraces(parameters);
641 // Get float placement, language, caption, and
642 // label, then remove the relative options if minted.
643 vector<docstring> opts =
644 getVectorFromString(parameters, from_ascii(","), false);
645 vector<docstring> latexed_opts;
646 for (size_t i = 0; i < opts.size(); ++i) {
647 // Restore replaced commas
648 opts[i] = subst(opts[i], comma, ',');
649 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
650 if (prefixIs(opts[i], from_ascii("float=")))
651 placement = opts[i].substr(6);
652 opts.erase(opts.begin() + i--);
653 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
654 language = opts[i].substr(9);
655 opts.erase(opts.begin() + i--);
656 } else if (prefixIs(opts[i], from_ascii("caption="))) {
657 // FIXME We should use HANDLING_LATEXIFY here,
658 // but that's a file format change (see #10455).
659 caption = opts[i].substr(8);
660 opts.erase(opts.begin() + i--);
662 latexed_opts.push_back(from_ascii("caption=") + caption);
663 } else if (prefixIs(opts[i], from_ascii("label="))) {
664 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
665 ParamInfo::HANDLING_ESCAPE);
666 opts.erase(opts.begin() + i--);
668 latexed_opts.push_back(from_ascii("label={") + label + "}");
670 if (use_minted && !label.empty()) {
671 if (isfloat || !caption.empty())
672 label = trim(label, "{}");
674 opts.push_back(from_ascii("label=") + label);
677 if (!latexed_opts.empty())
678 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
679 parameters = getStringFromVector(opts, from_ascii(","));
680 if (language.empty())
681 language = from_ascii("TeX");
682 if (use_minted && isfloat) {
683 os << breakln << "\\begin{listing}";
684 if (!placement.empty())
685 os << '[' << placement << "]";
687 } else if (use_minted && !caption.empty()) {
688 os << breakln << "\\lyxmintcaption[t]{" << caption;
690 os << "\\label{" << label << "}";
693 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
694 if (!parameters.empty())
695 os << "[" << parameters << "]";
697 os << '{' << ascii_lowercase(language) << '}';
698 os << '{' << incfile << '}';
699 if (use_minted && isfloat) {
700 if (!caption.empty())
701 os << breakln << "\\caption{" << caption << "}";
703 os << breakln << "\\label{" << label << "}";
704 os << breakln << "\\end{listing}\n";
709 runparams.exportdata->addExternalFile(tex_format, writefile,
712 // \include don't want extension and demands that the
713 // file really have .tex
714 incfile = changeExtension(incfile, string());
715 incfile = latex_path(incfile);
717 os << '\\' << from_ascii(params().getCmdName()) << '{'
718 << from_utf8(incfile) << '}';
725 if (runparams.inComment || runparams.dryrun)
726 // Don't try to load or copy the file if we're
727 // in a comment or doing a dryrun
730 if (isInputOrInclude(params()) &&
731 isLyXFileName(included_file.absFileName())) {
732 // if it's a LyX file and we're inputting or including,
733 // try to load it so we can write the associated latex
735 Buffer * tmp = loadIfNeeded();
737 if (!runparams.silent) {
738 docstring text = bformat(_("Could not load included "
740 "Please, check whether it actually exists."),
741 included_file.displayName());
742 throw ExceptionMessage(ErrorException, _("Error: "),
748 if (!runparams.silent) {
749 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
751 docstring text = bformat(_("Included file `%1$s'\n"
752 "has textclass `%2$s'\n"
753 "while parent file has textclass `%3$s'."),
754 included_file.displayName(),
755 from_utf8(tmp->params().documentClass().name()),
756 from_utf8(masterBuffer->params().documentClass().name()));
757 Alert::warning(_("Different textclasses"), text, true);
760 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
761 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
762 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
763 docstring text = bformat(_("Included file `%1$s'\n"
764 "has use-non-TeX-fonts set to `%2$s'\n"
765 "while parent file has use-non-TeX-fonts set to `%3$s'."),
766 included_file.displayName(),
768 from_utf8(master_tf));
769 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
772 // Make sure modules used in child are all included in master
773 // FIXME It might be worth loading the children's modules into the master
774 // over in BufferParams rather than doing this check.
775 LayoutModuleList const masterModules = masterBuffer->params().getModules();
776 LayoutModuleList const childModules = tmp->params().getModules();
777 LayoutModuleList::const_iterator it = childModules.begin();
778 LayoutModuleList::const_iterator end = childModules.end();
779 for (; it != end; ++it) {
780 string const module = *it;
781 LayoutModuleList::const_iterator found =
782 find(masterModules.begin(), masterModules.end(), module);
783 if (found == masterModules.end()) {
784 docstring text = bformat(_("Included file `%1$s'\n"
785 "uses module `%2$s'\n"
786 "which is not used in parent file."),
787 included_file.displayName(), from_utf8(module));
788 Alert::warning(_("Module not found"), text, true);
793 tmp->markDepClean(masterBuffer->temppath());
795 // Don't assume the child's format is latex
796 string const inc_format = tmp->params().bufferFormat();
797 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
798 theFormats().extension(inc_format)));
800 // FIXME: handle non existing files
801 // The included file might be written in a different encoding
803 Encoding const * const oldEnc = runparams.encoding;
804 Language const * const oldLang = runparams.master_language;
805 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
806 // the children must be encoded in plain utf8!
807 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
808 encodings.fromLyXName("utf8-plain")
809 : &tmp->params().encoding();
810 runparams.master_language = buffer().params().language;
811 runparams.par_begin = 0;
812 runparams.par_end = tmp->paragraphs().size();
813 runparams.is_child = true;
814 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
815 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
816 if (!runparams.silent) {
817 docstring msg = bformat(_("Included file `%1$s' "
818 "was not exported correctly.\n "
819 "LaTeX export is probably incomplete."),
820 included_file.displayName());
821 ErrorList const & el = tmp->errorList("Export");
823 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
824 msg, el.begin()->error,
825 el.begin()->description);
826 throw ExceptionMessage(ErrorException, _("Error: "),
830 runparams.encoding = oldEnc;
831 runparams.master_language = oldLang;
832 runparams.is_child = false;
834 // If needed, use converters to produce a latex file from the child
835 if (tmpwritefile != writefile) {
838 theConverters().convert(tmp, tmpwritefile, writefile,
840 inc_format, tex_format, el);
842 if (!success && !runparams.silent) {
843 docstring msg = bformat(_("Included file `%1$s' "
844 "was not exported correctly.\n "
845 "LaTeX export is probably incomplete."),
846 included_file.displayName());
848 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
849 msg, el.begin()->error,
850 el.begin()->description);
851 throw ExceptionMessage(ErrorException, _("Error: "),
856 // In this case, it's not a LyX file, so we copy the file
857 // to the temp dir, so that .aux files etc. are not created
858 // in the original dir. Files included by this file will be
859 // found via either the environment variable TEXINPUTS, or
860 // input@path, see ../Buffer.cpp.
861 unsigned long const checksum_in = included_file.checksum();
862 unsigned long const checksum_out = writefile.checksum();
864 if (checksum_in != checksum_out) {
865 if (!included_file.copyTo(writefile)) {
868 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
869 "into the temporary directory."),
870 from_utf8(included_file.absFileName()))));
878 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
883 // For verbatim and listings, we just include the contents of the file as-is.
884 // In the case of listings, we wrap it in <pre>.
885 bool const listing = isListings(params());
886 if (listing || isVerbatim(params())) {
888 xs << html::StartTag("pre");
889 // FIXME: We don't know the encoding of the file, default to UTF-8.
890 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
892 xs << html::EndTag("pre");
896 // We don't (yet) know how to Input or Include non-LyX files.
897 // (If we wanted to get really arcane, we could run some tex2html
898 // converter on the included file. But that's just masochistic.)
899 FileName const included_file = includedFileName(buffer(), params());
900 if (!isLyXFileName(included_file.absFileName())) {
902 frontend::Alert::warning(_("Unsupported Inclusion"),
903 bformat(_("LyX does not know how to include non-LyX files when "
904 "generating HTML output. Offending file:\n%1$s"),
905 params()["filename"]));
909 // In the other cases, we will generate the HTML and include it.
911 // Check we're not trying to include ourselves.
912 // FIXME RECURSIVE INCLUDE
913 if (buffer().absFileName() == included_file.absFileName()) {
914 Alert::error(_("Recursive input"),
915 bformat(_("Attempted to include file %1$s in itself! "
916 "Ignoring inclusion."), params()["filename"]));
920 Buffer const * const ibuf = loadIfNeeded();
924 // are we generating only some paragraphs, or all of them?
925 bool const all_pars = !rp.dryrun ||
926 (rp.par_begin == 0 &&
927 rp.par_end == (int)buffer().text().paragraphs().size());
929 OutputParams op = rp;
933 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
935 xs << XHTMLStream::ESCAPE_NONE
936 << "<!-- Included file: "
937 << from_utf8(included_file.absFileName())
938 << XHTMLStream::ESCAPE_NONE
944 int InsetInclude::plaintext(odocstringstream & os,
945 OutputParams const & op, size_t) const
947 // just write the filename if we're making a tooltip or toc entry,
948 // or are generating this for advanced search
949 if (op.for_tooltip || op.for_toc || op.for_search) {
950 os << '[' << screenLabel() << '\n'
951 << getParam("filename") << "\n]";
952 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
955 if (isVerbatim(params()) || isListings(params())) {
956 os << '[' << screenLabel() << '\n'
957 // FIXME: We don't know the encoding of the file, default to UTF-8.
958 << includedFileName(buffer(), params()).fileContents("UTF-8")
960 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
963 Buffer const * const ibuf = loadIfNeeded();
965 docstring const str = '[' + screenLabel() + ']';
969 writePlaintextFile(*ibuf, os, op);
974 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
976 string incfile = to_utf8(params()["filename"]);
978 // Do nothing if no file name has been specified
982 string const included_file = includedFileName(buffer(), params()).absFileName();
984 // Check we're not trying to include ourselves.
985 // FIXME RECURSIVE INCLUDE
986 // This isn't sufficient, as the inclusion could be downstream.
987 // But it'll have to do for now.
988 if (buffer().absFileName() == included_file) {
989 Alert::error(_("Recursive input"),
990 bformat(_("Attempted to include file %1$s in itself! "
991 "Ignoring inclusion."), from_utf8(incfile)));
995 string exppath = incfile;
996 if (!runparams.export_folder.empty()) {
997 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
998 FileName(exppath).onlyPath().createPath();
1001 // write it to a file (so far the complete file)
1002 string const exportfile = changeExtension(exppath, ".sgml");
1003 DocFileName writefile(changeExtension(included_file, ".sgml"));
1005 Buffer * tmp = loadIfNeeded();
1007 string const mangled = writefile.mangledFileName();
1008 writefile = makeAbsPath(mangled,
1009 buffer().masterBuffer()->temppath());
1010 if (!runparams.nice)
1013 LYXERR(Debug::LATEX, "incfile:" << incfile);
1014 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
1015 LYXERR(Debug::LATEX, "writefile:" << writefile);
1017 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
1020 runparams.exportdata->addExternalFile("docbook", writefile,
1022 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1025 if (isVerbatim(params()) || isListings(params())) {
1026 os << "<inlinegraphic fileref=\""
1027 << '&' << include_label << ';'
1028 << "\" format=\"linespecific\">";
1030 os << '&' << include_label << ';';
1036 void InsetInclude::validate(LaTeXFeatures & features) const
1038 LATTEST(&buffer() == &features.buffer());
1040 string incfile = to_utf8(params()["filename"]);
1041 string const included_file =
1042 includedFileName(buffer(), params()).absFileName();
1045 if (isLyXFileName(included_file))
1046 writefile = changeExtension(included_file, ".sgml");
1048 writefile = included_file;
1050 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1051 incfile = DocFileName(writefile).mangledFileName();
1052 writefile = makeAbsPath(incfile,
1053 buffer().masterBuffer()->temppath()).absFileName();
1056 features.includeFile(include_label, writefile);
1058 features.useInsetLayout(getLayout());
1059 if (isVerbatim(params()))
1060 features.require("verbatim");
1061 else if (isListings(params())) {
1062 if (buffer().params().use_minted) {
1063 features.require("minted");
1064 string const opts = to_utf8(params()["lstparams"]);
1065 InsetListingsParams lstpars(opts);
1066 if (!lstpars.isFloat() && contains(opts, "caption="))
1067 features.require("lyxmintcaption");
1069 features.require("listings");
1072 // Here we must do the fun stuff...
1073 // Load the file in the include if it needs
1075 Buffer * const tmp = loadIfNeeded();
1077 // the file is loaded
1078 // make sure the buffer isn't us
1079 // FIXME RECURSIVE INCLUDES
1080 // This is not sufficient, as recursive includes could be
1081 // more than a file away. But it will do for now.
1082 if (tmp && tmp != &buffer()) {
1083 // We must temporarily change features.buffer,
1084 // otherwise it would always be the master buffer,
1085 // and nested includes would not work.
1086 features.setBuffer(*tmp);
1087 // Maybe this is already a child
1088 bool const is_child =
1089 features.runparams().is_child;
1090 features.runparams().is_child = true;
1091 tmp->validate(features);
1092 features.runparams().is_child = is_child;
1093 features.setBuffer(buffer());
1099 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1101 Buffer * child = loadIfNeeded();
1104 // FIXME RECURSIVE INCLUDE
1105 // This isn't sufficient, as the inclusion could be downstream.
1106 // But it'll have to do for now.
1107 if (child == &buffer())
1109 child->collectBibKeys(checkedFiles);
1113 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1115 LBUFERR(mi.base.bv);
1117 bool use_preview = false;
1118 if (RenderPreview::previewText()) {
1119 graphics::PreviewImage const * pimage =
1120 preview_->getPreviewImage(mi.base.bv->buffer());
1121 use_preview = pimage && pimage->image();
1125 preview_->metrics(mi, dim);
1129 button_.update(screenLabel(), true, false);
1131 button_.metrics(mi, dim);
1134 Box b(0, dim.wid, -dim.asc, dim.des);
1139 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1141 LBUFERR(pi.base.bv);
1143 bool use_preview = false;
1144 if (RenderPreview::previewText()) {
1145 graphics::PreviewImage const * pimage =
1146 preview_->getPreviewImage(pi.base.bv->buffer());
1147 use_preview = pimage && pimage->image();
1151 preview_->draw(pi, x, y);
1153 button_.draw(pi, x, y);
1157 void InsetInclude::write(ostream & os) const
1159 params().Write(os, &buffer());
1163 string InsetInclude::contextMenuName() const
1165 return "context-include";
1169 Inset::DisplayType InsetInclude::display() const
1171 return type(params()) == INPUT ? Inline : AlignCenter;
1175 docstring InsetInclude::layoutName() const
1177 if (isListings(params()))
1178 return from_ascii("IncludeListings");
1179 return InsetCommand::layoutName();
1187 void InsetInclude::fileChanged() const
1189 Buffer const * const buffer = updateFrontend();
1193 preview_->removePreview(*buffer);
1194 add_preview(*preview_, *this, *buffer);
1195 preview_->startLoading(*buffer);
1201 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1203 FileName const included_file = includedFileName(buffer, params);
1205 return type(params) == INPUT && params.preview() &&
1206 included_file.isReadableFile();
1210 docstring latexString(InsetInclude const & inset)
1212 odocstringstream ods;
1214 // We don't need to set runparams.encoding since this will be done
1215 // by latex() anyway.
1216 OutputParams runparams(0);
1217 runparams.flavor = OutputParams::LATEX;
1218 runparams.for_preview = true;
1219 inset.latex(os, runparams);
1225 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1226 Buffer const & buffer)
1228 InsetCommandParams const & params = inset.params();
1229 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1230 renderer.setAbsFile(includedFileName(buffer, params));
1231 docstring const snippet = latexString(inset);
1232 renderer.addPreview(snippet, buffer);
1239 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1240 graphics::PreviewLoader & ploader) const
1242 Buffer const & buffer = ploader.buffer();
1243 if (!preview_wanted(params(), buffer))
1245 preview_->setAbsFile(includedFileName(buffer, params()));
1246 docstring const snippet = latexString(*this);
1247 preview_->addPreview(snippet, ploader);
1251 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1252 UpdateType utype, TocBackend & backend) const
1254 if (isListings(params())) {
1256 label_->addToToc(cpit, output_active, utype, backend);
1257 TocBuilder & b = backend.builder("listing");
1258 b.pushItem(cpit, screenLabel(), output_active);
1259 InsetListingsParams p(to_utf8(params()["lstparams"]));
1260 b.argumentItem(from_utf8(p.getParamValue("caption")));
1263 Buffer const * const childbuffer = getChildBuffer();
1265 TocBuilder & b = backend.builder("child");
1266 docstring str = childbuffer ? childbuffer->fileName().displayName()
1268 b.pushItem(cpit, str, output_active);
1274 // Update the child's tocBackend. The outliner uses the master's, but
1275 // the navigation menu uses the child's.
1276 childbuffer->tocBackend().update(output_active, utype);
1277 // Include Tocs from children
1278 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1280 //Copy missing outliner names (though the user has been warned against
1281 //having different document class and module selection between master
1283 for (pair<string, docstring> const & name
1284 : childbuffer->params().documentClass().outlinerNames())
1285 backend.addName(name.first, translateIfPossible(name.second));
1290 void InsetInclude::updateCommand()
1295 docstring old_label = label_->getParam("name");
1296 label_->updateLabel(old_label);
1297 // the label might have been adapted (duplicate)
1298 docstring new_label = label_->getParam("name");
1299 if (old_label == new_label)
1302 // update listings parameters...
1303 InsetCommandParams p(INCLUDE_CODE);
1305 InsetListingsParams par(to_utf8(params()["lstparams"]));
1306 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1307 p["lstparams"] = from_utf8(par.params());
1312 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1314 button_.update(screenLabel(), true, false);
1316 Buffer const * const childbuffer = getChildBuffer();
1318 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1321 if (!isListings(params()))
1325 label_->updateBuffer(it, utype);
1327 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1328 if (par.getParamValue("caption").empty()) {
1329 listings_label_ = buffer().B_("Program Listing");
1332 Buffer const & master = *buffer().masterBuffer();
1333 Counters & counters = master.params().documentClass().counters();
1334 docstring const cnt = from_ascii("listing");
1335 listings_label_ = master.B_("Program Listing");
1336 if (counters.hasCounter(cnt)) {
1337 counters.step(cnt, utype);
1338 listings_label_ += " " + convert<docstring>(counters.value(cnt));