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();
542 // write it to a file (so far the complete file)
546 if (type(params()) == LISTINGS) {
547 exportfile = exppath;
548 mangled = DocFileName(included_file).mangledFileName();
550 exportfile = changeExtension(exppath, ".tex");
551 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
557 else if (!runparams.silent)
558 ; // no warning wanted
559 else if (!isValidLaTeXFileName(incfile)) {
560 frontend::Alert::warning(_("Invalid filename"),
561 _("The following filename will cause troubles "
562 "when running the exported file through LaTeX: ") +
564 } else if (!isValidDVIFileName(incfile)) {
565 frontend::Alert::warning(_("Problematic filename for DVI"),
566 _("The following filename can cause troubles "
567 "when running the exported file through LaTeX "
568 "and opening the resulting DVI: ") +
569 from_utf8(incfile), true);
572 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
573 buffer().temppath() : masterBuffer->temppath()));
575 LYXERR(Debug::LATEX, "incfile:" << incfile);
576 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
577 LYXERR(Debug::LATEX, "writefile:" << writefile);
579 string const tex_format = flavor2format(runparams.flavor);
581 switch (type(params())) {
584 incfile = latex_path(incfile);
586 os << '\\' << from_ascii(params().getCmdName()) << '{'
587 << from_utf8(incfile) << '}';
591 runparams.exportdata->addExternalFile(tex_format, writefile,
594 // \input wants file with extension (default is .tex)
595 if (!isLyXFileName(included_file.absFileName())) {
596 incfile = latex_path(incfile);
598 os << '\\' << from_ascii(params().getCmdName())
599 << '{' << from_utf8(incfile) << '}';
601 incfile = changeExtension(incfile, ".tex");
602 incfile = latex_path(incfile);
604 os << '\\' << from_ascii(params().getCmdName())
605 << '{' << from_utf8(incfile) << '}';
610 // Here, listings and minted have sligthly different behaviors.
611 // Using listings, it is always possible to have a caption,
612 // even for non-floats. Using minted, only floats can have a
613 // caption. So, with minted we use the following strategy.
614 // If a caption was specified but the float parameter was not,
615 // we ourselves add a caption above the listing (because the
616 // listing comes from a file and might span several pages).
617 // Otherwise, if float was specified, the floating listing
618 // environment provided by minted is used. In either case, the
619 // label parameter is taken as the label by which the float
620 // can be referenced, otherwise it will have the meaning
621 // intended by minted. In this last case, the label will
622 // serve as a sort of caption that, however, will be shown
623 // by minted only if the frame parameter is also specified.
624 bool const use_minted = buffer().params().use_minted;
625 runparams.exportdata->addExternalFile(tex_format, writefile,
627 string const opt = to_utf8(params()["lstparams"]);
628 // opt is set in QInclude dialog and should have passed validation.
629 InsetListingsParams lstparams(opt);
630 docstring parameters = from_utf8(lstparams.params());
635 bool isfloat = lstparams.isFloat();
636 // We are going to split parameters at commas, so
637 // replace commas that are not parameter separators
638 // with a code point from the private use area
639 char_type comma = replaceCommaInBraces(parameters);
640 // Get float placement, language, caption, and
641 // label, then remove the relative options if minted.
642 vector<docstring> opts =
643 getVectorFromString(parameters, from_ascii(","), false);
644 vector<docstring> latexed_opts;
645 for (size_t i = 0; i < opts.size(); ++i) {
646 // Restore replaced commas
647 opts[i] = subst(opts[i], comma, ',');
648 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
649 if (prefixIs(opts[i], from_ascii("float=")))
650 placement = opts[i].substr(6);
651 opts.erase(opts.begin() + i--);
652 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
653 language = opts[i].substr(9);
654 opts.erase(opts.begin() + i--);
655 } else if (prefixIs(opts[i], from_ascii("caption="))) {
656 // FIXME We should use HANDLING_LATEXIFY here,
657 // but that's a file format change (see #10455).
658 caption = opts[i].substr(8);
659 opts.erase(opts.begin() + i--);
661 latexed_opts.push_back(from_ascii("caption=") + caption);
662 } else if (prefixIs(opts[i], from_ascii("label="))) {
663 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
664 ParamInfo::HANDLING_ESCAPE);
665 opts.erase(opts.begin() + i--);
667 latexed_opts.push_back(from_ascii("label={") + label + "}");
669 if (use_minted && !label.empty()) {
670 if (isfloat || !caption.empty())
671 label = trim(label, "{}");
673 opts.push_back(from_ascii("label=") + label);
676 if (!latexed_opts.empty())
677 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
678 parameters = getStringFromVector(opts, from_ascii(","));
679 if (language.empty())
680 language = from_ascii("TeX");
681 if (use_minted && isfloat) {
682 os << breakln << "\\begin{listing}";
683 if (!placement.empty())
684 os << '[' << placement << "]";
686 } else if (use_minted && !caption.empty()) {
687 os << breakln << "\\lyxmintcaption[t]{" << caption;
689 os << "\\label{" << label << "}";
692 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
693 if (!parameters.empty())
694 os << "[" << parameters << "]";
696 os << '{' << ascii_lowercase(language) << '}';
697 os << '{' << incfile << '}';
698 if (use_minted && isfloat) {
699 if (!caption.empty())
700 os << breakln << "\\caption{" << caption << "}";
702 os << breakln << "\\label{" << label << "}";
703 os << breakln << "\\end{listing}\n";
708 runparams.exportdata->addExternalFile(tex_format, writefile,
711 // \include don't want extension and demands that the
712 // file really have .tex
713 incfile = changeExtension(incfile, string());
714 incfile = latex_path(incfile);
716 os << '\\' << from_ascii(params().getCmdName()) << '{'
717 << from_utf8(incfile) << '}';
724 if (runparams.inComment || runparams.dryrun)
725 // Don't try to load or copy the file if we're
726 // in a comment or doing a dryrun
729 if (isInputOrInclude(params()) &&
730 isLyXFileName(included_file.absFileName())) {
731 // if it's a LyX file and we're inputting or including,
732 // try to load it so we can write the associated latex
734 Buffer * tmp = loadIfNeeded();
736 if (!runparams.silent) {
737 docstring text = bformat(_("Could not load included "
739 "Please, check whether it actually exists."),
740 included_file.displayName());
741 throw ExceptionMessage(ErrorException, _("Error: "),
747 if (!runparams.silent) {
748 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
750 docstring text = bformat(_("Included file `%1$s'\n"
751 "has textclass `%2$s'\n"
752 "while parent file has textclass `%3$s'."),
753 included_file.displayName(),
754 from_utf8(tmp->params().documentClass().name()),
755 from_utf8(masterBuffer->params().documentClass().name()));
756 Alert::warning(_("Different textclasses"), text, true);
759 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
760 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
761 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
762 docstring text = bformat(_("Included file `%1$s'\n"
763 "has use-non-TeX-fonts set to `%2$s'\n"
764 "while parent file has use-non-TeX-fonts set to `%3$s'."),
765 included_file.displayName(),
767 from_utf8(master_tf));
768 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
771 // Make sure modules used in child are all included in master
772 // FIXME It might be worth loading the children's modules into the master
773 // over in BufferParams rather than doing this check.
774 LayoutModuleList const masterModules = masterBuffer->params().getModules();
775 LayoutModuleList const childModules = tmp->params().getModules();
776 LayoutModuleList::const_iterator it = childModules.begin();
777 LayoutModuleList::const_iterator end = childModules.end();
778 for (; it != end; ++it) {
779 string const module = *it;
780 LayoutModuleList::const_iterator found =
781 find(masterModules.begin(), masterModules.end(), module);
782 if (found == masterModules.end()) {
783 docstring text = bformat(_("Included file `%1$s'\n"
784 "uses module `%2$s'\n"
785 "which is not used in parent file."),
786 included_file.displayName(), from_utf8(module));
787 Alert::warning(_("Module not found"), text, true);
792 tmp->markDepClean(masterBuffer->temppath());
794 // Don't assume the child's format is latex
795 string const inc_format = tmp->params().bufferFormat();
796 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
797 theFormats().extension(inc_format)));
799 // FIXME: handle non existing files
800 // The included file might be written in a different encoding
802 Encoding const * const oldEnc = runparams.encoding;
803 Language const * const oldLang = runparams.master_language;
804 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
805 // the children must be encoded in plain utf8!
806 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
807 encodings.fromLyXName("utf8-plain")
808 : &tmp->params().encoding();
809 runparams.master_language = buffer().params().language;
810 runparams.par_begin = 0;
811 runparams.par_end = tmp->paragraphs().size();
812 runparams.is_child = true;
813 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
814 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
815 if (!runparams.silent) {
816 docstring msg = bformat(_("Included file `%1$s' "
817 "was not exported correctly.\n "
818 "LaTeX export is probably incomplete."),
819 included_file.displayName());
820 ErrorList const & el = tmp->errorList("Export");
822 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
823 msg, el.begin()->error,
824 el.begin()->description);
825 throw ExceptionMessage(ErrorException, _("Error: "),
829 runparams.encoding = oldEnc;
830 runparams.master_language = oldLang;
831 runparams.is_child = false;
833 // If needed, use converters to produce a latex file from the child
834 if (tmpwritefile != writefile) {
837 theConverters().convert(tmp, tmpwritefile, writefile,
839 inc_format, tex_format, el);
841 if (!success && !runparams.silent) {
842 docstring msg = bformat(_("Included file `%1$s' "
843 "was not exported correctly.\n "
844 "LaTeX export is probably incomplete."),
845 included_file.displayName());
847 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
848 msg, el.begin()->error,
849 el.begin()->description);
850 throw ExceptionMessage(ErrorException, _("Error: "),
855 // In this case, it's not a LyX file, so we copy the file
856 // to the temp dir, so that .aux files etc. are not created
857 // in the original dir. Files included by this file will be
858 // found via either the environment variable TEXINPUTS, or
859 // input@path, see ../Buffer.cpp.
860 unsigned long const checksum_in = included_file.checksum();
861 unsigned long const checksum_out = writefile.checksum();
863 if (checksum_in != checksum_out) {
864 if (!included_file.copyTo(writefile)) {
867 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
868 "into the temporary directory."),
869 from_utf8(included_file.absFileName()))));
877 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
882 // For verbatim and listings, we just include the contents of the file as-is.
883 // In the case of listings, we wrap it in <pre>.
884 bool const listing = isListings(params());
885 if (listing || isVerbatim(params())) {
887 xs << html::StartTag("pre");
888 // FIXME: We don't know the encoding of the file, default to UTF-8.
889 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
891 xs << html::EndTag("pre");
895 // We don't (yet) know how to Input or Include non-LyX files.
896 // (If we wanted to get really arcane, we could run some tex2html
897 // converter on the included file. But that's just masochistic.)
898 FileName const included_file = includedFileName(buffer(), params());
899 if (!isLyXFileName(included_file.absFileName())) {
901 frontend::Alert::warning(_("Unsupported Inclusion"),
902 bformat(_("LyX does not know how to include non-LyX files when "
903 "generating HTML output. Offending file:\n%1$s"),
904 params()["filename"]));
908 // In the other cases, we will generate the HTML and include it.
910 // Check we're not trying to include ourselves.
911 // FIXME RECURSIVE INCLUDE
912 if (buffer().absFileName() == included_file.absFileName()) {
913 Alert::error(_("Recursive input"),
914 bformat(_("Attempted to include file %1$s in itself! "
915 "Ignoring inclusion."), params()["filename"]));
919 Buffer const * const ibuf = loadIfNeeded();
923 // are we generating only some paragraphs, or all of them?
924 bool const all_pars = !rp.dryrun ||
925 (rp.par_begin == 0 &&
926 rp.par_end == (int)buffer().text().paragraphs().size());
928 OutputParams op = rp;
932 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
934 xs << XHTMLStream::ESCAPE_NONE
935 << "<!-- Included file: "
936 << from_utf8(included_file.absFileName())
937 << XHTMLStream::ESCAPE_NONE
943 int InsetInclude::plaintext(odocstringstream & os,
944 OutputParams const & op, size_t) const
946 // just write the filename if we're making a tooltip or toc entry,
947 // or are generating this for advanced search
948 if (op.for_tooltip || op.for_toc || op.for_search) {
949 os << '[' << screenLabel() << '\n'
950 << getParam("filename") << "\n]";
951 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
954 if (isVerbatim(params()) || isListings(params())) {
955 os << '[' << screenLabel() << '\n'
956 // FIXME: We don't know the encoding of the file, default to UTF-8.
957 << includedFileName(buffer(), params()).fileContents("UTF-8")
959 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
962 Buffer const * const ibuf = loadIfNeeded();
964 docstring const str = '[' + screenLabel() + ']';
968 writePlaintextFile(*ibuf, os, op);
973 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
975 string incfile = to_utf8(params()["filename"]);
977 // Do nothing if no file name has been specified
981 string const included_file = includedFileName(buffer(), params()).absFileName();
983 // Check we're not trying to include ourselves.
984 // FIXME RECURSIVE INCLUDE
985 // This isn't sufficient, as the inclusion could be downstream.
986 // But it'll have to do for now.
987 if (buffer().absFileName() == included_file) {
988 Alert::error(_("Recursive input"),
989 bformat(_("Attempted to include file %1$s in itself! "
990 "Ignoring inclusion."), from_utf8(incfile)));
994 string exppath = incfile;
995 if (!runparams.export_folder.empty()) {
996 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
997 FileName(exppath).onlyPath().createPath();
1000 // write it to a file (so far the complete file)
1001 string const exportfile = changeExtension(exppath, ".sgml");
1002 DocFileName writefile(changeExtension(included_file, ".sgml"));
1004 Buffer * tmp = loadIfNeeded();
1006 string const mangled = writefile.mangledFileName();
1007 writefile = makeAbsPath(mangled,
1008 buffer().masterBuffer()->temppath());
1009 if (!runparams.nice)
1012 LYXERR(Debug::LATEX, "incfile:" << incfile);
1013 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
1014 LYXERR(Debug::LATEX, "writefile:" << writefile);
1016 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
1019 runparams.exportdata->addExternalFile("docbook", writefile,
1021 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1024 if (isVerbatim(params()) || isListings(params())) {
1025 os << "<inlinegraphic fileref=\""
1026 << '&' << include_label << ';'
1027 << "\" format=\"linespecific\">";
1029 os << '&' << include_label << ';';
1035 void InsetInclude::validate(LaTeXFeatures & features) const
1037 LATTEST(&buffer() == &features.buffer());
1039 string incfile = to_utf8(params()["filename"]);
1040 string const included_file =
1041 includedFileName(buffer(), params()).absFileName();
1044 if (isLyXFileName(included_file))
1045 writefile = changeExtension(included_file, ".sgml");
1047 writefile = included_file;
1049 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1050 incfile = DocFileName(writefile).mangledFileName();
1051 writefile = makeAbsPath(incfile,
1052 buffer().masterBuffer()->temppath()).absFileName();
1055 features.includeFile(include_label, writefile);
1057 features.useInsetLayout(getLayout());
1058 if (isVerbatim(params()))
1059 features.require("verbatim");
1060 else if (isListings(params())) {
1061 if (buffer().params().use_minted) {
1062 features.require("minted");
1063 string const opts = to_utf8(params()["lstparams"]);
1064 InsetListingsParams lstpars(opts);
1065 if (!lstpars.isFloat() && contains(opts, "caption="))
1066 features.require("lyxmintcaption");
1068 features.require("listings");
1071 // Here we must do the fun stuff...
1072 // Load the file in the include if it needs
1074 Buffer * const tmp = loadIfNeeded();
1076 // the file is loaded
1077 // make sure the buffer isn't us
1078 // FIXME RECURSIVE INCLUDES
1079 // This is not sufficient, as recursive includes could be
1080 // more than a file away. But it will do for now.
1081 if (tmp && tmp != &buffer()) {
1082 // We must temporarily change features.buffer,
1083 // otherwise it would always be the master buffer,
1084 // and nested includes would not work.
1085 features.setBuffer(*tmp);
1086 // Maybe this is already a child
1087 bool const is_child =
1088 features.runparams().is_child;
1089 features.runparams().is_child = true;
1090 tmp->validate(features);
1091 features.runparams().is_child = is_child;
1092 features.setBuffer(buffer());
1098 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1100 Buffer * child = loadIfNeeded();
1103 // FIXME RECURSIVE INCLUDE
1104 // This isn't sufficient, as the inclusion could be downstream.
1105 // But it'll have to do for now.
1106 if (child == &buffer())
1108 child->collectBibKeys(checkedFiles);
1112 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1114 LBUFERR(mi.base.bv);
1116 bool use_preview = false;
1117 if (RenderPreview::previewText()) {
1118 graphics::PreviewImage const * pimage =
1119 preview_->getPreviewImage(mi.base.bv->buffer());
1120 use_preview = pimage && pimage->image();
1124 preview_->metrics(mi, dim);
1128 button_.update(screenLabel(), true, false);
1130 button_.metrics(mi, dim);
1133 Box b(0, dim.wid, -dim.asc, dim.des);
1138 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1140 LBUFERR(pi.base.bv);
1142 bool use_preview = false;
1143 if (RenderPreview::previewText()) {
1144 graphics::PreviewImage const * pimage =
1145 preview_->getPreviewImage(pi.base.bv->buffer());
1146 use_preview = pimage && pimage->image();
1150 preview_->draw(pi, x, y);
1152 button_.draw(pi, x, y);
1156 void InsetInclude::write(ostream & os) const
1158 params().Write(os, &buffer());
1162 string InsetInclude::contextMenuName() const
1164 return "context-include";
1168 Inset::DisplayType InsetInclude::display() const
1170 return type(params()) == INPUT ? Inline : AlignCenter;
1174 docstring InsetInclude::layoutName() const
1176 if (isListings(params()))
1177 return from_ascii("IncludeListings");
1178 return InsetCommand::layoutName();
1186 void InsetInclude::fileChanged() const
1188 Buffer const * const buffer = updateFrontend();
1192 preview_->removePreview(*buffer);
1193 add_preview(*preview_, *this, *buffer);
1194 preview_->startLoading(*buffer);
1200 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1202 FileName const included_file = includedFileName(buffer, params);
1204 return type(params) == INPUT && params.preview() &&
1205 included_file.isReadableFile();
1209 docstring latexString(InsetInclude const & inset)
1211 odocstringstream ods;
1213 // We don't need to set runparams.encoding since this will be done
1214 // by latex() anyway.
1215 OutputParams runparams(0);
1216 runparams.flavor = OutputParams::LATEX;
1217 runparams.for_preview = true;
1218 inset.latex(os, runparams);
1224 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1225 Buffer const & buffer)
1227 InsetCommandParams const & params = inset.params();
1228 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1229 renderer.setAbsFile(includedFileName(buffer, params));
1230 docstring const snippet = latexString(inset);
1231 renderer.addPreview(snippet, buffer);
1238 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1239 graphics::PreviewLoader & ploader) const
1241 Buffer const & buffer = ploader.buffer();
1242 if (!preview_wanted(params(), buffer))
1244 preview_->setAbsFile(includedFileName(buffer, params()));
1245 docstring const snippet = latexString(*this);
1246 preview_->addPreview(snippet, ploader);
1250 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1251 UpdateType utype, TocBackend & backend) const
1253 if (isListings(params())) {
1255 label_->addToToc(cpit, output_active, utype, backend);
1256 TocBuilder & b = backend.builder("listing");
1257 b.pushItem(cpit, screenLabel(), output_active);
1258 InsetListingsParams p(to_utf8(params()["lstparams"]));
1259 b.argumentItem(from_utf8(p.getParamValue("caption")));
1261 } else if (isVerbatim(params())) {
1262 TocBuilder & b = backend.builder("child");
1263 b.pushItem(cpit, screenLabel(), output_active);
1266 Buffer const * const childbuffer = getChildBuffer();
1268 TocBuilder & b = backend.builder("child");
1269 docstring str = childbuffer ? childbuffer->fileName().displayName()
1271 b.pushItem(cpit, str, output_active);
1277 // Update the child's tocBackend. The outliner uses the master's, but
1278 // the navigation menu uses the child's.
1279 childbuffer->tocBackend().update(output_active, utype);
1280 // Include Tocs from children
1281 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1283 //Copy missing outliner names (though the user has been warned against
1284 //having different document class and module selection between master
1286 for (pair<string, docstring> const & name
1287 : childbuffer->params().documentClass().outlinerNames())
1288 backend.addName(name.first, translateIfPossible(name.second));
1293 void InsetInclude::updateCommand()
1298 docstring old_label = label_->getParam("name");
1299 label_->updateLabel(old_label);
1300 // the label might have been adapted (duplicate)
1301 docstring new_label = label_->getParam("name");
1302 if (old_label == new_label)
1305 // update listings parameters...
1306 InsetCommandParams p(INCLUDE_CODE);
1308 InsetListingsParams par(to_utf8(params()["lstparams"]));
1309 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1310 p["lstparams"] = from_utf8(par.params());
1315 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1317 button_.update(screenLabel(), true, false);
1319 Buffer const * const childbuffer = getChildBuffer();
1321 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1324 if (!isListings(params()))
1328 label_->updateBuffer(it, utype);
1330 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1331 if (par.getParamValue("caption").empty()) {
1332 listings_label_ = buffer().B_("Program Listing");
1335 Buffer const & master = *buffer().masterBuffer();
1336 Counters & counters = master.params().documentClass().counters();
1337 docstring const cnt = from_ascii("listing");
1338 listings_label_ = master.B_("Program Listing");
1339 if (counters.hasCounter(cnt)) {
1340 counters.step(cnt, utype);
1341 listings_label_ += " " + convert<docstring>(counters.value(cnt));