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 // reset in order to allow loading new file
362 failedtoload_ = false;
364 InsetCommand::setParams(p);
367 if (preview_->monitoring())
368 preview_->stopMonitoring();
370 if (type(params()) == INPUT)
371 add_preview(*preview_, *this, buffer());
375 bool InsetInclude::isChildIncluded() const
377 std::list<std::string> includeonlys =
378 buffer().params().getIncludedChildren();
379 if (includeonlys.empty())
381 return (std::find(includeonlys.begin(),
383 to_utf8(params()["filename"])) != includeonlys.end());
387 docstring InsetInclude::screenLabel() const
391 switch (type(params())) {
393 temp = buffer().B_("Input");
396 temp = buffer().B_("Verbatim Input");
399 temp = buffer().B_("Verbatim Input*");
402 if (isChildIncluded())
403 temp = buffer().B_("Include");
405 temp += buffer().B_("Include (excluded)");
408 temp = listings_label_;
411 LASSERT(false, temp = buffer().B_("Unknown"));
417 if (params()["filename"].empty())
420 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
426 Buffer * InsetInclude::getChildBuffer() const
428 Buffer * childBuffer = loadIfNeeded();
430 // FIXME RECURSIVE INCLUDE
431 // This isn't sufficient, as the inclusion could be downstream.
432 // But it'll have to do for now.
433 return (childBuffer == &buffer()) ? 0 : childBuffer;
437 Buffer * InsetInclude::loadIfNeeded() const
439 // This is for background export and preview. We don't even want to
440 // try to load the cloned child document again.
441 if (buffer().isClone())
442 return child_buffer_;
444 // Don't try to load it again if we failed before.
445 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
448 FileName const included_file = includedFileName(buffer(), params());
449 // Use cached Buffer if possible.
450 if (child_buffer_ != 0) {
451 if (theBufferList().isLoaded(child_buffer_)
452 // additional sanity check: make sure the Buffer really is
453 // associated with the file we want.
454 && child_buffer_ == theBufferList().getBuffer(included_file))
455 return child_buffer_;
456 // Buffer vanished, so invalidate cache and try to reload.
460 if (!isLyXFileName(included_file.absFileName()))
463 Buffer * child = theBufferList().getBuffer(included_file);
465 // the readonly flag can/will be wrong, not anymore I think.
466 if (!included_file.exists()) {
467 failedtoload_ = true;
471 child = theBufferList().newBuffer(included_file.absFileName());
473 // Buffer creation is not possible.
476 // Set parent before loading, such that macros can be tracked
477 child->setParent(&buffer());
479 if (child->loadLyXFile() != Buffer::ReadSuccess) {
480 failedtoload_ = true;
482 //close the buffer we just opened
483 theBufferList().release(child);
487 if (!child->errorList("Parse").empty()) {
488 // FIXME: Do something.
491 // The file was already loaded, so, simply
492 // inform parent buffer about local macros.
493 Buffer const * parent = &buffer();
494 child->setParent(parent);
496 child->listMacroNames(macros);
497 MacroNameSet::const_iterator cit = macros.begin();
498 MacroNameSet::const_iterator end = macros.end();
499 for (; cit != end; ++cit)
500 parent->usermacros.insert(*cit);
503 // Cache the child buffer.
504 child_buffer_ = child;
509 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
511 string incfile = to_utf8(params()["filename"]);
513 // Do nothing if no file name has been specified
517 FileName const included_file = includedFileName(buffer(), params());
519 // Check we're not trying to include ourselves.
520 // FIXME RECURSIVE INCLUDE
521 // This isn't sufficient, as the inclusion could be downstream.
522 // But it'll have to do for now.
523 if (isInputOrInclude(params()) &&
524 buffer().absFileName() == included_file.absFileName())
526 Alert::error(_("Recursive input"),
527 bformat(_("Attempted to include file %1$s in itself! "
528 "Ignoring inclusion."), from_utf8(incfile)));
532 Buffer const * const masterBuffer = buffer().masterBuffer();
534 // if incfile is relative, make it relative to the master
536 if (!FileName::isAbsolute(incfile)) {
538 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
539 from_utf8(masterBuffer->filePath())));
542 string exppath = incfile;
543 if (!runparams.export_folder.empty()) {
544 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
547 // write it to a file (so far the complete file)
551 if (type(params()) == LISTINGS) {
552 exportfile = exppath;
553 mangled = DocFileName(included_file).mangledFileName();
555 exportfile = changeExtension(exppath, ".tex");
556 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
562 else if (!runparams.silent)
563 ; // no warning wanted
564 else if (!isValidLaTeXFileName(incfile)) {
565 frontend::Alert::warning(_("Invalid filename"),
566 _("The following filename will cause troubles "
567 "when running the exported file through LaTeX: ") +
569 } else if (!isValidDVIFileName(incfile)) {
570 frontend::Alert::warning(_("Problematic filename for DVI"),
571 _("The following filename can cause troubles "
572 "when running the exported file through LaTeX "
573 "and opening the resulting DVI: ") +
574 from_utf8(incfile), true);
577 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
578 buffer().temppath() : masterBuffer->temppath()));
580 LYXERR(Debug::LATEX, "incfile:" << incfile);
581 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
582 LYXERR(Debug::LATEX, "writefile:" << writefile);
584 string const tex_format = flavor2format(runparams.flavor);
586 switch (type(params())) {
589 incfile = latex_path(incfile);
591 os << '\\' << from_ascii(params().getCmdName()) << '{'
592 << from_utf8(incfile) << '}';
596 runparams.exportdata->addExternalFile(tex_format, writefile,
599 // \input wants file with extension (default is .tex)
600 if (!isLyXFileName(included_file.absFileName())) {
601 incfile = latex_path(incfile);
603 os << '\\' << from_ascii(params().getCmdName())
604 << '{' << from_utf8(incfile) << '}';
606 incfile = changeExtension(incfile, ".tex");
607 incfile = latex_path(incfile);
609 os << '\\' << from_ascii(params().getCmdName())
610 << '{' << from_utf8(incfile) << '}';
615 // Here, listings and minted have sligthly different behaviors.
616 // Using listings, it is always possible to have a caption,
617 // even for non-floats. Using minted, only floats can have a
618 // caption. So, with minted we use the following strategy.
619 // If a caption was specified but the float parameter was not,
620 // we ourselves add a caption above the listing (because the
621 // listing comes from a file and might span several pages).
622 // Otherwise, if float was specified, the floating listing
623 // environment provided by minted is used. In either case, the
624 // label parameter is taken as the label by which the float
625 // can be referenced, otherwise it will have the meaning
626 // intended by minted. In this last case, the label will
627 // serve as a sort of caption that, however, will be shown
628 // by minted only if the frame parameter is also specified.
629 bool const use_minted = buffer().params().use_minted;
630 runparams.exportdata->addExternalFile(tex_format, writefile,
632 string const opt = to_utf8(params()["lstparams"]);
633 // opt is set in QInclude dialog and should have passed validation.
634 InsetListingsParams lstparams(opt);
635 docstring parameters = from_utf8(lstparams.params());
640 bool isfloat = lstparams.isFloat();
641 // We are going to split parameters at commas, so
642 // replace commas that are not parameter separators
643 // with a code point from the private use area
644 char_type comma = replaceCommaInBraces(parameters);
645 // Get float placement, language, caption, and
646 // label, then remove the relative options if minted.
647 vector<docstring> opts =
648 getVectorFromString(parameters, from_ascii(","), false);
649 vector<docstring> latexed_opts;
650 for (size_t i = 0; i < opts.size(); ++i) {
651 // Restore replaced commas
652 opts[i] = subst(opts[i], comma, ',');
653 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
654 if (prefixIs(opts[i], from_ascii("float=")))
655 placement = opts[i].substr(6);
656 opts.erase(opts.begin() + i--);
657 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
658 language = opts[i].substr(9);
659 opts.erase(opts.begin() + i--);
660 } else if (prefixIs(opts[i], from_ascii("caption="))) {
661 // FIXME We should use HANDLING_LATEXIFY here,
662 // but that's a file format change (see #10455).
663 caption = opts[i].substr(8);
664 opts.erase(opts.begin() + i--);
666 latexed_opts.push_back(from_ascii("caption=") + caption);
667 } else if (prefixIs(opts[i], from_ascii("label="))) {
668 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
669 ParamInfo::HANDLING_ESCAPE);
670 opts.erase(opts.begin() + i--);
672 latexed_opts.push_back(from_ascii("label={") + label + "}");
674 if (use_minted && !label.empty()) {
675 if (isfloat || !caption.empty())
676 label = trim(label, "{}");
678 opts.push_back(from_ascii("label=") + label);
681 if (!latexed_opts.empty())
682 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
683 parameters = getStringFromVector(opts, from_ascii(","));
684 if (language.empty())
685 language = from_ascii("TeX");
686 if (use_minted && isfloat) {
687 os << breakln << "\\begin{listing}";
688 if (!placement.empty())
689 os << '[' << placement << "]";
691 } else if (use_minted && !caption.empty()) {
692 os << breakln << "\\lyxmintcaption[t]{" << caption;
694 os << "\\label{" << label << "}";
697 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
698 if (!parameters.empty())
699 os << "[" << parameters << "]";
701 os << '{' << ascii_lowercase(language) << '}';
702 os << '{' << incfile << '}';
703 if (use_minted && isfloat) {
704 if (!caption.empty())
705 os << breakln << "\\caption{" << caption << "}";
707 os << breakln << "\\label{" << label << "}";
708 os << breakln << "\\end{listing}\n";
713 runparams.exportdata->addExternalFile(tex_format, writefile,
716 // \include don't want extension and demands that the
717 // file really have .tex
718 incfile = changeExtension(incfile, string());
719 incfile = latex_path(incfile);
721 os << '\\' << from_ascii(params().getCmdName()) << '{'
722 << from_utf8(incfile) << '}';
729 if (runparams.inComment || runparams.dryrun)
730 // Don't try to load or copy the file if we're
731 // in a comment or doing a dryrun
734 if (isInputOrInclude(params()) &&
735 isLyXFileName(included_file.absFileName())) {
736 // if it's a LyX file and we're inputting or including,
737 // try to load it so we can write the associated latex
739 Buffer * tmp = loadIfNeeded();
741 if (!runparams.silent) {
742 docstring text = bformat(_("Could not load included "
744 "Please, check whether it actually exists."),
745 included_file.displayName());
746 throw ExceptionMessage(ErrorException, _("Error: "),
752 if (!runparams.silent) {
753 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
755 docstring text = bformat(_("Included file `%1$s'\n"
756 "has textclass `%2$s'\n"
757 "while parent file has textclass `%3$s'."),
758 included_file.displayName(),
759 from_utf8(tmp->params().documentClass().name()),
760 from_utf8(masterBuffer->params().documentClass().name()));
761 Alert::warning(_("Different textclasses"), text, true);
764 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
765 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
766 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
767 docstring text = bformat(_("Included file `%1$s'\n"
768 "has use-non-TeX-fonts set to `%2$s'\n"
769 "while parent file has use-non-TeX-fonts set to `%3$s'."),
770 included_file.displayName(),
772 from_utf8(master_tf));
773 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
776 // Make sure modules used in child are all included in master
777 // FIXME It might be worth loading the children's modules into the master
778 // over in BufferParams rather than doing this check.
779 LayoutModuleList const masterModules = masterBuffer->params().getModules();
780 LayoutModuleList const childModules = tmp->params().getModules();
781 LayoutModuleList::const_iterator it = childModules.begin();
782 LayoutModuleList::const_iterator end = childModules.end();
783 for (; it != end; ++it) {
784 string const module = *it;
785 LayoutModuleList::const_iterator found =
786 find(masterModules.begin(), masterModules.end(), module);
787 if (found == masterModules.end()) {
788 docstring text = bformat(_("Included file `%1$s'\n"
789 "uses module `%2$s'\n"
790 "which is not used in parent file."),
791 included_file.displayName(), from_utf8(module));
792 Alert::warning(_("Module not found"), text, true);
797 tmp->markDepClean(masterBuffer->temppath());
799 // Don't assume the child's format is latex
800 string const inc_format = tmp->params().bufferFormat();
801 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
802 theFormats().extension(inc_format)));
804 // FIXME: handle non existing files
805 // The included file might be written in a different encoding
807 Encoding const * const oldEnc = runparams.encoding;
808 Language const * const oldLang = runparams.master_language;
809 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
810 // the children must be encoded in plain utf8!
811 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
812 encodings.fromLyXName("utf8-plain")
813 : &tmp->params().encoding();
814 runparams.master_language = buffer().params().language;
815 runparams.par_begin = 0;
816 runparams.par_end = tmp->paragraphs().size();
817 runparams.is_child = true;
818 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
819 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
820 if (!runparams.silent) {
821 docstring msg = bformat(_("Included file `%1$s' "
822 "was not exported correctly.\n "
823 "LaTeX export is probably incomplete."),
824 included_file.displayName());
825 ErrorList const & el = tmp->errorList("Export");
827 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
828 msg, el.begin()->error,
829 el.begin()->description);
830 throw ExceptionMessage(ErrorException, _("Error: "),
834 runparams.encoding = oldEnc;
835 runparams.master_language = oldLang;
836 runparams.is_child = false;
838 // If needed, use converters to produce a latex file from the child
839 if (tmpwritefile != writefile) {
842 theConverters().convert(tmp, tmpwritefile, writefile,
844 inc_format, tex_format, el);
846 if (!success && !runparams.silent) {
847 docstring msg = bformat(_("Included file `%1$s' "
848 "was not exported correctly.\n "
849 "LaTeX export is probably incomplete."),
850 included_file.displayName());
852 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
853 msg, el.begin()->error,
854 el.begin()->description);
855 throw ExceptionMessage(ErrorException, _("Error: "),
860 // In this case, it's not a LyX file, so we copy the file
861 // to the temp dir, so that .aux files etc. are not created
862 // in the original dir. Files included by this file will be
863 // found via either the environment variable TEXINPUTS, or
864 // input@path, see ../Buffer.cpp.
865 unsigned long const checksum_in = included_file.checksum();
866 unsigned long const checksum_out = writefile.checksum();
868 if (checksum_in != checksum_out) {
869 if (!included_file.copyTo(writefile)) {
872 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
873 "into the temporary directory."),
874 from_utf8(included_file.absFileName()))));
882 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
887 // For verbatim and listings, we just include the contents of the file as-is.
888 // In the case of listings, we wrap it in <pre>.
889 bool const listing = isListings(params());
890 if (listing || isVerbatim(params())) {
892 xs << html::StartTag("pre");
893 // FIXME: We don't know the encoding of the file, default to UTF-8.
894 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
896 xs << html::EndTag("pre");
900 // We don't (yet) know how to Input or Include non-LyX files.
901 // (If we wanted to get really arcane, we could run some tex2html
902 // converter on the included file. But that's just masochistic.)
903 FileName const included_file = includedFileName(buffer(), params());
904 if (!isLyXFileName(included_file.absFileName())) {
906 frontend::Alert::warning(_("Unsupported Inclusion"),
907 bformat(_("LyX does not know how to include non-LyX files when "
908 "generating HTML output. Offending file:\n%1$s"),
909 params()["filename"]));
913 // In the other cases, we will generate the HTML and include it.
915 // Check we're not trying to include ourselves.
916 // FIXME RECURSIVE INCLUDE
917 if (buffer().absFileName() == included_file.absFileName()) {
918 Alert::error(_("Recursive input"),
919 bformat(_("Attempted to include file %1$s in itself! "
920 "Ignoring inclusion."), params()["filename"]));
924 Buffer const * const ibuf = loadIfNeeded();
928 // are we generating only some paragraphs, or all of them?
929 bool const all_pars = !rp.dryrun ||
930 (rp.par_begin == 0 &&
931 rp.par_end == (int)buffer().text().paragraphs().size());
933 OutputParams op = rp;
937 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
939 xs << XHTMLStream::ESCAPE_NONE
940 << "<!-- Included file: "
941 << from_utf8(included_file.absFileName())
942 << XHTMLStream::ESCAPE_NONE
948 int InsetInclude::plaintext(odocstringstream & os,
949 OutputParams const & op, size_t) const
951 // just write the filename if we're making a tooltip or toc entry,
952 // or are generating this for advanced search
953 if (op.for_tooltip || op.for_toc || op.for_search) {
954 os << '[' << screenLabel() << '\n'
955 << getParam("filename") << "\n]";
956 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
959 if (isVerbatim(params()) || isListings(params())) {
960 os << '[' << screenLabel() << '\n'
961 // FIXME: We don't know the encoding of the file, default to UTF-8.
962 << includedFileName(buffer(), params()).fileContents("UTF-8")
964 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
967 Buffer const * const ibuf = loadIfNeeded();
969 docstring const str = '[' + screenLabel() + ']';
973 writePlaintextFile(*ibuf, os, op);
978 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
980 string incfile = to_utf8(params()["filename"]);
982 // Do nothing if no file name has been specified
986 string const included_file = includedFileName(buffer(), params()).absFileName();
988 // Check we're not trying to include ourselves.
989 // FIXME RECURSIVE INCLUDE
990 // This isn't sufficient, as the inclusion could be downstream.
991 // But it'll have to do for now.
992 if (buffer().absFileName() == included_file) {
993 Alert::error(_("Recursive input"),
994 bformat(_("Attempted to include file %1$s in itself! "
995 "Ignoring inclusion."), from_utf8(incfile)));
999 string exppath = incfile;
1000 if (!runparams.export_folder.empty()) {
1001 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
1002 FileName(exppath).onlyPath().createPath();
1005 // write it to a file (so far the complete file)
1006 string const exportfile = changeExtension(exppath, ".sgml");
1007 DocFileName writefile(changeExtension(included_file, ".sgml"));
1009 Buffer * tmp = loadIfNeeded();
1011 string const mangled = writefile.mangledFileName();
1012 writefile = makeAbsPath(mangled,
1013 buffer().masterBuffer()->temppath());
1014 if (!runparams.nice)
1017 LYXERR(Debug::LATEX, "incfile:" << incfile);
1018 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
1019 LYXERR(Debug::LATEX, "writefile:" << writefile);
1021 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
1024 runparams.exportdata->addExternalFile("docbook", writefile,
1026 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1029 if (isVerbatim(params()) || isListings(params())) {
1030 os << "<inlinegraphic fileref=\""
1031 << '&' << include_label << ';'
1032 << "\" format=\"linespecific\">";
1034 os << '&' << include_label << ';';
1040 void InsetInclude::validate(LaTeXFeatures & features) const
1042 LATTEST(&buffer() == &features.buffer());
1044 string incfile = to_utf8(params()["filename"]);
1045 string const included_file =
1046 includedFileName(buffer(), params()).absFileName();
1049 if (isLyXFileName(included_file))
1050 writefile = changeExtension(included_file, ".sgml");
1052 writefile = included_file;
1054 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1055 incfile = DocFileName(writefile).mangledFileName();
1056 writefile = makeAbsPath(incfile,
1057 buffer().masterBuffer()->temppath()).absFileName();
1060 features.includeFile(include_label, writefile);
1062 features.useInsetLayout(getLayout());
1063 if (isVerbatim(params()))
1064 features.require("verbatim");
1065 else if (isListings(params())) {
1066 if (buffer().params().use_minted) {
1067 features.require("minted");
1068 string const opts = to_utf8(params()["lstparams"]);
1069 InsetListingsParams lstpars(opts);
1070 if (!lstpars.isFloat() && contains(opts, "caption="))
1071 features.require("lyxmintcaption");
1073 features.require("listings");
1076 // Here we must do the fun stuff...
1077 // Load the file in the include if it needs
1079 Buffer * const tmp = loadIfNeeded();
1081 // the file is loaded
1082 // make sure the buffer isn't us
1083 // FIXME RECURSIVE INCLUDES
1084 // This is not sufficient, as recursive includes could be
1085 // more than a file away. But it will do for now.
1086 if (tmp && tmp != &buffer()) {
1087 // We must temporarily change features.buffer,
1088 // otherwise it would always be the master buffer,
1089 // and nested includes would not work.
1090 features.setBuffer(*tmp);
1091 // Maybe this is already a child
1092 bool const is_child =
1093 features.runparams().is_child;
1094 features.runparams().is_child = true;
1095 tmp->validate(features);
1096 features.runparams().is_child = is_child;
1097 features.setBuffer(buffer());
1103 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1105 Buffer * child = loadIfNeeded();
1108 // FIXME RECURSIVE INCLUDE
1109 // This isn't sufficient, as the inclusion could be downstream.
1110 // But it'll have to do for now.
1111 if (child == &buffer())
1113 child->collectBibKeys(checkedFiles);
1117 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1119 LBUFERR(mi.base.bv);
1121 bool use_preview = false;
1122 if (RenderPreview::previewText()) {
1123 graphics::PreviewImage const * pimage =
1124 preview_->getPreviewImage(mi.base.bv->buffer());
1125 use_preview = pimage && pimage->image();
1129 preview_->metrics(mi, dim);
1133 button_.update(screenLabel(), true, false);
1135 button_.metrics(mi, dim);
1138 Box b(0, dim.wid, -dim.asc, dim.des);
1143 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1145 LBUFERR(pi.base.bv);
1147 bool use_preview = false;
1148 if (RenderPreview::previewText()) {
1149 graphics::PreviewImage const * pimage =
1150 preview_->getPreviewImage(pi.base.bv->buffer());
1151 use_preview = pimage && pimage->image();
1155 preview_->draw(pi, x, y);
1157 button_.draw(pi, x, y);
1161 void InsetInclude::write(ostream & os) const
1163 params().Write(os, &buffer());
1167 string InsetInclude::contextMenuName() const
1169 return "context-include";
1173 Inset::DisplayType InsetInclude::display() const
1175 return type(params()) == INPUT ? Inline : AlignCenter;
1179 docstring InsetInclude::layoutName() const
1181 if (isListings(params()))
1182 return from_ascii("IncludeListings");
1183 return InsetCommand::layoutName();
1191 void InsetInclude::fileChanged() const
1193 Buffer const * const buffer = updateFrontend();
1197 preview_->removePreview(*buffer);
1198 add_preview(*preview_, *this, *buffer);
1199 preview_->startLoading(*buffer);
1205 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1207 FileName const included_file = includedFileName(buffer, params);
1209 return type(params) == INPUT && params.preview() &&
1210 included_file.isReadableFile();
1214 docstring latexString(InsetInclude const & inset)
1216 odocstringstream ods;
1218 // We don't need to set runparams.encoding since this will be done
1219 // by latex() anyway.
1220 OutputParams runparams(0);
1221 runparams.flavor = OutputParams::LATEX;
1222 runparams.for_preview = true;
1223 inset.latex(os, runparams);
1229 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1230 Buffer const & buffer)
1232 InsetCommandParams const & params = inset.params();
1233 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1234 renderer.setAbsFile(includedFileName(buffer, params));
1235 docstring const snippet = latexString(inset);
1236 renderer.addPreview(snippet, buffer);
1243 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1244 graphics::PreviewLoader & ploader) const
1246 Buffer const & buffer = ploader.buffer();
1247 if (!preview_wanted(params(), buffer))
1249 preview_->setAbsFile(includedFileName(buffer, params()));
1250 docstring const snippet = latexString(*this);
1251 preview_->addPreview(snippet, ploader);
1255 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1256 UpdateType utype, TocBackend & backend) const
1258 if (isListings(params())) {
1260 label_->addToToc(cpit, output_active, utype, backend);
1261 TocBuilder & b = backend.builder("listing");
1262 b.pushItem(cpit, screenLabel(), output_active);
1263 InsetListingsParams p(to_utf8(params()["lstparams"]));
1264 b.argumentItem(from_utf8(p.getParamValue("caption")));
1266 } else if (isVerbatim(params())) {
1267 TocBuilder & b = backend.builder("child");
1268 b.pushItem(cpit, screenLabel(), output_active);
1271 Buffer const * const childbuffer = getChildBuffer();
1273 TocBuilder & b = backend.builder("child");
1274 docstring str = childbuffer ? childbuffer->fileName().displayName()
1276 b.pushItem(cpit, str, output_active);
1282 // Update the child's tocBackend. The outliner uses the master's, but
1283 // the navigation menu uses the child's.
1284 childbuffer->tocBackend().update(output_active, utype);
1285 // Include Tocs from children
1286 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1288 //Copy missing outliner names (though the user has been warned against
1289 //having different document class and module selection between master
1291 for (pair<string, docstring> const & name
1292 : childbuffer->params().documentClass().outlinerNames())
1293 backend.addName(name.first, translateIfPossible(name.second));
1298 void InsetInclude::updateCommand()
1303 docstring old_label = label_->getParam("name");
1304 label_->updateLabel(old_label);
1305 // the label might have been adapted (duplicate)
1306 docstring new_label = label_->getParam("name");
1307 if (old_label == new_label)
1310 // update listings parameters...
1311 InsetCommandParams p(INCLUDE_CODE);
1313 InsetListingsParams par(to_utf8(params()["lstparams"]));
1314 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1315 p["lstparams"] = from_utf8(par.params());
1320 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1322 button_.update(screenLabel(), true, false);
1324 Buffer const * const childbuffer = getChildBuffer();
1326 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1329 if (!isListings(params()))
1333 label_->updateBuffer(it, utype);
1335 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1336 if (par.getParamValue("caption").empty()) {
1337 listings_label_ = buffer().B_("Program Listing");
1340 Buffer const & master = *buffer().masterBuffer();
1341 Counters & counters = master.params().documentClass().counters();
1342 docstring const cnt = from_ascii("listing");
1343 listings_label_ = master.B_("Program Listing");
1344 if (counters.hasCounter(cnt)) {
1345 counters.step(cnt, utype);
1346 listings_label_ += " " + convert<docstring>(counters.value(cnt));