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 string parameters = lstparams.params();
619 bool isfloat = lstparams.isFloat();
621 // Get float placement, language, caption, and
622 // label, then remove the relative options.
623 vector<string> opts =
624 getVectorFromString(parameters, ",", false);
625 for (size_t i = 0; i < opts.size(); ++i) {
626 if (prefixIs(opts[i], "float")) {
627 if (prefixIs(opts[i], "float="))
628 placement = opts[i].substr(6);
629 opts.erase(opts.begin() + i--);
630 } else if (prefixIs(opts[i], "language=")) {
631 language = opts[i].substr(9);
632 opts.erase(opts.begin() + i--);
633 } else if (prefixIs(opts[i], "caption=")) {
634 caption = opts[i].substr(8);
635 opts.erase(opts.begin() + i--);
636 } else if (prefixIs(opts[i], "label=")) {
637 label = opts[i].substr(6);
638 opts.erase(opts.begin() + i--);
641 if (!label.empty()) {
642 if (isfloat || !caption.empty())
643 label = trim(label, "{}");
645 opts.push_back("label=" + label);
647 parameters = getStringFromVector(opts, ",");
649 if (language.empty())
651 if (use_minted && isfloat) {
652 os << breakln << "\\begin{listing}";
653 if (!placement.empty())
654 os << '[' << placement << "]";
656 } else if (use_minted && !caption.empty()) {
657 os << breakln << "\\lyxmintcaption[t]{" << caption;
659 os << "\\label{" << label << "}";
662 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
663 if (!parameters.empty())
664 os << "[" << parameters << "]";
666 os << '{' << ascii_lowercase(language) << '}';
667 os << '{' << incfile << '}';
668 if (use_minted && isfloat) {
669 if (!caption.empty())
670 os << breakln << "\\caption{" << caption << "}";
672 os << breakln << "\\label{" << label << "}";
673 os << breakln << "\\end{listing}\n";
678 runparams.exportdata->addExternalFile(tex_format, writefile,
681 // \include don't want extension and demands that the
682 // file really have .tex
683 incfile = changeExtension(incfile, string());
684 incfile = latex_path(incfile);
686 os << '\\' << from_ascii(params().getCmdName()) << '{'
687 << from_utf8(incfile) << '}';
694 if (runparams.inComment || runparams.dryrun)
695 // Don't try to load or copy the file if we're
696 // in a comment or doing a dryrun
699 if (isInputOrInclude(params()) &&
700 isLyXFileName(included_file.absFileName())) {
701 // if it's a LyX file and we're inputting or including,
702 // try to load it so we can write the associated latex
704 Buffer * tmp = loadIfNeeded();
706 if (!runparams.silent) {
707 docstring text = bformat(_("Could not load included "
709 "Please, check whether it actually exists."),
710 included_file.displayName());
711 throw ExceptionMessage(ErrorException, _("Error: "),
717 if (!runparams.silent) {
718 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
720 docstring text = bformat(_("Included file `%1$s'\n"
721 "has textclass `%2$s'\n"
722 "while parent file has textclass `%3$s'."),
723 included_file.displayName(),
724 from_utf8(tmp->params().documentClass().name()),
725 from_utf8(masterBuffer->params().documentClass().name()));
726 Alert::warning(_("Different textclasses"), text, true);
729 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
730 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
731 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
732 docstring text = bformat(_("Included file `%1$s'\n"
733 "has use-non-TeX-fonts set to `%2$s'\n"
734 "while parent file has use-non-TeX-fonts set to `%3$s'."),
735 included_file.displayName(),
737 from_utf8(master_tf));
738 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
741 // Make sure modules used in child are all included in master
742 // FIXME It might be worth loading the children's modules into the master
743 // over in BufferParams rather than doing this check.
744 LayoutModuleList const masterModules = masterBuffer->params().getModules();
745 LayoutModuleList const childModules = tmp->params().getModules();
746 LayoutModuleList::const_iterator it = childModules.begin();
747 LayoutModuleList::const_iterator end = childModules.end();
748 for (; it != end; ++it) {
749 string const module = *it;
750 LayoutModuleList::const_iterator found =
751 find(masterModules.begin(), masterModules.end(), module);
752 if (found == masterModules.end()) {
753 docstring text = bformat(_("Included file `%1$s'\n"
754 "uses module `%2$s'\n"
755 "which is not used in parent file."),
756 included_file.displayName(), from_utf8(module));
757 Alert::warning(_("Module not found"), text);
762 tmp->markDepClean(masterBuffer->temppath());
764 // Don't assume the child's format is latex
765 string const inc_format = tmp->params().bufferFormat();
766 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
767 theFormats().extension(inc_format)));
769 // FIXME: handle non existing files
770 // The included file might be written in a different encoding
772 Encoding const * const oldEnc = runparams.encoding;
773 Language const * const oldLang = runparams.master_language;
774 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
775 // the children must be encoded in plain utf8!
776 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
777 encodings.fromLyXName("utf8-plain")
778 : &tmp->params().encoding();
779 runparams.master_language = buffer().params().language;
780 runparams.par_begin = 0;
781 runparams.par_end = tmp->paragraphs().size();
782 runparams.is_child = true;
783 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
784 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
785 if (!runparams.silent) {
786 docstring msg = bformat(_("Included file `%1$s' "
787 "was not exported correctly.\n "
788 "LaTeX export is probably incomplete."),
789 included_file.displayName());
790 ErrorList const & el = tmp->errorList("Export");
792 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
793 msg, el.begin()->error,
794 el.begin()->description);
795 throw ExceptionMessage(ErrorException, _("Error: "),
799 runparams.encoding = oldEnc;
800 runparams.master_language = oldLang;
801 runparams.is_child = false;
803 // If needed, use converters to produce a latex file from the child
804 if (tmpwritefile != writefile) {
807 theConverters().convert(tmp, tmpwritefile, writefile,
809 inc_format, tex_format, el);
811 if (!success && !runparams.silent) {
812 docstring msg = bformat(_("Included file `%1$s' "
813 "was not exported correctly.\n "
814 "LaTeX export is probably incomplete."),
815 included_file.displayName());
817 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
818 msg, el.begin()->error,
819 el.begin()->description);
820 throw ExceptionMessage(ErrorException, _("Error: "),
825 // In this case, it's not a LyX file, so we copy the file
826 // to the temp dir, so that .aux files etc. are not created
827 // in the original dir. Files included by this file will be
828 // found via either the environment variable TEXINPUTS, or
829 // input@path, see ../Buffer.cpp.
830 unsigned long const checksum_in = included_file.checksum();
831 unsigned long const checksum_out = writefile.checksum();
833 if (checksum_in != checksum_out) {
834 if (!included_file.copyTo(writefile)) {
837 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
838 "into the temporary directory."),
839 from_utf8(included_file.absFileName()))));
847 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
852 // For verbatim and listings, we just include the contents of the file as-is.
853 // In the case of listings, we wrap it in <pre>.
854 bool const listing = isListings(params());
855 if (listing || isVerbatim(params())) {
857 xs << html::StartTag("pre");
858 // FIXME: We don't know the encoding of the file, default to UTF-8.
859 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
861 xs << html::EndTag("pre");
865 // We don't (yet) know how to Input or Include non-LyX files.
866 // (If we wanted to get really arcane, we could run some tex2html
867 // converter on the included file. But that's just masochistic.)
868 FileName const included_file = includedFileName(buffer(), params());
869 if (!isLyXFileName(included_file.absFileName())) {
871 frontend::Alert::warning(_("Unsupported Inclusion"),
872 bformat(_("LyX does not know how to include non-LyX files when "
873 "generating HTML output. Offending file:\n%1$s"),
874 params()["filename"]));
878 // In the other cases, we will generate the HTML and include it.
880 // Check we're not trying to include ourselves.
881 // FIXME RECURSIVE INCLUDE
882 if (buffer().absFileName() == included_file.absFileName()) {
883 Alert::error(_("Recursive input"),
884 bformat(_("Attempted to include file %1$s in itself! "
885 "Ignoring inclusion."), params()["filename"]));
889 Buffer const * const ibuf = loadIfNeeded();
893 // are we generating only some paragraphs, or all of them?
894 bool const all_pars = !rp.dryrun ||
895 (rp.par_begin == 0 &&
896 rp.par_end == (int)buffer().text().paragraphs().size());
898 OutputParams op = rp;
902 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
904 xs << XHTMLStream::ESCAPE_NONE
905 << "<!-- Included file: "
906 << from_utf8(included_file.absFileName())
907 << XHTMLStream::ESCAPE_NONE
913 int InsetInclude::plaintext(odocstringstream & os,
914 OutputParams const & op, size_t) const
916 // just write the filename if we're making a tooltip or toc entry,
917 // or are generating this for advanced search
918 if (op.for_tooltip || op.for_toc || op.for_search) {
919 os << '[' << screenLabel() << '\n'
920 << getParam("filename") << "\n]";
921 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
924 if (isVerbatim(params()) || isListings(params())) {
925 os << '[' << screenLabel() << '\n'
926 // FIXME: We don't know the encoding of the file, default to UTF-8.
927 << includedFileName(buffer(), params()).fileContents("UTF-8")
929 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
932 Buffer const * const ibuf = loadIfNeeded();
934 docstring const str = '[' + screenLabel() + ']';
938 writePlaintextFile(*ibuf, os, op);
943 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
945 string incfile = to_utf8(params()["filename"]);
947 // Do nothing if no file name has been specified
951 string const included_file = includedFileName(buffer(), params()).absFileName();
953 // Check we're not trying to include ourselves.
954 // FIXME RECURSIVE INCLUDE
955 // This isn't sufficient, as the inclusion could be downstream.
956 // But it'll have to do for now.
957 if (buffer().absFileName() == included_file) {
958 Alert::error(_("Recursive input"),
959 bformat(_("Attempted to include file %1$s in itself! "
960 "Ignoring inclusion."), from_utf8(incfile)));
964 string exppath = incfile;
965 if (!runparams.export_folder.empty()) {
966 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
967 FileName(exppath).onlyPath().createPath();
970 // write it to a file (so far the complete file)
971 string const exportfile = changeExtension(exppath, ".sgml");
972 DocFileName writefile(changeExtension(included_file, ".sgml"));
974 Buffer * tmp = loadIfNeeded();
976 string const mangled = writefile.mangledFileName();
977 writefile = makeAbsPath(mangled,
978 buffer().masterBuffer()->temppath());
982 LYXERR(Debug::LATEX, "incfile:" << incfile);
983 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
984 LYXERR(Debug::LATEX, "writefile:" << writefile);
986 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
989 runparams.exportdata->addExternalFile("docbook", writefile,
991 runparams.exportdata->addExternalFile("docbook-xml", writefile,
994 if (isVerbatim(params()) || isListings(params())) {
995 os << "<inlinegraphic fileref=\""
996 << '&' << include_label << ';'
997 << "\" format=\"linespecific\">";
999 os << '&' << include_label << ';';
1005 void InsetInclude::validate(LaTeXFeatures & features) const
1007 LATTEST(&buffer() == &features.buffer());
1009 string incfile = to_utf8(params()["filename"]);
1010 string const included_file =
1011 includedFileName(buffer(), params()).absFileName();
1014 if (isLyXFileName(included_file))
1015 writefile = changeExtension(included_file, ".sgml");
1017 writefile = included_file;
1019 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1020 incfile = DocFileName(writefile).mangledFileName();
1021 writefile = makeAbsPath(incfile,
1022 buffer().masterBuffer()->temppath()).absFileName();
1025 features.includeFile(include_label, writefile);
1027 features.useInsetLayout(getLayout());
1028 if (isVerbatim(params()))
1029 features.require("verbatim");
1030 else if (isListings(params())) {
1031 if (buffer().params().use_minted) {
1032 features.require("minted");
1033 string const opts = to_utf8(params()["lstparams"]);
1034 InsetListingsParams lstpars(opts);
1035 if (!lstpars.isFloat() && contains(opts, "caption="))
1036 features.require("lyxmintcaption");
1038 features.require("listings");
1041 // Here we must do the fun stuff...
1042 // Load the file in the include if it needs
1044 Buffer * const tmp = loadIfNeeded();
1046 // the file is loaded
1047 // make sure the buffer isn't us
1048 // FIXME RECURSIVE INCLUDES
1049 // This is not sufficient, as recursive includes could be
1050 // more than a file away. But it will do for now.
1051 if (tmp && tmp != &buffer()) {
1052 // We must temporarily change features.buffer,
1053 // otherwise it would always be the master buffer,
1054 // and nested includes would not work.
1055 features.setBuffer(*tmp);
1056 // Maybe this is already a child
1057 bool const is_child =
1058 features.runparams().is_child;
1059 features.runparams().is_child = true;
1060 tmp->validate(features);
1061 features.runparams().is_child = is_child;
1062 features.setBuffer(buffer());
1068 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1070 Buffer * child = loadIfNeeded();
1073 // FIXME RECURSIVE INCLUDE
1074 // This isn't sufficient, as the inclusion could be downstream.
1075 // But it'll have to do for now.
1076 if (child == &buffer())
1078 child->collectBibKeys(checkedFiles);
1082 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1084 LBUFERR(mi.base.bv);
1086 bool use_preview = false;
1087 if (RenderPreview::previewText()) {
1088 graphics::PreviewImage const * pimage =
1089 preview_->getPreviewImage(mi.base.bv->buffer());
1090 use_preview = pimage && pimage->image();
1094 preview_->metrics(mi, dim);
1098 button_.update(screenLabel(), true, false);
1100 button_.metrics(mi, dim);
1103 Box b(0, dim.wid, -dim.asc, dim.des);
1108 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1110 LBUFERR(pi.base.bv);
1112 bool use_preview = false;
1113 if (RenderPreview::previewText()) {
1114 graphics::PreviewImage const * pimage =
1115 preview_->getPreviewImage(pi.base.bv->buffer());
1116 use_preview = pimage && pimage->image();
1120 preview_->draw(pi, x, y);
1122 button_.draw(pi, x, y);
1126 void InsetInclude::write(ostream & os) const
1128 params().Write(os, &buffer());
1132 string InsetInclude::contextMenuName() const
1134 return "context-include";
1138 Inset::DisplayType InsetInclude::display() const
1140 return type(params()) == INPUT ? Inline : AlignCenter;
1144 docstring InsetInclude::layoutName() const
1146 if (isListings(params()))
1147 return from_ascii("IncludeListings");
1148 return InsetCommand::layoutName();
1156 void InsetInclude::fileChanged() const
1158 Buffer const * const buffer = updateFrontend();
1162 preview_->removePreview(*buffer);
1163 add_preview(*preview_, *this, *buffer);
1164 preview_->startLoading(*buffer);
1170 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1172 FileName const included_file = includedFileName(buffer, params);
1174 return type(params) == INPUT && params.preview() &&
1175 included_file.isReadableFile();
1179 docstring latexString(InsetInclude const & inset)
1181 odocstringstream ods;
1183 // We don't need to set runparams.encoding since this will be done
1184 // by latex() anyway.
1185 OutputParams runparams(0);
1186 runparams.flavor = OutputParams::LATEX;
1187 runparams.for_preview = true;
1188 inset.latex(os, runparams);
1194 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1195 Buffer const & buffer)
1197 InsetCommandParams const & params = inset.params();
1198 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1199 renderer.setAbsFile(includedFileName(buffer, params));
1200 docstring const snippet = latexString(inset);
1201 renderer.addPreview(snippet, buffer);
1208 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1209 graphics::PreviewLoader & ploader) const
1211 Buffer const & buffer = ploader.buffer();
1212 if (!preview_wanted(params(), buffer))
1214 preview_->setAbsFile(includedFileName(buffer, params()));
1215 docstring const snippet = latexString(*this);
1216 preview_->addPreview(snippet, ploader);
1220 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1221 UpdateType utype, TocBackend & backend) const
1223 if (isListings(params())) {
1225 label_->addToToc(cpit, output_active, utype, backend);
1226 TocBuilder & b = backend.builder("listing");
1227 b.pushItem(cpit, screenLabel(), output_active);
1228 InsetListingsParams p(to_utf8(params()["lstparams"]));
1229 b.argumentItem(from_utf8(p.getParamValue("caption")));
1232 Buffer const * const childbuffer = getChildBuffer();
1234 TocBuilder & b = backend.builder("child");
1235 docstring str = childbuffer ? childbuffer->fileName().displayName()
1237 b.pushItem(cpit, str, output_active);
1243 // Update the child's tocBackend. The outliner uses the master's, but
1244 // the navigation menu uses the child's.
1245 childbuffer->tocBackend().update(output_active, utype);
1246 // Include Tocs from children
1247 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1249 //Copy missing outliner names (though the user has been warned against
1250 //having different document class and module selection between master
1252 for (pair<string, docstring> const & name
1253 : childbuffer->params().documentClass().outlinerNames())
1254 backend.addName(name.first, translateIfPossible(name.second));
1259 void InsetInclude::updateCommand()
1264 docstring old_label = label_->getParam("name");
1265 label_->updateLabel(old_label);
1266 // the label might have been adapted (duplicate)
1267 docstring new_label = label_->getParam("name");
1268 if (old_label == new_label)
1271 // update listings parameters...
1272 InsetCommandParams p(INCLUDE_CODE);
1274 InsetListingsParams par(to_utf8(params()["lstparams"]));
1275 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1276 p["lstparams"] = from_utf8(par.params());
1281 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1283 button_.update(screenLabel(), true, false);
1285 Buffer const * const childbuffer = getChildBuffer();
1287 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1290 if (!isListings(params()))
1294 label_->updateBuffer(it, utype);
1296 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1297 if (par.getParamValue("caption").empty()) {
1298 listings_label_ = buffer().B_("Program Listing");
1301 Buffer const & master = *buffer().masterBuffer();
1302 Counters & counters = master.params().documentClass().counters();
1303 docstring const cnt = from_ascii("listing");
1304 listings_label_ = master.B_("Program Listing");
1305 if (counters.hasCounter(cnt)) {
1306 counters.step(cnt, utype);
1307 listings_label_ += " " + convert<docstring>(counters.value(cnt));