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"
36 #include "MetricsInfo.h"
37 #include "output_plaintext.h"
38 #include "output_xhtml.h"
39 #include "OutputParams.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"
65 #include "support/bind.h"
68 using namespace lyx::support;
72 namespace Alert = frontend::Alert;
77 docstring const uniqueID()
79 static unsigned int seed = 1000;
80 return "file" + convert<docstring>(++seed);
84 /// the type of inclusion
86 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
90 Types type(string const & s)
94 if (s == "verbatiminput")
96 if (s == "verbatiminput*")
98 if (s == "lstinputlisting")
106 Types type(InsetCommandParams const & params)
108 return type(params.getCmdName());
112 bool isListings(InsetCommandParams const & params)
114 return type(params) == LISTINGS;
118 bool isVerbatim(InsetCommandParams const & params)
120 Types const t = type(params);
121 return t == VERB || t == VERBAST;
125 bool isInputOrInclude(InsetCommandParams const & params)
127 Types const t = type(params);
128 return t == INPUT || t == INCLUDE;
132 FileName const masterFileName(Buffer const & buffer)
134 return buffer.masterBuffer()->fileName();
138 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
141 string const parentFileName(Buffer const & buffer)
143 return buffer.absFileName();
147 FileName const includedFileName(Buffer const & buffer,
148 InsetCommandParams const & params)
150 return makeAbsPath(to_utf8(params["filename"]),
151 onlyPath(parentFileName(buffer)));
155 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
157 if (label_str.empty())
159 InsetCommandParams icp(LABEL_CODE);
160 icp["name"] = label_str;
161 return new InsetLabel(buf, icp);
167 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
168 : InsetCommand(buf, p), include_label(uniqueID()),
169 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
170 set_label_(false), label_(0), child_buffer_(0)
172 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
174 if (isListings(params())) {
175 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
176 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
177 } else if (isInputOrInclude(params()) && buf)
182 InsetInclude::InsetInclude(InsetInclude const & other)
183 : InsetCommand(other), include_label(other.include_label),
184 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
185 set_label_(false), label_(0), child_buffer_(0)
187 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
190 label_ = new InsetLabel(*other.label_);
194 InsetInclude::~InsetInclude()
196 if (isBufferLoaded())
197 buffer().invalidateBibfileCache();
202 void InsetInclude::setBuffer(Buffer & buffer)
204 InsetCommand::setBuffer(buffer);
206 label_->setBuffer(buffer);
210 void InsetInclude::setChildBuffer(Buffer * buffer)
212 child_buffer_ = buffer;
216 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
219 // This is only correct for the case of listings, but it'll do for now.
220 // In the other cases, this second parameter should just be empty.
221 static ParamInfo param_info_;
222 if (param_info_.empty()) {
223 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
224 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
230 bool InsetInclude::isCompatibleCommand(string const & s)
232 return type(s) != NONE;
236 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
238 switch (cmd.action()) {
240 case LFUN_INSET_EDIT: {
241 editIncluded(to_utf8(params()["filename"]));
245 case LFUN_INSET_MODIFY: {
246 // It should be OK just to invalidate the cache in setParams()
248 // child_buffer_ = 0;
249 InsetCommandParams p(INCLUDE_CODE);
250 if (cmd.getArg(0) == "changetype") {
252 InsetCommand::doDispatch(cur, cmd);
255 InsetCommand::string2params(to_utf8(cmd.argument()), p);
256 if (!p.getCmdName().empty()) {
258 InsetListingsParams new_params(to_utf8(p["lstparams"]));
259 docstring const new_label =
260 from_utf8(new_params.getParamValue("label"));
262 if (new_label.empty()) {
268 old_label = label_->getParam("name");
270 label_ = createLabel(buffer_, new_label);
271 label_->setBuffer(buffer());
274 if (new_label != old_label) {
275 label_->updateLabelAndRefs(new_label, &cur);
276 // the label might have been adapted (duplicate)
277 if (new_label != label_->getParam("name")) {
278 new_params.addParam("label", "{" +
279 to_utf8(label_->getParam("name")) + "}", true);
280 p["lstparams"] = from_utf8(new_params.params());
287 cur.forceBufferUpdate();
289 cur.noScreenUpdate();
293 //pass everything else up the chain
295 InsetCommand::doDispatch(cur, cmd);
301 void InsetInclude::editIncluded(string const & file)
303 string const ext = support::getExtension(file);
305 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
308 // tex file or other text file in verbatim mode
309 formats.edit(buffer(),
310 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
315 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
316 FuncStatus & flag) const
318 switch (cmd.action()) {
320 case LFUN_INSET_EDIT:
321 flag.setEnabled(true);
324 case LFUN_INSET_MODIFY:
325 if (cmd.getArg(0) == "changetype")
326 return InsetCommand::getStatus(cur, cmd, flag);
328 flag.setEnabled(true);
332 return InsetCommand::getStatus(cur, cmd, flag);
337 void InsetInclude::setParams(InsetCommandParams const & p)
339 // invalidate the cache
342 InsetCommand::setParams(p);
345 if (preview_->monitoring())
346 preview_->stopMonitoring();
348 if (type(params()) == INPUT)
349 add_preview(*preview_, *this, buffer());
351 buffer().invalidateBibfileCache();
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, /**/);
396 if (params()["filename"].empty())
399 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
405 Buffer * InsetInclude::getChildBuffer() const
407 Buffer * childBuffer = loadIfNeeded();
409 // FIXME: recursive includes
410 return (childBuffer == &buffer()) ? 0 : childBuffer;
414 Buffer * InsetInclude::loadIfNeeded() const
416 // This is for background export and preview. We don't even want to
417 // try to load the cloned child document again.
418 if (buffer().isClone())
419 return child_buffer_;
421 // Don't try to load it again if we failed before.
422 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
425 FileName const included_file = includedFileName(buffer(), params());
426 // Use cached Buffer if possible.
427 if (child_buffer_ != 0) {
428 if (theBufferList().isLoaded(child_buffer_)
429 // additional sanity check: make sure the Buffer really is
430 // associated with the file we want.
431 && child_buffer_ == theBufferList().getBuffer(included_file))
432 return child_buffer_;
433 // Buffer vanished, so invalidate cache and try to reload.
437 if (!isLyXFileName(included_file.absFileName()))
440 Buffer * child = theBufferList().getBuffer(included_file);
442 // the readonly flag can/will be wrong, not anymore I think.
443 if (!included_file.exists())
446 child = theBufferList().newBuffer(included_file.absFileName());
448 // Buffer creation is not possible.
451 // Set parent before loading, such that macros can be tracked
452 child->setParent(&buffer());
454 if (child->loadLyXFile() != Buffer::ReadSuccess) {
455 failedtoload_ = true;
457 //close the buffer we just opened
458 theBufferList().release(child);
462 if (!child->errorList("Parse").empty()) {
463 // FIXME: Do something.
466 // The file was already loaded, so, simply
467 // inform parent buffer about local macros.
468 Buffer const * parent = &buffer();
469 child->setParent(parent);
471 child->listMacroNames(macros);
472 MacroNameSet::const_iterator cit = macros.begin();
473 MacroNameSet::const_iterator end = macros.end();
474 for (; cit != end; ++cit)
475 parent->usermacros.insert(*cit);
478 // Cache the child buffer.
479 child_buffer_ = child;
484 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
486 string incfile = to_utf8(params()["filename"]);
488 // Do nothing if no file name has been specified
492 FileName const included_file = includedFileName(buffer(), params());
494 // Check we're not trying to include ourselves.
495 // FIXME RECURSIVE INCLUDE
496 // This isn't sufficient, as the inclusion could be downstream.
497 // But it'll have to do for now.
498 if (isInputOrInclude(params()) &&
499 buffer().absFileName() == included_file.absFileName())
501 Alert::error(_("Recursive input"),
502 bformat(_("Attempted to include file %1$s in itself! "
503 "Ignoring inclusion."), from_utf8(incfile)));
507 Buffer const * const masterBuffer = buffer().masterBuffer();
509 // if incfile is relative, make it relative to the master
511 if (!FileName::isAbsolute(incfile)) {
513 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
514 from_utf8(masterBuffer->filePath())));
517 string exppath = incfile;
518 if (!runparams.export_folder.empty()) {
519 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
520 FileName(exppath).onlyPath().createPath();
523 // write it to a file (so far the complete file)
527 if (type(params()) == LISTINGS) {
528 exportfile = exppath;
529 mangled = DocFileName(included_file).mangledFileName();
531 exportfile = changeExtension(exppath, ".tex");
532 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
536 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
540 else if (!isValidLaTeXFileName(incfile)) {
541 frontend::Alert::warning(_("Invalid filename"),
542 _("The following filename will cause troubles "
543 "when running the exported file through LaTeX: ") +
546 else if (!isValidDVIFileName(incfile)) {
547 frontend::Alert::warning(_("Problematic filename for DVI"),
548 _("The following filename can cause troubles "
549 "when running the exported file through LaTeX "
550 "and opening the resulting DVI: ") +
551 from_utf8(incfile), true);
553 LYXERR(Debug::LATEX, "incfile:" << incfile);
554 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
555 LYXERR(Debug::LATEX, "writefile:" << writefile);
557 string const tex_format = flavor2format(runparams.flavor);
558 if (runparams.inComment || runparams.dryrun) {
559 //Don't try to load or copy the file if we're
560 //in a comment or doing a dryrun
561 } else if (isInputOrInclude(params()) &&
562 isLyXFileName(included_file.absFileName())) {
563 // if it's a LyX file and we're inputting or including,
564 // try to load it so we can write the associated latex
566 Buffer * tmp = loadIfNeeded();
568 docstring text = bformat(_("Could not load included "
570 "Please, check whether it actually exists."),
571 included_file.displayName());
572 Alert::warning(_("Missing included file"), text);
576 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
578 docstring text = bformat(_("Included file `%1$s'\n"
579 "has textclass `%2$s'\n"
580 "while parent file has textclass `%3$s'."),
581 included_file.displayName(),
582 from_utf8(tmp->params().documentClass().name()),
583 from_utf8(masterBuffer->params().documentClass().name()));
584 Alert::warning(_("Different textclasses"), text, true);
587 // Make sure modules used in child are all included in master
588 // FIXME It might be worth loading the children's modules into the master
589 // over in BufferParams rather than doing this check.
590 LayoutModuleList const masterModules = masterBuffer->params().getModules();
591 LayoutModuleList const childModules = tmp->params().getModules();
592 LayoutModuleList::const_iterator it = childModules.begin();
593 LayoutModuleList::const_iterator end = childModules.end();
594 for (; it != end; ++it) {
595 string const module = *it;
596 LayoutModuleList::const_iterator found =
597 find(masterModules.begin(), masterModules.end(), module);
598 if (found == masterModules.end()) {
599 docstring text = bformat(_("Included file `%1$s'\n"
600 "uses module `%2$s'\n"
601 "which is not used in parent file."),
602 included_file.displayName(), from_utf8(module));
603 Alert::warning(_("Module not found"), text);
607 tmp->markDepClean(masterBuffer->temppath());
609 // Don't assume the child's format is latex
610 string const inc_format = tmp->params().bufferFormat();
611 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
612 formats.extension(inc_format)));
614 // FIXME: handle non existing files
615 // The included file might be written in a different encoding
617 Encoding const * const oldEnc = runparams.encoding;
618 Language const * const oldLang = runparams.master_language;
619 // If the master has full unicode flavor (XeTeX, LuaTeX),
620 // the children must be encoded in plain utf8!
621 runparams.encoding = runparams.isFullUnicode() ?
622 encodings.fromLyXName("utf8-plain")
623 : &tmp->params().encoding();
624 runparams.master_language = buffer().params().language;
625 runparams.par_begin = 0;
626 runparams.par_end = tmp->paragraphs().size();
627 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
628 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
629 docstring msg = bformat(_("Included file `%1$s' "
630 "was not exported correctly.\nWarning: "
631 "LaTeX export is probably incomplete."),
632 included_file.displayName());
633 ErrorList const & el = tmp->errorList("Export");
635 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
636 msg, el.begin()->error,
637 el.begin()->description);
638 Alert::warning(_("Export failure"), msg);
640 runparams.encoding = oldEnc;
641 runparams.master_language = oldLang;
643 // If needed, use converters to produce a latex file from the child
644 if (tmpwritefile != writefile) {
647 theConverters().convert(tmp, tmpwritefile, writefile,
649 inc_format, tex_format, el);
652 docstring msg = bformat(_("Included file `%1$s' "
653 "was not exported correctly.\nWarning: "
654 "LaTeX export is probably incomplete."),
655 included_file.displayName());
657 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
658 msg, el.begin()->error,
659 el.begin()->description);
660 Alert::warning(_("Export failure"), msg);
664 // In this case, it's not a LyX file, so we copy the file
665 // to the temp dir, so that .aux files etc. are not created
666 // in the original dir. Files included by this file will be
667 // found via either the environment variable TEXINPUTS, or
668 // input@path, see ../Buffer.cpp.
669 unsigned long const checksum_in = included_file.checksum();
670 unsigned long const checksum_out = writefile.checksum();
672 if (checksum_in != checksum_out) {
673 if (!included_file.copyTo(writefile)) {
676 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
677 "into the temporary directory."),
678 from_utf8(included_file.absFileName()))));
684 switch (type(params())) {
687 incfile = latex_path(incfile);
689 os << '\\' << from_ascii(params().getCmdName()) << '{'
690 << from_utf8(incfile) << '}';
694 runparams.exportdata->addExternalFile(tex_format, writefile,
697 // \input wants file with extension (default is .tex)
698 if (!isLyXFileName(included_file.absFileName())) {
699 incfile = latex_path(incfile);
701 os << '\\' << from_ascii(params().getCmdName())
702 << '{' << from_utf8(incfile) << '}';
704 incfile = changeExtension(incfile, ".tex");
705 incfile = latex_path(incfile);
707 os << '\\' << from_ascii(params().getCmdName())
708 << '{' << from_utf8(incfile) << '}';
713 runparams.exportdata->addExternalFile(tex_format, writefile,
715 os << '\\' << from_ascii(params().getCmdName());
716 string const opt = to_utf8(params()["lstparams"]);
717 // opt is set in QInclude dialog and should have passed validation.
718 InsetListingsParams params(opt);
719 if (!params.params().empty())
720 os << "[" << from_utf8(params.params()) << "]";
721 os << '{' << from_utf8(incfile) << '}';
725 runparams.exportdata->addExternalFile(tex_format, writefile,
728 // \include don't want extension and demands that the
729 // file really have .tex
730 incfile = changeExtension(incfile, string());
731 incfile = latex_path(incfile);
733 os << '\\' << from_ascii(params().getCmdName()) << '{'
734 << from_utf8(incfile) << '}';
743 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
748 // For verbatim and listings, we just include the contents of the file as-is.
749 // In the case of listings, we wrap it in <pre>.
750 bool const listing = isListings(params());
751 if (listing || isVerbatim(params())) {
753 xs << html::StartTag("pre");
754 // FIXME: We don't know the encoding of the file, default to UTF-8.
755 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
757 xs << html::EndTag("pre");
761 // We don't (yet) know how to Input or Include non-LyX files.
762 // (If we wanted to get really arcane, we could run some tex2html
763 // converter on the included file. But that's just masochistic.)
764 FileName const included_file = includedFileName(buffer(), params());
765 if (!isLyXFileName(included_file.absFileName())) {
766 frontend::Alert::warning(_("Unsupported Inclusion"),
767 bformat(_("LyX does not know how to include non-LyX files when "
768 "generating HTML output. Offending file:\n%1$s"),
769 params()["filename"]));
773 // In the other cases, we will generate the HTML and include it.
775 // Check we're not trying to include ourselves.
776 // FIXME RECURSIVE INCLUDE
777 if (buffer().absFileName() == included_file.absFileName()) {
778 Alert::error(_("Recursive input"),
779 bformat(_("Attempted to include file %1$s in itself! "
780 "Ignoring inclusion."), params()["filename"]));
784 Buffer const * const ibuf = loadIfNeeded();
788 // are we generating only some paragraphs, or all of them?
789 bool const all_pars = !rp.dryrun ||
790 (rp.par_begin == 0 &&
791 rp.par_end == (int)buffer().text().paragraphs().size());
793 OutputParams op = rp;
797 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
799 xs << XHTMLStream::ESCAPE_NONE
800 << "<!-- Included file: "
801 << from_utf8(included_file.absFileName())
802 << XHTMLStream::ESCAPE_NONE
808 int InsetInclude::plaintext(odocstream & os, OutputParams const & op) const
810 if (isVerbatim(params()) || isListings(params())) {
811 os << '[' << screenLabel() << '\n';
812 // FIXME: We don't know the encoding of the file, default to UTF-8.
813 os << includedFileName(buffer(), params()).fileContents("UTF-8");
815 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
818 Buffer const * const ibuf = loadIfNeeded();
820 docstring const str = '[' + screenLabel() + ']';
824 writePlaintextFile(*ibuf, os, op);
829 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
831 string incfile = to_utf8(params()["filename"]);
833 // Do nothing if no file name has been specified
837 string const included_file = includedFileName(buffer(), params()).absFileName();
839 // Check we're not trying to include ourselves.
840 // FIXME RECURSIVE INCLUDE
841 // This isn't sufficient, as the inclusion could be downstream.
842 // But it'll have to do for now.
843 if (buffer().absFileName() == included_file) {
844 Alert::error(_("Recursive input"),
845 bformat(_("Attempted to include file %1$s in itself! "
846 "Ignoring inclusion."), from_utf8(incfile)));
850 string exppath = incfile;
851 if (!runparams.export_folder.empty()) {
852 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
853 FileName(exppath).onlyPath().createPath();
856 // write it to a file (so far the complete file)
857 string const exportfile = changeExtension(exppath, ".sgml");
858 DocFileName writefile(changeExtension(included_file, ".sgml"));
860 Buffer * tmp = loadIfNeeded();
862 string const mangled = writefile.mangledFileName();
863 writefile = makeAbsPath(mangled,
864 buffer().masterBuffer()->temppath());
868 LYXERR(Debug::LATEX, "incfile:" << incfile);
869 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
870 LYXERR(Debug::LATEX, "writefile:" << writefile);
872 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
875 runparams.exportdata->addExternalFile("docbook", writefile,
877 runparams.exportdata->addExternalFile("docbook-xml", writefile,
880 if (isVerbatim(params()) || isListings(params())) {
881 os << "<inlinegraphic fileref=\""
882 << '&' << include_label << ';'
883 << "\" format=\"linespecific\">";
885 os << '&' << include_label << ';';
891 void InsetInclude::validate(LaTeXFeatures & features) const
893 string incfile = to_utf8(params()["filename"]);
896 LASSERT(&buffer() == &features.buffer(), /**/);
898 string const included_file =
899 includedFileName(buffer(), params()).absFileName();
901 if (isLyXFileName(included_file))
902 writefile = changeExtension(included_file, ".sgml");
904 writefile = included_file;
906 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
907 incfile = DocFileName(writefile).mangledFileName();
908 writefile = makeAbsPath(incfile,
909 buffer().masterBuffer()->temppath()).absFileName();
912 features.includeFile(include_label, writefile);
914 features.useInsetLayout(getLayout());
915 if (isVerbatim(params()))
916 features.require("verbatim");
917 else if (isListings(params()))
918 features.require("listings");
920 // Here we must do the fun stuff...
921 // Load the file in the include if it needs
923 Buffer * const tmp = loadIfNeeded();
925 // the file is loaded
926 // make sure the buffer isn't us
927 // FIXME RECURSIVE INCLUDES
928 // This is not sufficient, as recursive includes could be
929 // more than a file away. But it will do for now.
930 if (tmp && tmp != &buffer()) {
931 // We must temporarily change features.buffer,
932 // otherwise it would always be the master buffer,
933 // and nested includes would not work.
934 features.setBuffer(*tmp);
935 tmp->validate(features);
936 features.setBuffer(buffer());
942 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
944 Buffer * child = loadIfNeeded();
947 child->collectBibKeys();
951 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
953 LASSERT(mi.base.bv, /**/);
955 bool use_preview = false;
956 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
957 graphics::PreviewImage const * pimage =
958 preview_->getPreviewImage(mi.base.bv->buffer());
959 use_preview = pimage && pimage->image();
963 preview_->metrics(mi, dim);
967 button_.update(screenLabel(), true);
969 button_.metrics(mi, dim);
972 Box b(0, dim.wid, -dim.asc, dim.des);
977 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
979 LASSERT(pi.base.bv, /**/);
981 bool use_preview = false;
982 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
983 graphics::PreviewImage const * pimage =
984 preview_->getPreviewImage(pi.base.bv->buffer());
985 use_preview = pimage && pimage->image();
989 preview_->draw(pi, x, y);
991 button_.draw(pi, x, y);
995 string InsetInclude::contextMenuName() const
997 return "context-include";
1001 Inset::DisplayType InsetInclude::display() const
1003 return type(params()) == INPUT ? Inline : AlignCenter;
1007 docstring InsetInclude::layoutName() const
1009 if (isListings(params()))
1010 return from_ascii("IncludeListings");
1011 return InsetCommand::layoutName();
1019 void InsetInclude::fileChanged() const
1021 Buffer const * const buffer = updateFrontend();
1025 preview_->removePreview(*buffer);
1026 add_preview(*preview_.get(), *this, *buffer);
1027 preview_->startLoading(*buffer);
1033 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1035 FileName const included_file = includedFileName(buffer, params);
1037 return type(params) == INPUT && params.preview() &&
1038 included_file.isReadableFile();
1042 docstring latexString(InsetInclude const & inset)
1045 odocstringstream ods;
1046 otexstream os(ods, texrow);
1047 // We don't need to set runparams.encoding since this will be done
1048 // by latex() anyway.
1049 OutputParams runparams(0);
1050 runparams.flavor = OutputParams::LATEX;
1051 inset.latex(os, runparams);
1057 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1058 Buffer const & buffer)
1060 InsetCommandParams const & params = inset.params();
1061 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
1062 preview_wanted(params, buffer)) {
1063 renderer.setAbsFile(includedFileName(buffer, params));
1064 docstring const snippet = latexString(inset);
1065 renderer.addPreview(snippet, buffer);
1072 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1073 graphics::PreviewLoader & ploader) const
1075 Buffer const & buffer = ploader.buffer();
1076 if (!preview_wanted(params(), buffer))
1078 preview_->setAbsFile(includedFileName(buffer, params()));
1079 docstring const snippet = latexString(*this);
1080 preview_->addPreview(snippet, ploader);
1084 void InsetInclude::addToToc(DocIterator const & cpit) const
1086 TocBackend & backend = buffer().tocBackend();
1088 if (isListings(params())) {
1090 label_->addToToc(cpit);
1092 InsetListingsParams p(to_utf8(params()["lstparams"]));
1093 string caption = p.getParamValue("caption");
1094 if (caption.empty())
1096 Toc & toc = backend.toc("listing");
1097 docstring str = convert<docstring>(toc.size() + 1)
1098 + ". " + from_utf8(caption);
1099 DocIterator pit = cpit;
1100 toc.push_back(TocItem(pit, 0, str));
1103 Buffer const * const childbuffer = getChildBuffer();
1107 Toc & toc = backend.toc("child");
1108 docstring str = childbuffer->fileName().displayName();
1109 toc.push_back(TocItem(cpit, 0, str));
1111 TocList & toclist = backend.tocs();
1112 childbuffer->tocBackend().update();
1113 TocList const & childtoclist = childbuffer->tocBackend().tocs();
1114 TocList::const_iterator it = childtoclist.begin();
1115 TocList::const_iterator const end = childtoclist.end();
1116 for(; it != end; ++it)
1117 toclist[it->first].insert(toclist[it->first].end(),
1118 it->second.begin(), it->second.end());
1122 void InsetInclude::updateCommand()
1127 docstring old_label = label_->getParam("name");
1128 label_->updateLabel(old_label);
1129 // the label might have been adapted (duplicate)
1130 docstring new_label = label_->getParam("name");
1131 if (old_label == new_label)
1134 // update listings parameters...
1135 InsetCommandParams p(INCLUDE_CODE);
1137 InsetListingsParams par(to_utf8(params()["lstparams"]));
1138 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1139 p["lstparams"] = from_utf8(par.params());
1144 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1146 Buffer const * const childbuffer = getChildBuffer();
1148 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1151 if (!isListings(params()))
1155 label_->updateBuffer(it, utype);
1157 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1158 if (par.getParamValue("caption").empty()) {
1159 listings_label_ = buffer().B_("Program Listing");
1162 Buffer const & master = *buffer().masterBuffer();
1163 Counters & counters = master.params().documentClass().counters();
1164 docstring const cnt = from_ascii("listing");
1165 listings_label_ = master.B_("Program Listing");
1166 if (counters.hasCounter(cnt)) {
1167 counters.step(cnt, utype);
1168 listings_label_ += " " + convert<docstring>(counters.value(cnt));