2 * \file InsetInclude.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
7 * \author Richard Heck (conversion to InsetCommand)
9 * Full author contact details are available in file CREDITS.
14 #include "InsetInclude.h"
17 #include "buffer_funcs.h"
18 #include "BufferList.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "Converter.h"
23 #include "DispatchResult.h"
25 #include "ErrorList.h"
28 #include "FuncRequest.h"
29 #include "FuncStatus.h"
30 #include "LaTeXFeatures.h"
31 #include "LayoutFile.h"
32 #include "LayoutModuleList.h"
35 #include "MetricsInfo.h"
36 #include "output_plaintext.h"
37 #include "output_xhtml.h"
38 #include "OutputParams.h"
39 #include "texstream.h"
40 #include "TextClass.h"
41 #include "TocBackend.h"
43 #include "frontends/alert.h"
44 #include "frontends/Painter.h"
46 #include "graphics/PreviewImage.h"
47 #include "graphics/PreviewLoader.h"
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetListingsParams.h"
51 #include "insets/RenderPreview.h"
53 #include "mathed/MacroTable.h"
55 #include "support/convert.h"
56 #include "support/debug.h"
57 #include "support/docstream.h"
58 #include "support/FileNameList.h"
59 #include "support/filetools.h"
60 #include "support/gettext.h"
61 #include "support/lassert.h"
62 #include "support/lstrings.h" // contains
63 #include "support/lyxalgo.h"
64 #include "support/mutex.h"
65 #include "support/ExceptionMessage.h"
67 #include "support/bind.h"
70 using namespace lyx::support;
74 namespace Alert = frontend::Alert;
79 docstring const uniqueID()
81 static unsigned int seed = 1000;
83 Mutex::Locker lock(&mutex);
84 return "file" + convert<docstring>(++seed);
88 /// the type of inclusion
90 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
94 Types type(string const & s)
98 if (s == "verbatiminput")
100 if (s == "verbatiminput*")
102 if (s == "lstinputlisting" || s == "inputminted")
110 Types type(InsetCommandParams const & params)
112 return type(params.getCmdName());
116 bool isListings(InsetCommandParams const & params)
118 return type(params) == LISTINGS;
122 bool isVerbatim(InsetCommandParams const & params)
124 Types const t = type(params);
125 return t == VERB || t == VERBAST;
129 bool isInputOrInclude(InsetCommandParams const & params)
131 Types const t = type(params);
132 return t == INPUT || t == INCLUDE;
136 FileName const masterFileName(Buffer const & buffer)
138 return buffer.masterBuffer()->fileName();
142 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
145 string const parentFileName(Buffer const & buffer)
147 return buffer.absFileName();
151 FileName const includedFileName(Buffer const & buffer,
152 InsetCommandParams const & params)
154 return makeAbsPath(to_utf8(params["filename"]),
155 onlyPath(parentFileName(buffer)));
159 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
161 if (label_str.empty())
163 InsetCommandParams icp(LABEL_CODE);
164 icp["name"] = label_str;
165 return new InsetLabel(buf, icp);
171 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
172 : InsetCommand(buf, p), include_label(uniqueID()),
173 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
174 set_label_(false), label_(0), child_buffer_(0)
176 preview_->connect([=](){ fileChanged(); });
178 if (isListings(params())) {
179 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
180 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
181 } else if (isInputOrInclude(params()) && buf)
186 InsetInclude::InsetInclude(InsetInclude const & other)
187 : InsetCommand(other), include_label(other.include_label),
188 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
189 set_label_(false), label_(0), child_buffer_(0)
191 preview_->connect([=](){ fileChanged(); });
194 label_ = new InsetLabel(*other.label_);
198 InsetInclude::~InsetInclude()
204 void InsetInclude::setBuffer(Buffer & buffer)
206 InsetCommand::setBuffer(buffer);
208 label_->setBuffer(buffer);
212 void InsetInclude::setChildBuffer(Buffer * buffer)
214 child_buffer_ = buffer;
218 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
221 // This is only correct for the case of listings, but it'll do for now.
222 // In the other cases, this second parameter should just be empty.
223 static ParamInfo param_info_;
224 if (param_info_.empty()) {
225 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
226 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
232 bool InsetInclude::isCompatibleCommand(string const & s)
234 return type(s) != NONE;
238 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
240 switch (cmd.action()) {
242 case LFUN_INSET_EDIT: {
243 editIncluded(to_utf8(params()["filename"]));
247 case LFUN_INSET_MODIFY: {
248 // It should be OK just to invalidate the cache in setParams()
250 // child_buffer_ = 0;
251 InsetCommandParams p(INCLUDE_CODE);
252 if (cmd.getArg(0) == "changetype") {
254 InsetCommand::doDispatch(cur, cmd);
257 InsetCommand::string2params(to_utf8(cmd.argument()), p);
258 if (!p.getCmdName().empty()) {
260 InsetListingsParams new_params(to_utf8(p["lstparams"]));
261 docstring const new_label =
262 from_utf8(new_params.getParamValue("label"));
264 if (new_label.empty()) {
270 old_label = label_->getParam("name");
272 label_ = createLabel(buffer_, new_label);
273 label_->setBuffer(buffer());
276 if (new_label != old_label) {
277 label_->updateLabelAndRefs(new_label, &cur);
278 // the label might have been adapted (duplicate)
279 if (new_label != label_->getParam("name")) {
280 new_params.addParam("label", "{" +
281 to_utf8(label_->getParam("name")) + "}", true);
282 p["lstparams"] = from_utf8(new_params.params());
289 cur.forceBufferUpdate();
291 cur.noScreenUpdate();
295 //pass everything else up the chain
297 InsetCommand::doDispatch(cur, cmd);
303 void InsetInclude::editIncluded(string const & file)
305 string const ext = support::getExtension(file);
307 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
310 // tex file or other text file in verbatim mode
311 theFormats().edit(buffer(),
312 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
317 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
318 FuncStatus & flag) const
320 switch (cmd.action()) {
322 case LFUN_INSET_EDIT:
323 flag.setEnabled(true);
326 case LFUN_INSET_MODIFY:
327 if (cmd.getArg(0) == "changetype")
328 return InsetCommand::getStatus(cur, cmd, flag);
330 flag.setEnabled(true);
334 return InsetCommand::getStatus(cur, cmd, flag);
339 void InsetInclude::setParams(InsetCommandParams const & p)
341 // invalidate the cache
344 InsetCommand::setParams(p);
347 if (preview_->monitoring())
348 preview_->stopMonitoring();
350 if (type(params()) == INPUT)
351 add_preview(*preview_, *this, buffer());
355 bool InsetInclude::isChildIncluded() const
357 std::list<std::string> includeonlys =
358 buffer().params().getIncludedChildren();
359 if (includeonlys.empty())
361 return (std::find(includeonlys.begin(),
363 to_utf8(params()["filename"])) != includeonlys.end());
367 docstring InsetInclude::screenLabel() const
371 switch (type(params())) {
373 temp = buffer().B_("Input");
376 temp = buffer().B_("Verbatim Input");
379 temp = buffer().B_("Verbatim Input*");
382 if (isChildIncluded())
383 temp = buffer().B_("Include");
385 temp += buffer().B_("Include (excluded)");
388 temp = listings_label_;
391 LASSERT(false, temp = buffer().B_("Unknown"));
397 if (params()["filename"].empty())
400 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
406 Buffer * InsetInclude::getChildBuffer() const
408 Buffer * childBuffer = loadIfNeeded();
410 // FIXME RECURSIVE INCLUDE
411 // This isn't sufficient, as the inclusion could be downstream.
412 // But it'll have to do for now.
413 return (childBuffer == &buffer()) ? 0 : childBuffer;
417 Buffer * InsetInclude::loadIfNeeded() const
419 // This is for background export and preview. We don't even want to
420 // try to load the cloned child document again.
421 if (buffer().isClone())
422 return child_buffer_;
424 // Don't try to load it again if we failed before.
425 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
428 FileName const included_file = includedFileName(buffer(), params());
429 // Use cached Buffer if possible.
430 if (child_buffer_ != 0) {
431 if (theBufferList().isLoaded(child_buffer_)
432 // additional sanity check: make sure the Buffer really is
433 // associated with the file we want.
434 && child_buffer_ == theBufferList().getBuffer(included_file))
435 return child_buffer_;
436 // Buffer vanished, so invalidate cache and try to reload.
440 if (!isLyXFileName(included_file.absFileName()))
443 Buffer * child = theBufferList().getBuffer(included_file);
445 // the readonly flag can/will be wrong, not anymore I think.
446 if (!included_file.exists())
449 child = theBufferList().newBuffer(included_file.absFileName());
451 // Buffer creation is not possible.
454 // Set parent before loading, such that macros can be tracked
455 child->setParent(&buffer());
457 if (child->loadLyXFile() != Buffer::ReadSuccess) {
458 failedtoload_ = true;
460 //close the buffer we just opened
461 theBufferList().release(child);
465 if (!child->errorList("Parse").empty()) {
466 // FIXME: Do something.
469 // The file was already loaded, so, simply
470 // inform parent buffer about local macros.
471 Buffer const * parent = &buffer();
472 child->setParent(parent);
474 child->listMacroNames(macros);
475 MacroNameSet::const_iterator cit = macros.begin();
476 MacroNameSet::const_iterator end = macros.end();
477 for (; cit != end; ++cit)
478 parent->usermacros.insert(*cit);
481 // Cache the child buffer.
482 child_buffer_ = child;
487 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
489 string incfile = to_utf8(params()["filename"]);
491 // Do nothing if no file name has been specified
495 FileName const included_file = includedFileName(buffer(), params());
497 // Check we're not trying to include ourselves.
498 // FIXME RECURSIVE INCLUDE
499 // This isn't sufficient, as the inclusion could be downstream.
500 // But it'll have to do for now.
501 if (isInputOrInclude(params()) &&
502 buffer().absFileName() == included_file.absFileName())
504 Alert::error(_("Recursive input"),
505 bformat(_("Attempted to include file %1$s in itself! "
506 "Ignoring inclusion."), from_utf8(incfile)));
510 Buffer const * const masterBuffer = buffer().masterBuffer();
512 // if incfile is relative, make it relative to the master
514 if (!FileName::isAbsolute(incfile)) {
516 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
517 from_utf8(masterBuffer->filePath())));
520 string exppath = incfile;
521 if (!runparams.export_folder.empty()) {
522 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
523 FileName(exppath).onlyPath().createPath();
526 // write it to a file (so far the complete file)
530 if (type(params()) == LISTINGS) {
531 exportfile = exppath;
532 mangled = DocFileName(included_file).mangledFileName();
534 exportfile = changeExtension(exppath, ".tex");
535 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
541 else if (!runparams.silent)
542 ; // no warning wanted
543 else if (!isValidLaTeXFileName(incfile)) {
544 frontend::Alert::warning(_("Invalid filename"),
545 _("The following filename will cause troubles "
546 "when running the exported file through LaTeX: ") +
548 } else if (!isValidDVIFileName(incfile)) {
549 frontend::Alert::warning(_("Problematic filename for DVI"),
550 _("The following filename can cause troubles "
551 "when running the exported file through LaTeX "
552 "and opening the resulting DVI: ") +
553 from_utf8(incfile), true);
556 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
557 buffer().temppath() : masterBuffer->temppath()));
559 LYXERR(Debug::LATEX, "incfile:" << incfile);
560 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
561 LYXERR(Debug::LATEX, "writefile:" << writefile);
563 string const tex_format = flavor2format(runparams.flavor);
565 switch (type(params())) {
568 incfile = latex_path(incfile);
570 os << '\\' << from_ascii(params().getCmdName()) << '{'
571 << from_utf8(incfile) << '}';
575 runparams.exportdata->addExternalFile(tex_format, writefile,
578 // \input wants file with extension (default is .tex)
579 if (!isLyXFileName(included_file.absFileName())) {
580 incfile = latex_path(incfile);
582 os << '\\' << from_ascii(params().getCmdName())
583 << '{' << from_utf8(incfile) << '}';
585 incfile = changeExtension(incfile, ".tex");
586 incfile = latex_path(incfile);
588 os << '\\' << from_ascii(params().getCmdName())
589 << '{' << from_utf8(incfile) << '}';
594 // Here, listings and minted have sligthly different behaviors.
595 // Using listings, it is always possible to have a caption,
596 // even for non-floats. Using minted, only floats can have a
597 // caption. So, with minted we use the following strategy.
598 // If a caption was specified but the float parameter was not,
599 // we ourselves add a caption above the listing (because the
600 // listing comes from a file and might span several pages).
601 // Otherwise, if float was specified, the floating listing
602 // environment provided by minted is used. In either case, the
603 // label parameter is taken as the label by which the float
604 // can be referenced, otherwise it will have the meaning
605 // intended by minted. In this last case, the label will
606 // serve as a sort of caption that, however, will be shown
607 // by minted only if the frame parameter is also specified.
608 bool const use_minted = buffer().params().use_minted;
609 runparams.exportdata->addExternalFile(tex_format, writefile,
611 string const opt = to_utf8(params()["lstparams"]);
612 // opt is set in QInclude dialog and should have passed validation.
613 InsetListingsParams lstparams(opt);
614 docstring parameters = from_utf8(lstparams.params());
619 bool isfloat = lstparams.isFloat();
620 // Get float placement, language, caption, and
621 // label, then remove the relative options if minted.
622 vector<docstring> opts =
623 getVectorFromString(parameters, from_ascii(","), false);
624 vector<docstring> latexed_opts;
625 for (size_t i = 0; i < opts.size(); ++i) {
626 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
627 if (prefixIs(opts[i], from_ascii("float=")))
628 placement = opts[i].substr(6);
629 opts.erase(opts.begin() + i--);
630 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
631 language = opts[i].substr(9);
632 opts.erase(opts.begin() + i--);
633 } else if (prefixIs(opts[i], from_ascii("caption="))) {
634 // FIXME We should use HANDLING_LATEXIFY here,
635 // but that's a file format change (see #10455).
636 caption = opts[i].substr(8);
637 opts.erase(opts.begin() + i--);
639 latexed_opts.push_back(from_ascii("caption=") + caption);
640 } else if (prefixIs(opts[i], from_ascii("label="))) {
641 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
642 ParamInfo::HANDLING_ESCAPE);
643 opts.erase(opts.begin() + i--);
645 latexed_opts.push_back(from_ascii("label={") + label + "}");
647 if (use_minted && !label.empty()) {
648 if (isfloat || !caption.empty())
649 label = trim(label, "{}");
651 opts.push_back(from_ascii("label=") + label);
654 if (!latexed_opts.empty())
655 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
656 parameters = getStringFromVector(opts, from_ascii(","));
657 if (language.empty())
658 language = from_ascii("TeX");
659 if (use_minted && isfloat) {
660 os << breakln << "\\begin{listing}";
661 if (!placement.empty())
662 os << '[' << placement << "]";
664 } else if (use_minted && !caption.empty()) {
665 os << breakln << "\\lyxmintcaption[t]{" << caption;
667 os << "\\label{" << label << "}";
670 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
671 if (!parameters.empty())
672 os << "[" << parameters << "]";
674 os << '{' << ascii_lowercase(language) << '}';
675 os << '{' << incfile << '}';
676 if (use_minted && isfloat) {
677 if (!caption.empty())
678 os << breakln << "\\caption{" << caption << "}";
680 os << breakln << "\\label{" << label << "}";
681 os << breakln << "\\end{listing}\n";
686 runparams.exportdata->addExternalFile(tex_format, writefile,
689 // \include don't want extension and demands that the
690 // file really have .tex
691 incfile = changeExtension(incfile, string());
692 incfile = latex_path(incfile);
694 os << '\\' << from_ascii(params().getCmdName()) << '{'
695 << from_utf8(incfile) << '}';
702 if (runparams.inComment || runparams.dryrun)
703 // Don't try to load or copy the file if we're
704 // in a comment or doing a dryrun
707 if (isInputOrInclude(params()) &&
708 isLyXFileName(included_file.absFileName())) {
709 // if it's a LyX file and we're inputting or including,
710 // try to load it so we can write the associated latex
712 Buffer * tmp = loadIfNeeded();
714 if (!runparams.silent) {
715 docstring text = bformat(_("Could not load included "
717 "Please, check whether it actually exists."),
718 included_file.displayName());
719 throw ExceptionMessage(ErrorException, _("Error: "),
725 if (!runparams.silent) {
726 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
728 docstring text = bformat(_("Included file `%1$s'\n"
729 "has textclass `%2$s'\n"
730 "while parent file has textclass `%3$s'."),
731 included_file.displayName(),
732 from_utf8(tmp->params().documentClass().name()),
733 from_utf8(masterBuffer->params().documentClass().name()));
734 Alert::warning(_("Different textclasses"), text, true);
737 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
738 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
739 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
740 docstring text = bformat(_("Included file `%1$s'\n"
741 "has use-non-TeX-fonts set to `%2$s'\n"
742 "while parent file has use-non-TeX-fonts set to `%3$s'."),
743 included_file.displayName(),
745 from_utf8(master_tf));
746 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
749 // Make sure modules used in child are all included in master
750 // FIXME It might be worth loading the children's modules into the master
751 // over in BufferParams rather than doing this check.
752 LayoutModuleList const masterModules = masterBuffer->params().getModules();
753 LayoutModuleList const childModules = tmp->params().getModules();
754 LayoutModuleList::const_iterator it = childModules.begin();
755 LayoutModuleList::const_iterator end = childModules.end();
756 for (; it != end; ++it) {
757 string const module = *it;
758 LayoutModuleList::const_iterator found =
759 find(masterModules.begin(), masterModules.end(), module);
760 if (found == masterModules.end()) {
761 docstring text = bformat(_("Included file `%1$s'\n"
762 "uses module `%2$s'\n"
763 "which is not used in parent file."),
764 included_file.displayName(), from_utf8(module));
765 Alert::warning(_("Module not found"), text, true);
770 tmp->markDepClean(masterBuffer->temppath());
772 // Don't assume the child's format is latex
773 string const inc_format = tmp->params().bufferFormat();
774 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
775 theFormats().extension(inc_format)));
777 // FIXME: handle non existing files
778 // The included file might be written in a different encoding
780 Encoding const * const oldEnc = runparams.encoding;
781 Language const * const oldLang = runparams.master_language;
782 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
783 // the children must be encoded in plain utf8!
784 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
785 encodings.fromLyXName("utf8-plain")
786 : &tmp->params().encoding();
787 runparams.master_language = buffer().params().language;
788 runparams.par_begin = 0;
789 runparams.par_end = tmp->paragraphs().size();
790 runparams.is_child = true;
791 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
792 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
793 if (!runparams.silent) {
794 docstring msg = bformat(_("Included file `%1$s' "
795 "was not exported correctly.\n "
796 "LaTeX export is probably incomplete."),
797 included_file.displayName());
798 ErrorList const & el = tmp->errorList("Export");
800 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
801 msg, el.begin()->error,
802 el.begin()->description);
803 throw ExceptionMessage(ErrorException, _("Error: "),
807 runparams.encoding = oldEnc;
808 runparams.master_language = oldLang;
809 runparams.is_child = false;
811 // If needed, use converters to produce a latex file from the child
812 if (tmpwritefile != writefile) {
815 theConverters().convert(tmp, tmpwritefile, writefile,
817 inc_format, tex_format, el);
819 if (!success && !runparams.silent) {
820 docstring msg = bformat(_("Included file `%1$s' "
821 "was not exported correctly.\n "
822 "LaTeX export is probably incomplete."),
823 included_file.displayName());
825 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
826 msg, el.begin()->error,
827 el.begin()->description);
828 throw ExceptionMessage(ErrorException, _("Error: "),
833 // In this case, it's not a LyX file, so we copy the file
834 // to the temp dir, so that .aux files etc. are not created
835 // in the original dir. Files included by this file will be
836 // found via either the environment variable TEXINPUTS, or
837 // input@path, see ../Buffer.cpp.
838 unsigned long const checksum_in = included_file.checksum();
839 unsigned long const checksum_out = writefile.checksum();
841 if (checksum_in != checksum_out) {
842 if (!included_file.copyTo(writefile)) {
845 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
846 "into the temporary directory."),
847 from_utf8(included_file.absFileName()))));
855 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
860 // For verbatim and listings, we just include the contents of the file as-is.
861 // In the case of listings, we wrap it in <pre>.
862 bool const listing = isListings(params());
863 if (listing || isVerbatim(params())) {
865 xs << html::StartTag("pre");
866 // FIXME: We don't know the encoding of the file, default to UTF-8.
867 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
869 xs << html::EndTag("pre");
873 // We don't (yet) know how to Input or Include non-LyX files.
874 // (If we wanted to get really arcane, we could run some tex2html
875 // converter on the included file. But that's just masochistic.)
876 FileName const included_file = includedFileName(buffer(), params());
877 if (!isLyXFileName(included_file.absFileName())) {
879 frontend::Alert::warning(_("Unsupported Inclusion"),
880 bformat(_("LyX does not know how to include non-LyX files when "
881 "generating HTML output. Offending file:\n%1$s"),
882 params()["filename"]));
886 // In the other cases, we will generate the HTML and include it.
888 // Check we're not trying to include ourselves.
889 // FIXME RECURSIVE INCLUDE
890 if (buffer().absFileName() == included_file.absFileName()) {
891 Alert::error(_("Recursive input"),
892 bformat(_("Attempted to include file %1$s in itself! "
893 "Ignoring inclusion."), params()["filename"]));
897 Buffer const * const ibuf = loadIfNeeded();
901 // are we generating only some paragraphs, or all of them?
902 bool const all_pars = !rp.dryrun ||
903 (rp.par_begin == 0 &&
904 rp.par_end == (int)buffer().text().paragraphs().size());
906 OutputParams op = rp;
910 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
912 xs << XHTMLStream::ESCAPE_NONE
913 << "<!-- Included file: "
914 << from_utf8(included_file.absFileName())
915 << XHTMLStream::ESCAPE_NONE
921 int InsetInclude::plaintext(odocstringstream & os,
922 OutputParams const & op, size_t) const
924 // just write the filename if we're making a tooltip or toc entry,
925 // or are generating this for advanced search
926 if (op.for_tooltip || op.for_toc || op.for_search) {
927 os << '[' << screenLabel() << '\n'
928 << getParam("filename") << "\n]";
929 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
932 if (isVerbatim(params()) || isListings(params())) {
933 os << '[' << screenLabel() << '\n'
934 // FIXME: We don't know the encoding of the file, default to UTF-8.
935 << includedFileName(buffer(), params()).fileContents("UTF-8")
937 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
940 Buffer const * const ibuf = loadIfNeeded();
942 docstring const str = '[' + screenLabel() + ']';
946 writePlaintextFile(*ibuf, os, op);
951 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
953 string incfile = to_utf8(params()["filename"]);
955 // Do nothing if no file name has been specified
959 string const included_file = includedFileName(buffer(), params()).absFileName();
961 // Check we're not trying to include ourselves.
962 // FIXME RECURSIVE INCLUDE
963 // This isn't sufficient, as the inclusion could be downstream.
964 // But it'll have to do for now.
965 if (buffer().absFileName() == included_file) {
966 Alert::error(_("Recursive input"),
967 bformat(_("Attempted to include file %1$s in itself! "
968 "Ignoring inclusion."), from_utf8(incfile)));
972 string exppath = incfile;
973 if (!runparams.export_folder.empty()) {
974 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
975 FileName(exppath).onlyPath().createPath();
978 // write it to a file (so far the complete file)
979 string const exportfile = changeExtension(exppath, ".sgml");
980 DocFileName writefile(changeExtension(included_file, ".sgml"));
982 Buffer * tmp = loadIfNeeded();
984 string const mangled = writefile.mangledFileName();
985 writefile = makeAbsPath(mangled,
986 buffer().masterBuffer()->temppath());
990 LYXERR(Debug::LATEX, "incfile:" << incfile);
991 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
992 LYXERR(Debug::LATEX, "writefile:" << writefile);
994 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
997 runparams.exportdata->addExternalFile("docbook", writefile,
999 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1002 if (isVerbatim(params()) || isListings(params())) {
1003 os << "<inlinegraphic fileref=\""
1004 << '&' << include_label << ';'
1005 << "\" format=\"linespecific\">";
1007 os << '&' << include_label << ';';
1013 void InsetInclude::validate(LaTeXFeatures & features) const
1015 LATTEST(&buffer() == &features.buffer());
1017 string incfile = to_utf8(params()["filename"]);
1018 string const included_file =
1019 includedFileName(buffer(), params()).absFileName();
1022 if (isLyXFileName(included_file))
1023 writefile = changeExtension(included_file, ".sgml");
1025 writefile = included_file;
1027 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1028 incfile = DocFileName(writefile).mangledFileName();
1029 writefile = makeAbsPath(incfile,
1030 buffer().masterBuffer()->temppath()).absFileName();
1033 features.includeFile(include_label, writefile);
1035 features.useInsetLayout(getLayout());
1036 if (isVerbatim(params()))
1037 features.require("verbatim");
1038 else if (isListings(params())) {
1039 if (buffer().params().use_minted) {
1040 features.require("minted");
1041 string const opts = to_utf8(params()["lstparams"]);
1042 InsetListingsParams lstpars(opts);
1043 if (!lstpars.isFloat() && contains(opts, "caption="))
1044 features.require("lyxmintcaption");
1046 features.require("listings");
1049 // Here we must do the fun stuff...
1050 // Load the file in the include if it needs
1052 Buffer * const tmp = loadIfNeeded();
1054 // the file is loaded
1055 // make sure the buffer isn't us
1056 // FIXME RECURSIVE INCLUDES
1057 // This is not sufficient, as recursive includes could be
1058 // more than a file away. But it will do for now.
1059 if (tmp && tmp != &buffer()) {
1060 // We must temporarily change features.buffer,
1061 // otherwise it would always be the master buffer,
1062 // and nested includes would not work.
1063 features.setBuffer(*tmp);
1064 // Maybe this is already a child
1065 bool const is_child =
1066 features.runparams().is_child;
1067 features.runparams().is_child = true;
1068 tmp->validate(features);
1069 features.runparams().is_child = is_child;
1070 features.setBuffer(buffer());
1076 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1078 Buffer * child = loadIfNeeded();
1081 // FIXME RECURSIVE INCLUDE
1082 // This isn't sufficient, as the inclusion could be downstream.
1083 // But it'll have to do for now.
1084 if (child == &buffer())
1086 child->collectBibKeys(checkedFiles);
1090 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1092 LBUFERR(mi.base.bv);
1094 bool use_preview = false;
1095 if (RenderPreview::previewText()) {
1096 graphics::PreviewImage const * pimage =
1097 preview_->getPreviewImage(mi.base.bv->buffer());
1098 use_preview = pimage && pimage->image();
1102 preview_->metrics(mi, dim);
1106 button_.update(screenLabel(), true, false);
1108 button_.metrics(mi, dim);
1111 Box b(0, dim.wid, -dim.asc, dim.des);
1116 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1118 LBUFERR(pi.base.bv);
1120 bool use_preview = false;
1121 if (RenderPreview::previewText()) {
1122 graphics::PreviewImage const * pimage =
1123 preview_->getPreviewImage(pi.base.bv->buffer());
1124 use_preview = pimage && pimage->image();
1128 preview_->draw(pi, x, y);
1130 button_.draw(pi, x, y);
1134 void InsetInclude::write(ostream & os) const
1136 params().Write(os, &buffer());
1140 string InsetInclude::contextMenuName() const
1142 return "context-include";
1146 Inset::DisplayType InsetInclude::display() const
1148 return type(params()) == INPUT ? Inline : AlignCenter;
1152 docstring InsetInclude::layoutName() const
1154 if (isListings(params()))
1155 return from_ascii("IncludeListings");
1156 return InsetCommand::layoutName();
1164 void InsetInclude::fileChanged() const
1166 Buffer const * const buffer = updateFrontend();
1170 preview_->removePreview(*buffer);
1171 add_preview(*preview_, *this, *buffer);
1172 preview_->startLoading(*buffer);
1178 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1180 FileName const included_file = includedFileName(buffer, params);
1182 return type(params) == INPUT && params.preview() &&
1183 included_file.isReadableFile();
1187 docstring latexString(InsetInclude const & inset)
1189 odocstringstream ods;
1191 // We don't need to set runparams.encoding since this will be done
1192 // by latex() anyway.
1193 OutputParams runparams(0);
1194 runparams.flavor = OutputParams::LATEX;
1195 runparams.for_preview = true;
1196 inset.latex(os, runparams);
1202 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1203 Buffer const & buffer)
1205 InsetCommandParams const & params = inset.params();
1206 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1207 renderer.setAbsFile(includedFileName(buffer, params));
1208 docstring const snippet = latexString(inset);
1209 renderer.addPreview(snippet, buffer);
1216 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1217 graphics::PreviewLoader & ploader) const
1219 Buffer const & buffer = ploader.buffer();
1220 if (!preview_wanted(params(), buffer))
1222 preview_->setAbsFile(includedFileName(buffer, params()));
1223 docstring const snippet = latexString(*this);
1224 preview_->addPreview(snippet, ploader);
1228 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1229 UpdateType utype, TocBackend & backend) const
1231 if (isListings(params())) {
1233 label_->addToToc(cpit, output_active, utype, backend);
1234 TocBuilder & b = backend.builder("listing");
1235 b.pushItem(cpit, screenLabel(), output_active);
1236 InsetListingsParams p(to_utf8(params()["lstparams"]));
1237 b.argumentItem(from_utf8(p.getParamValue("caption")));
1240 Buffer const * const childbuffer = getChildBuffer();
1242 TocBuilder & b = backend.builder("child");
1243 docstring str = childbuffer ? childbuffer->fileName().displayName()
1245 b.pushItem(cpit, str, output_active);
1251 // Update the child's tocBackend. The outliner uses the master's, but
1252 // the navigation menu uses the child's.
1253 childbuffer->tocBackend().update(output_active, utype);
1254 // Include Tocs from children
1255 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1257 //Copy missing outliner names (though the user has been warned against
1258 //having different document class and module selection between master
1260 for (pair<string, docstring> const & name
1261 : childbuffer->params().documentClass().outlinerNames())
1262 backend.addName(name.first, translateIfPossible(name.second));
1267 void InsetInclude::updateCommand()
1272 docstring old_label = label_->getParam("name");
1273 label_->updateLabel(old_label);
1274 // the label might have been adapted (duplicate)
1275 docstring new_label = label_->getParam("name");
1276 if (old_label == new_label)
1279 // update listings parameters...
1280 InsetCommandParams p(INCLUDE_CODE);
1282 InsetListingsParams par(to_utf8(params()["lstparams"]));
1283 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1284 p["lstparams"] = from_utf8(par.params());
1289 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1291 button_.update(screenLabel(), true, false);
1293 Buffer const * const childbuffer = getChildBuffer();
1295 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1298 if (!isListings(params()))
1302 label_->updateBuffer(it, utype);
1304 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1305 if (par.getParamValue("caption").empty()) {
1306 listings_label_ = buffer().B_("Program Listing");
1309 Buffer const & master = *buffer().masterBuffer();
1310 Counters & counters = master.params().documentClass().counters();
1311 docstring const cnt = from_ascii("listing");
1312 listings_label_ = master.B_("Program Listing");
1313 if (counters.hasCounter(cnt)) {
1314 counters.step(cnt, utype);
1315 listings_label_ += " " + convert<docstring>(counters.value(cnt));