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"
22 #include "DispatchResult.h"
23 #include "ErrorList.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
29 #include "LayoutFile.h"
30 #include "LayoutModuleList.h"
35 #include "MetricsInfo.h"
36 #include "output_xhtml.h"
37 #include "OutputParams.h"
38 #include "TextClass.h"
39 #include "TocBackend.h"
41 #include "frontends/alert.h"
42 #include "frontends/Painter.h"
44 #include "graphics/PreviewImage.h"
45 #include "graphics/PreviewLoader.h"
47 #include "insets/InsetLabel.h"
48 #include "insets/InsetListingsParams.h"
49 #include "insets/RenderPreview.h"
51 #include "support/convert.h"
52 #include "support/debug.h"
53 #include "support/docstream.h"
54 #include "support/FileNameList.h"
55 #include "support/filetools.h"
56 #include "support/gettext.h"
57 #include "support/lassert.h"
58 #include "support/lstrings.h" // contains
59 #include "support/lyxalgo.h"
61 #include <boost/bind.hpp>
64 using namespace lyx::support;
68 namespace Alert = frontend::Alert;
73 docstring const uniqueID()
75 static unsigned int seed = 1000;
76 return "file" + convert<docstring>(++seed);
80 /// the type of inclusion
82 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
86 Types type(string const & s)
90 if (s == "verbatiminput")
92 if (s == "verbatiminput*")
94 if (s == "lstinputlisting")
102 Types type(InsetCommandParams const & params)
104 return type(params.getCmdName());
108 bool isListings(InsetCommandParams const & params)
110 return type(params) == LISTINGS;
114 bool isVerbatim(InsetCommandParams const & params)
116 Types const t = type(params);
117 return t == VERB || t == VERBAST;
121 bool isInputOrInclude(InsetCommandParams const & params)
123 Types const t = type(params);
124 return t == INPUT || t == INCLUDE;
128 FileName const masterFileName(Buffer const & buffer)
130 return buffer.masterBuffer()->fileName();
134 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
137 string const parentFilename(Buffer const & buffer)
139 return buffer.absFileName();
143 FileName const includedFilename(Buffer const & buffer,
144 InsetCommandParams const & params)
146 return makeAbsPath(to_utf8(params["filename"]),
147 onlyPath(parentFilename(buffer)));
151 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
153 if (label_str.empty())
155 InsetCommandParams icp(LABEL_CODE);
156 icp["name"] = label_str;
157 return new InsetLabel(buf, icp);
163 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
164 : InsetCommand(buf, p, "include"), include_label(uniqueID()),
165 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
166 set_label_(false), label_(0), child_buffer_(0)
168 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
170 if (isListings(params())) {
171 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
172 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
177 InsetInclude::InsetInclude(InsetInclude const & other)
178 : InsetCommand(other), include_label(other.include_label),
179 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
180 set_label_(false), label_(0), child_buffer_(0)
182 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
185 label_ = new InsetLabel(*other.label_);
189 InsetInclude::~InsetInclude()
195 void InsetInclude::setBuffer(Buffer & buffer)
197 InsetCommand::setBuffer(buffer);
199 label_->setBuffer(buffer);
203 void InsetInclude::setChildBuffer(Buffer * buffer)
205 child_buffer_ = buffer;
209 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
212 // This is only correct for the case of listings, but it'll do for now.
213 // In the other cases, this second parameter should just be empty.
214 static ParamInfo param_info_;
215 if (param_info_.empty()) {
216 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
217 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
223 bool InsetInclude::isCompatibleCommand(string const & s)
225 return type(s) != NONE;
229 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
231 switch (cmd.action) {
233 case LFUN_INSET_EDIT: {
234 editIncluded(to_utf8(params()["filename"]));
238 case LFUN_INSET_MODIFY: {
239 // It should be OK just to invalidate the cache is setParams()
241 // child_buffer_ = 0;
242 InsetCommandParams p(INCLUDE_CODE);
243 if (cmd.getArg(0) == "changetype") {
244 InsetCommand::doDispatch(cur, cmd);
247 InsetCommand::string2params("include", to_utf8(cmd.argument()), p);
248 if (!p.getCmdName().empty()) {
250 InsetListingsParams new_params(to_utf8(p["lstparams"]));
251 docstring const new_label =
252 from_utf8(new_params.getParamValue("label"));
254 if (new_label.empty()) {
260 old_label = label_->getParam("name");
262 label_ = createLabel(buffer_, new_label);
263 label_->setBuffer(buffer());
266 if (new_label != old_label) {
267 label_->updateCommand(new_label);
268 // the label might have been adapted (duplicate)
269 if (new_label != label_->getParam("name")) {
270 new_params.addParam("label", "{" +
271 to_utf8(label_->getParam("name")) + "}", true);
272 p["lstparams"] = from_utf8(new_params.params());
283 //pass everything else up the chain
285 InsetCommand::doDispatch(cur, cmd);
291 void InsetInclude::editIncluded(string const & file)
293 string const ext = support::getExtension(file);
295 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
298 // tex file or other text file in verbatim mode
299 formats.edit(buffer(),
300 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
305 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
306 FuncStatus & flag) const
308 switch (cmd.action) {
310 case LFUN_INSET_EDIT:
311 flag.setEnabled(true);
314 case LFUN_INSET_MODIFY:
315 if (cmd.getArg(0) == "changetype")
316 return InsetCommand::getStatus(cur, cmd, flag);
318 flag.setEnabled(true);
322 return InsetCommand::getStatus(cur, cmd, flag);
327 void InsetInclude::setParams(InsetCommandParams const & p)
329 // invalidate the cache
332 InsetCommand::setParams(p);
335 if (preview_->monitoring())
336 preview_->stopMonitoring();
338 if (type(params()) == INPUT)
339 add_preview(*preview_, *this, buffer());
341 buffer().updateBibfilesCache();
345 bool InsetInclude::isChildIncluded() const
347 std::list<std::string> includeonlys =
348 buffer().params().getIncludedChildren();
349 if (includeonlys.empty())
351 return (std::find(includeonlys.begin(),
353 to_utf8(params()["filename"])) != includeonlys.end());
357 docstring InsetInclude::screenLabel() const
361 switch (type(params())) {
363 temp = buffer().B_("Input");
366 temp = buffer().B_("Verbatim Input");
369 temp = buffer().B_("Verbatim Input*");
372 if (isChildIncluded())
373 temp = buffer().B_("Include");
375 temp += buffer().B_("Include (excluded)");
378 temp = listings_label_;
381 LASSERT(false, /**/);
386 if (params()["filename"].empty())
389 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
395 Buffer * InsetInclude::getChildBuffer() const
397 Buffer * childBuffer = loadIfNeeded();
399 // FIXME: recursive includes
400 return (childBuffer == &buffer()) ? 0 : childBuffer;
404 Buffer * InsetInclude::loadIfNeeded() const
406 // This is for background export and preview. We don't want to load the
407 // cloned child document again.
408 if (child_buffer_ && theBufferList().isLoaded(child_buffer_)
409 && child_buffer_->isClone())
410 return child_buffer_;
412 // Don't try to load it again if we failed before.
413 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
416 // Use cached Buffer if possible.
417 if (child_buffer_ != 0) {
418 if (theBufferList().isLoaded(child_buffer_))
419 return child_buffer_;
420 // Buffer vanished, so invalidate cache and try to reload.
424 string const parent_filename = buffer().absFileName();
425 FileName const included_file =
426 makeAbsPath(to_utf8(params()["filename"]), onlyPath(parent_filename));
428 if (!isLyXFilename(included_file.absFilename()))
431 Buffer * child = theBufferList().getBuffer(included_file);
433 // the readonly flag can/will be wrong, not anymore I think.
434 if (!included_file.exists())
437 child = theBufferList().newBuffer(included_file.absFilename());
439 // Buffer creation is not possible.
442 if (!child->loadLyXFile(included_file)) {
443 failedtoload_ = true;
444 //close the buffer we just opened
445 theBufferList().release(child);
449 if (!child->errorList("Parse").empty()) {
450 // FIXME: Do something.
453 child->setParent(&buffer());
454 // Cache the child buffer.
455 child_buffer_ = child;
460 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
462 string incfile = to_utf8(params()["filename"]);
464 // Do nothing if no file name has been specified
468 FileName const included_file = includedFilename(buffer(), params());
470 // Check we're not trying to include ourselves.
471 // FIXME RECURSIVE INCLUDE
472 // This isn't sufficient, as the inclusion could be downstream.
473 // But it'll have to do for now.
474 if (isInputOrInclude(params()) &&
475 buffer().absFileName() == included_file.absFilename())
477 Alert::error(_("Recursive input"),
478 bformat(_("Attempted to include file %1$s in itself! "
479 "Ignoring inclusion."), from_utf8(incfile)));
483 Buffer const * const masterBuffer = buffer().masterBuffer();
485 // if incfile is relative, make it relative to the master
487 if (!FileName::isAbsolute(incfile)) {
489 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
490 from_utf8(masterBuffer->filePath())));
493 // write it to a file (so far the complete file)
497 if (type(params()) == LISTINGS) {
498 exportfile = incfile;
499 mangled = DocFileName(included_file).mangledFilename();
501 exportfile = changeExtension(incfile, ".tex");
502 mangled = DocFileName(changeExtension(included_file.absFilename(), ".tex")).
506 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
510 else if (!isValidLaTeXFilename(incfile)) {
511 frontend::Alert::warning(_("Invalid filename"),
512 _("The following filename is likely to cause trouble "
513 "when running the exported file through LaTeX: ") +
516 LYXERR(Debug::LATEX, "incfile:" << incfile);
517 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
518 LYXERR(Debug::LATEX, "writefile:" << writefile);
520 if (runparams.inComment || runparams.dryrun) {
521 //Don't try to load or copy the file if we're
522 //in a comment or doing a dryrun
523 } else if (isInputOrInclude(params()) &&
524 isLyXFilename(included_file.absFilename())) {
525 //if it's a LyX file and we're inputting or including,
526 //try to load it so we can write the associated latex
530 Buffer * tmp = theBufferList().getBuffer(included_file);
532 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
534 docstring text = bformat(_("Included file `%1$s'\n"
535 "has textclass `%2$s'\n"
536 "while parent file has textclass `%3$s'."),
537 included_file.displayName(),
538 from_utf8(tmp->params().documentClass().name()),
539 from_utf8(masterBuffer->params().documentClass().name()));
540 Alert::warning(_("Different textclasses"), text, true);
543 // Make sure modules used in child are all included in master
544 // FIXME It might be worth loading the children's modules into the master
545 // over in BufferParams rather than doing this check.
546 LayoutModuleList const masterModules = masterBuffer->params().getModules();
547 LayoutModuleList const childModules = tmp->params().getModules();
548 LayoutModuleList::const_iterator it = childModules.begin();
549 LayoutModuleList::const_iterator end = childModules.end();
550 for (; it != end; ++it) {
551 string const module = *it;
552 LayoutModuleList::const_iterator found =
553 find(masterModules.begin(), masterModules.end(), module);
554 if (found == masterModules.end()) {
555 docstring text = bformat(_("Included file `%1$s'\n"
556 "uses module `%2$s'\n"
557 "which is not used in parent file."),
558 included_file.displayName(), from_utf8(module));
559 Alert::warning(_("Module not found"), text);
563 tmp->markDepClean(masterBuffer->temppath());
565 // FIXME: handle non existing files
566 // FIXME: Second argument is irrelevant!
567 // since only_body is true, makeLaTeXFile will not look at second
568 // argument. Should we set it to string(), or should makeLaTeXFile
569 // make use of it somehow? (JMarc 20031002)
570 // The included file might be written in a different encoding
572 Encoding const * const oldEnc = runparams.encoding;
573 Language const * const oldLang = runparams.master_language;
574 runparams.encoding = &tmp->params().encoding();
575 runparams.master_language = buffer().params().language;
576 tmp->makeLaTeXFile(writefile,
577 masterFileName(buffer()).onlyPath().absFilename(),
579 runparams.encoding = oldEnc;
580 runparams.master_language = oldLang;
582 // In this case, it's not a LyX file, so we copy the file
583 // to the temp dir, so that .aux files etc. are not created
584 // in the original dir. Files included by this file will be
585 // found via input@path, see ../Buffer.cpp.
586 unsigned long const checksum_in = included_file.checksum();
587 unsigned long const checksum_out = writefile.checksum();
589 if (checksum_in != checksum_out) {
590 if (!included_file.copyTo(writefile)) {
593 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
594 "into the temporary directory."),
595 from_utf8(included_file.absFilename()))));
601 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
602 "latex" : "pdflatex";
603 switch (type(params())) {
606 incfile = latex_path(incfile);
608 os << '\\' << from_ascii(params().getCmdName()) << '{'
609 << from_utf8(incfile) << '}';
613 runparams.exportdata->addExternalFile(tex_format, writefile,
616 // \input wants file with extension (default is .tex)
617 if (!isLyXFilename(included_file.absFilename())) {
618 incfile = latex_path(incfile);
620 os << '\\' << from_ascii(params().getCmdName())
621 << '{' << from_utf8(incfile) << '}';
623 incfile = changeExtension(incfile, ".tex");
624 incfile = latex_path(incfile);
626 os << '\\' << from_ascii(params().getCmdName())
627 << '{' << from_utf8(incfile) << '}';
632 os << '\\' << from_ascii(params().getCmdName());
633 string const opt = to_utf8(params()["lstparams"]);
634 // opt is set in QInclude dialog and should have passed validation.
635 InsetListingsParams params(opt);
636 if (!params.params().empty())
637 os << "[" << from_utf8(params.params()) << "]";
638 os << '{' << from_utf8(incfile) << '}';
642 runparams.exportdata->addExternalFile(tex_format, writefile,
645 // \include don't want extension and demands that the
646 // file really have .tex
647 incfile = changeExtension(incfile, string());
648 incfile = latex_path(incfile);
650 os << '\\' << from_ascii(params().getCmdName()) << '{'
651 << from_utf8(incfile) << '}';
662 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const &rp) const
667 // For verbatim and listings, we just include the contents of the file as-is.
668 // In the case of listings, we wrap it in <pre>.
669 bool const listing = isListings(params());
670 if (listing || isVerbatim(params())) {
672 xs << html::StartTag("pre");
673 // FIXME: We don't know the encoding of the file, default to UTF-8.
674 xs << includedFilename(buffer(), params()).fileContents("UTF-8");
676 xs << html::EndTag("pre");
680 // We don't (yet) know how to Input or Include non-LyX files.
681 // (If we wanted to get really arcane, we could run some tex2html
682 // converter on the included file. But that's just masochistic.)
683 string const parent_filename = buffer().absFileName();
684 FileName const included_file =
685 makeAbsPath(to_utf8(params()["filename"]), onlyPath(parent_filename));
686 if (!isLyXFilename(included_file.absFilename())) {
687 frontend::Alert::warning(_("Unsupported Inclusion"),
688 bformat(_("LyX does not know how to include non-LyX files when "
689 "generating HTML output. Offending file:\n%1$s"),
690 params()["filename"]));
694 // In the other cases, we will generate the HTML and include it.
696 // Check we're not trying to include ourselves.
697 // FIXME RECURSIVE INCLUDE
698 if (buffer().absFileName() == included_file.absFilename()) {
699 Alert::error(_("Recursive input"),
700 bformat(_("Attempted to include file %1$s in itself! "
701 "Ignoring inclusion."), params()["filename"]));
705 Buffer const * const ibuf = loadIfNeeded();
708 ibuf->writeLyXHTMLSource(xs.os(), rp, true);
713 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
715 if (isVerbatim(params()) || isListings(params())) {
716 os << '[' << screenLabel() << '\n';
717 // FIXME: We don't know the encoding of the file, default to UTF-8.
718 os << includedFilename(buffer(), params()).fileContents("UTF-8");
720 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
722 docstring const str = '[' + screenLabel() + ']';
729 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
731 string incfile = to_utf8(params()["filename"]);
733 // Do nothing if no file name has been specified
737 string const included_file = includedFilename(buffer(), params()).absFilename();
739 // Check we're not trying to include ourselves.
740 // FIXME RECURSIVE INCLUDE
741 // This isn't sufficient, as the inclusion could be downstream.
742 // But it'll have to do for now.
743 if (buffer().absFileName() == included_file) {
744 Alert::error(_("Recursive input"),
745 bformat(_("Attempted to include file %1$s in itself! "
746 "Ignoring inclusion."), from_utf8(incfile)));
750 // write it to a file (so far the complete file)
751 string const exportfile = changeExtension(incfile, ".sgml");
752 DocFileName writefile(changeExtension(included_file, ".sgml"));
754 if (loadIfNeeded()) {
755 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
757 string const mangled = writefile.mangledFilename();
758 writefile = makeAbsPath(mangled,
759 buffer().masterBuffer()->temppath());
763 LYXERR(Debug::LATEX, "incfile:" << incfile);
764 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
765 LYXERR(Debug::LATEX, "writefile:" << writefile);
767 tmp->makeDocBookFile(writefile, runparams, true);
770 runparams.exportdata->addExternalFile("docbook", writefile,
772 runparams.exportdata->addExternalFile("docbook-xml", writefile,
775 if (isVerbatim(params()) || isListings(params())) {
776 os << "<inlinegraphic fileref=\""
777 << '&' << include_label << ';'
778 << "\" format=\"linespecific\">";
780 os << '&' << include_label << ';';
786 void InsetInclude::validate(LaTeXFeatures & features) const
788 string incfile = to_utf8(params()["filename"]);
791 LASSERT(&buffer() == &features.buffer(), /**/);
793 string const included_file =
794 includedFilename(buffer(), params()).absFilename();
796 if (isLyXFilename(included_file))
797 writefile = changeExtension(included_file, ".sgml");
799 writefile = included_file;
801 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
802 incfile = DocFileName(writefile).mangledFilename();
803 writefile = makeAbsPath(incfile,
804 buffer().masterBuffer()->temppath()).absFilename();
807 features.includeFile(include_label, writefile);
809 if (isVerbatim(params()))
810 features.require("verbatim");
811 else if (isListings(params()))
812 features.require("listings");
814 // Here we must do the fun stuff...
815 // Load the file in the include if it needs
817 if (loadIfNeeded()) {
819 Buffer * const tmp = theBufferList().getBuffer(FileName(included_file));
820 // make sure the buffer isn't us
821 // FIXME RECURSIVE INCLUDES
822 // This is not sufficient, as recursive includes could be
823 // more than a file away. But it will do for now.
824 if (tmp && tmp != &buffer()) {
825 // We must temporarily change features.buffer,
826 // otherwise it would always be the master buffer,
827 // and nested includes would not work.
828 features.setBuffer(*tmp);
829 tmp->validate(features);
830 features.setBuffer(buffer());
836 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
837 InsetIterator const & /*di*/) const
839 if (loadIfNeeded()) {
840 string const included_file = includedFilename(buffer(), params()).absFilename();
841 Buffer * tmp = theBufferList().getBuffer(FileName(included_file));
842 BiblioInfo const & newkeys = tmp->localBibInfo();
843 keys.mergeBiblioInfo(newkeys);
848 void InsetInclude::updateBibfilesCache()
850 Buffer const * const child = getChildBuffer();
852 child->updateBibfilesCache(Buffer::UpdateChildOnly);
856 support::FileNameList const &
857 InsetInclude::getBibfilesCache() const
859 Buffer const * const child = getChildBuffer();
861 return child->getBibfilesCache(Buffer::UpdateChildOnly);
863 static support::FileNameList const empty;
868 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
870 LASSERT(mi.base.bv, /**/);
872 bool use_preview = false;
873 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
874 graphics::PreviewImage const * pimage =
875 preview_->getPreviewImage(mi.base.bv->buffer());
876 use_preview = pimage && pimage->image();
880 preview_->metrics(mi, dim);
884 button_.update(screenLabel(), true);
886 button_.metrics(mi, dim);
889 Box b(0, dim.wid, -dim.asc, dim.des);
894 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
896 LASSERT(pi.base.bv, /**/);
898 bool use_preview = false;
899 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
900 graphics::PreviewImage const * pimage =
901 preview_->getPreviewImage(pi.base.bv->buffer());
902 use_preview = pimage && pimage->image();
906 preview_->draw(pi, x, y);
908 button_.draw(pi, x, y);
912 docstring InsetInclude::contextMenu(BufferView const &, int, int) const
914 return from_ascii("context-include");
918 Inset::DisplayType InsetInclude::display() const
920 return type(params()) == INPUT ? Inline : AlignCenter;
929 void InsetInclude::fileChanged() const
931 Buffer const * const buffer = updateFrontend();
935 preview_->removePreview(*buffer);
936 add_preview(*preview_.get(), *this, *buffer);
937 preview_->startLoading(*buffer);
943 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
945 FileName const included_file = includedFilename(buffer, params);
947 return type(params) == INPUT && params.preview() &&
948 included_file.isReadableFile();
952 docstring latexString(InsetInclude const & inset)
955 // We don't need to set runparams.encoding since this will be done
956 // by latex() anyway.
957 OutputParams runparams(0);
958 runparams.flavor = OutputParams::LATEX;
959 inset.latex(os, runparams);
965 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
966 Buffer const & buffer)
968 InsetCommandParams const & params = inset.params();
969 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
970 preview_wanted(params, buffer)) {
971 renderer.setAbsFile(includedFilename(buffer, params));
972 docstring const snippet = latexString(inset);
973 renderer.addPreview(snippet, buffer);
980 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
981 graphics::PreviewLoader & ploader) const
983 Buffer const & buffer = ploader.buffer();
984 if (!preview_wanted(params(), buffer))
986 preview_->setAbsFile(includedFilename(buffer, params()));
987 docstring const snippet = latexString(*this);
988 preview_->addPreview(snippet, ploader);
992 void InsetInclude::addToToc(DocIterator const & cpit)
994 TocBackend & backend = buffer().tocBackend();
996 if (isListings(params())) {
998 label_->addToToc(cpit);
1000 InsetListingsParams p(to_utf8(params()["lstparams"]));
1001 string caption = p.getParamValue("caption");
1002 if (caption.empty())
1004 Toc & toc = backend.toc("listing");
1005 docstring str = convert<docstring>(toc.size() + 1)
1006 + ". " + from_utf8(caption);
1007 DocIterator pit = cpit;
1008 toc.push_back(TocItem(pit, 0, str));
1011 Buffer const * const childbuffer = getChildBuffer();
1015 Toc & toc = backend.toc("child");
1016 docstring str = childbuffer->fileName().displayName();
1017 toc.push_back(TocItem(cpit, 0, str));
1019 TocList & toclist = backend.tocs();
1020 childbuffer->tocBackend().update();
1021 TocList const & childtoclist = childbuffer->tocBackend().tocs();
1022 TocList::const_iterator it = childtoclist.begin();
1023 TocList::const_iterator const end = childtoclist.end();
1024 for(; it != end; ++it)
1025 toclist[it->first].insert(toclist[it->first].end(),
1026 it->second.begin(), it->second.end());
1030 void InsetInclude::updateCommand()
1035 docstring old_label = label_->getParam("name");
1036 label_->updateCommand(old_label, false);
1037 // the label might have been adapted (duplicate)
1038 docstring new_label = label_->getParam("name");
1039 if (old_label == new_label)
1042 // update listings parameters...
1043 InsetCommandParams p(INCLUDE_CODE);
1045 InsetListingsParams par(to_utf8(params()["lstparams"]));
1046 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1047 p["lstparams"] = from_utf8(par.params());
1051 void InsetInclude::updateLabels(ParIterator const & it, UpdateType utype)
1053 Buffer const * const childbuffer = getChildBuffer();
1055 childbuffer->updateLabels(Buffer::UpdateChildOnly, utype);
1058 if (!isListings(params()))
1062 label_->updateLabels(it, utype);
1064 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1065 if (par.getParamValue("caption").empty()) {
1066 listings_label_ = buffer().B_("Program Listing");
1069 Buffer const & master = *buffer().masterBuffer();
1070 Counters & counters = master.params().documentClass().counters();
1071 docstring const cnt = from_ascii("listing");
1072 listings_label_ = master.B_("Program Listing");
1073 if (counters.hasCounter(cnt)) {
1074 counters.step(cnt, utype);
1075 listings_label_ += " " + convert<docstring>(counters.value(cnt));