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"
24 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LaTeXFeatures.h"
30 #include "LayoutFile.h"
31 #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 "mathed/MacroTable.h"
53 #include "support/convert.h"
54 #include "support/debug.h"
55 #include "support/docstream.h"
56 #include "support/FileNameList.h"
57 #include "support/filetools.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/lstrings.h" // contains
61 #include "support/lyxalgo.h"
63 #include "support/bind.h"
66 using namespace lyx::support;
70 namespace Alert = frontend::Alert;
75 docstring const uniqueID()
77 static unsigned int seed = 1000;
78 return "file" + convert<docstring>(++seed);
82 /// the type of inclusion
84 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
88 Types type(string const & s)
92 if (s == "verbatiminput")
94 if (s == "verbatiminput*")
96 if (s == "lstinputlisting")
104 Types type(InsetCommandParams const & params)
106 return type(params.getCmdName());
110 bool isListings(InsetCommandParams const & params)
112 return type(params) == LISTINGS;
116 bool isVerbatim(InsetCommandParams const & params)
118 Types const t = type(params);
119 return t == VERB || t == VERBAST;
123 bool isInputOrInclude(InsetCommandParams const & params)
125 Types const t = type(params);
126 return t == INPUT || t == INCLUDE;
130 FileName const masterFileName(Buffer const & buffer)
132 return buffer.masterBuffer()->fileName();
136 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
139 string const parentFileName(Buffer const & buffer)
141 return buffer.absFileName();
145 FileName const includedFileName(Buffer const & buffer,
146 InsetCommandParams const & params)
148 return makeAbsPath(to_utf8(params["filename"]),
149 onlyPath(parentFileName(buffer)));
153 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
155 if (label_str.empty())
157 InsetCommandParams icp(LABEL_CODE);
158 icp["name"] = label_str;
159 return new InsetLabel(buf, icp);
165 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
166 : InsetCommand(buf, p), include_label(uniqueID()),
167 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
168 set_label_(false), label_(0), child_buffer_(0)
170 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
172 if (isListings(params())) {
173 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
174 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
175 } else if (isInputOrInclude(params()) && buf)
180 InsetInclude::InsetInclude(InsetInclude const & other)
181 : InsetCommand(other), include_label(other.include_label),
182 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
183 set_label_(false), label_(0), child_buffer_(0)
185 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
188 label_ = new InsetLabel(*other.label_);
192 InsetInclude::~InsetInclude()
194 if (isBufferLoaded())
195 buffer().invalidateBibfileCache();
200 void InsetInclude::setBuffer(Buffer & buffer)
202 InsetCommand::setBuffer(buffer);
204 label_->setBuffer(buffer);
208 void InsetInclude::setChildBuffer(Buffer * buffer)
210 child_buffer_ = buffer;
214 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
217 // This is only correct for the case of listings, but it'll do for now.
218 // In the other cases, this second parameter should just be empty.
219 static ParamInfo param_info_;
220 if (param_info_.empty()) {
221 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
222 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
228 bool InsetInclude::isCompatibleCommand(string const & s)
230 return type(s) != NONE;
234 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
236 switch (cmd.action()) {
238 case LFUN_INSET_EDIT: {
239 editIncluded(to_utf8(params()["filename"]));
243 case LFUN_INSET_MODIFY: {
244 // It should be OK just to invalidate the cache in setParams()
246 // child_buffer_ = 0;
247 InsetCommandParams p(INCLUDE_CODE);
248 if (cmd.getArg(0) == "changetype") {
250 InsetCommand::doDispatch(cur, cmd);
253 InsetCommand::string2params(to_utf8(cmd.argument()), p);
254 if (!p.getCmdName().empty()) {
256 InsetListingsParams new_params(to_utf8(p["lstparams"]));
257 docstring const new_label =
258 from_utf8(new_params.getParamValue("label"));
260 if (new_label.empty()) {
266 old_label = label_->getParam("name");
268 label_ = createLabel(buffer_, new_label);
269 label_->setBuffer(buffer());
272 if (new_label != old_label) {
273 label_->updateCommand(new_label);
274 // the label might have been adapted (duplicate)
275 if (new_label != label_->getParam("name")) {
276 new_params.addParam("label", "{" +
277 to_utf8(label_->getParam("name")) + "}", true);
278 p["lstparams"] = from_utf8(new_params.params());
285 cur.forceBufferUpdate();
287 cur.noScreenUpdate();
291 //pass everything else up the chain
293 InsetCommand::doDispatch(cur, cmd);
299 void InsetInclude::editIncluded(string const & file)
301 string const ext = support::getExtension(file);
303 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
306 // tex file or other text file in verbatim mode
307 formats.edit(buffer(),
308 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
313 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
314 FuncStatus & flag) const
316 switch (cmd.action()) {
318 case LFUN_INSET_EDIT:
319 flag.setEnabled(true);
322 case LFUN_INSET_MODIFY:
323 if (cmd.getArg(0) == "changetype")
324 return InsetCommand::getStatus(cur, cmd, flag);
326 flag.setEnabled(true);
330 return InsetCommand::getStatus(cur, cmd, flag);
335 void InsetInclude::setParams(InsetCommandParams const & p)
337 // invalidate the cache
340 InsetCommand::setParams(p);
343 if (preview_->monitoring())
344 preview_->stopMonitoring();
346 if (type(params()) == INPUT)
347 add_preview(*preview_, *this, buffer());
349 buffer().invalidateBibfileCache();
353 bool InsetInclude::isChildIncluded() const
355 std::list<std::string> includeonlys =
356 buffer().params().getIncludedChildren();
357 if (includeonlys.empty())
359 return (std::find(includeonlys.begin(),
361 to_utf8(params()["filename"])) != includeonlys.end());
365 docstring InsetInclude::screenLabel() const
369 switch (type(params())) {
371 temp = buffer().B_("Input");
374 temp = buffer().B_("Verbatim Input");
377 temp = buffer().B_("Verbatim Input*");
380 if (isChildIncluded())
381 temp = buffer().B_("Include");
383 temp += buffer().B_("Include (excluded)");
386 temp = listings_label_;
389 LASSERT(false, /**/);
394 if (params()["filename"].empty())
397 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
403 Buffer * InsetInclude::getChildBuffer() const
405 Buffer * childBuffer = loadIfNeeded();
407 // FIXME: recursive includes
408 return (childBuffer == &buffer()) ? 0 : childBuffer;
412 Buffer * InsetInclude::loadIfNeeded() const
414 // This is for background export and preview. We don't even want to
415 // try to load the cloned child document again.
416 if (buffer().isClone())
417 return child_buffer_;
419 // Don't try to load it again if we failed before.
420 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
423 FileName const included_file = includedFileName(buffer(), params());
424 // Use cached Buffer if possible.
425 if (child_buffer_ != 0) {
426 if (theBufferList().isLoaded(child_buffer_)
427 // additional sanity check: make sure the Buffer really is
428 // associated with the file we want.
429 && child_buffer_ == theBufferList().getBuffer(included_file))
430 return child_buffer_;
431 // Buffer vanished, so invalidate cache and try to reload.
435 if (!isLyXFileName(included_file.absFileName()))
438 Buffer * child = theBufferList().getBuffer(included_file);
440 // the readonly flag can/will be wrong, not anymore I think.
441 if (!included_file.exists())
444 child = theBufferList().newBuffer(included_file.absFileName());
446 // Buffer creation is not possible.
449 // Set parent before loading, such that macros can be tracked
450 child->setParent(&buffer());
452 if (child->loadLyXFile() != Buffer::ReadSuccess) {
453 failedtoload_ = true;
455 //close the buffer we just opened
456 theBufferList().release(child);
460 if (!child->errorList("Parse").empty()) {
461 // FIXME: Do something.
464 // The file was already loaded, so, simply
465 // inform parent buffer about local macros.
466 Buffer const * parent = &buffer();
467 child->setParent(parent);
469 child->listMacroNames(macros);
470 MacroNameSet::const_iterator cit = macros.begin();
471 MacroNameSet::const_iterator end = macros.end();
472 for (; cit != end; ++cit)
473 parent->usermacros.insert(*cit);
476 // Cache the child buffer.
477 child_buffer_ = child;
482 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
484 string incfile = to_utf8(params()["filename"]);
486 // Do nothing if no file name has been specified
490 FileName const included_file = includedFileName(buffer(), params());
492 // Check we're not trying to include ourselves.
493 // FIXME RECURSIVE INCLUDE
494 // This isn't sufficient, as the inclusion could be downstream.
495 // But it'll have to do for now.
496 if (isInputOrInclude(params()) &&
497 buffer().absFileName() == included_file.absFileName())
499 Alert::error(_("Recursive input"),
500 bformat(_("Attempted to include file %1$s in itself! "
501 "Ignoring inclusion."), from_utf8(incfile)));
505 Buffer const * const masterBuffer = buffer().masterBuffer();
507 // if incfile is relative, make it relative to the master
509 if (!FileName::isAbsolute(incfile)) {
511 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
512 from_utf8(masterBuffer->filePath())));
515 // write it to a file (so far the complete file)
519 if (type(params()) == LISTINGS) {
520 exportfile = incfile;
521 mangled = DocFileName(included_file).mangledFileName();
523 exportfile = changeExtension(incfile, ".tex");
524 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
528 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
532 else if (!isValidLaTeXFileName(incfile)) {
533 frontend::Alert::warning(_("Invalid filename"),
534 _("The following filename will cause troubles "
535 "when running the exported file through LaTeX: ") +
538 else if (!isValidDVIFileName(incfile)) {
539 frontend::Alert::warning(_("Problematic filename for DVI"),
540 _("The following filename can cause troubles "
541 "when running the exported file through LaTeX "
542 "and opening the resulting DVI: ") +
543 from_utf8(incfile), true);
545 LYXERR(Debug::LATEX, "incfile:" << incfile);
546 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
547 LYXERR(Debug::LATEX, "writefile:" << writefile);
549 if (runparams.inComment || runparams.dryrun) {
550 //Don't try to load or copy the file if we're
551 //in a comment or doing a dryrun
552 } else if (isInputOrInclude(params()) &&
553 isLyXFileName(included_file.absFileName())) {
554 // if it's a LyX file and we're inputting or including,
555 // try to load it so we can write the associated latex
557 Buffer * tmp = loadIfNeeded();
561 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
563 docstring text = bformat(_("Included file `%1$s'\n"
564 "has textclass `%2$s'\n"
565 "while parent file has textclass `%3$s'."),
566 included_file.displayName(),
567 from_utf8(tmp->params().documentClass().name()),
568 from_utf8(masterBuffer->params().documentClass().name()));
569 Alert::warning(_("Different textclasses"), text, true);
572 // Make sure modules used in child are all included in master
573 // FIXME It might be worth loading the children's modules into the master
574 // over in BufferParams rather than doing this check.
575 LayoutModuleList const masterModules = masterBuffer->params().getModules();
576 LayoutModuleList const childModules = tmp->params().getModules();
577 LayoutModuleList::const_iterator it = childModules.begin();
578 LayoutModuleList::const_iterator end = childModules.end();
579 for (; it != end; ++it) {
580 string const module = *it;
581 LayoutModuleList::const_iterator found =
582 find(masterModules.begin(), masterModules.end(), module);
583 if (found == masterModules.end()) {
584 docstring text = bformat(_("Included file `%1$s'\n"
585 "uses module `%2$s'\n"
586 "which is not used in parent file."),
587 included_file.displayName(), from_utf8(module));
588 Alert::warning(_("Module not found"), text);
592 tmp->markDepClean(masterBuffer->temppath());
594 // FIXME: handle non existing files
595 // FIXME: Second argument is irrelevant!
596 // since only_body is true, makeLaTeXFile will not look at second
597 // argument. Should we set it to string(), or should makeLaTeXFile
598 // make use of it somehow? (JMarc 20031002)
599 // The included file might be written in a different encoding
601 Encoding const * const oldEnc = runparams.encoding;
602 Language const * const oldLang = runparams.master_language;
603 // If the master has full unicode flavor (XeTeX, LuaTeX),
604 // the children must be encoded in plain utf8!
605 runparams.encoding = runparams.isFullUnicode() ?
606 encodings.fromLyXName("utf8-plain")
607 : &tmp->params().encoding();
608 runparams.master_language = buffer().params().language;
609 runparams.par_begin = 0;
610 runparams.par_end = tmp->paragraphs().size();
611 if (!tmp->makeLaTeXFile(writefile, masterFileName(buffer()).
612 onlyPath().absFileName(), runparams, false)) {
613 docstring msg = bformat(_("Included file `%1$s' "
614 "was not exported correctly.\nWarning: "
615 "LaTeX export is probably incomplete."),
616 included_file.displayName());
617 ErrorList & el = tmp->errorList("Export");
619 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
620 msg, el.begin()->error,
621 el.begin()->description);
622 Alert::warning(_("Export failure"), msg);
624 runparams.encoding = oldEnc;
625 runparams.master_language = oldLang;
627 // In this case, it's not a LyX file, so we copy the file
628 // to the temp dir, so that .aux files etc. are not created
629 // in the original dir. Files included by this file will be
630 // found via input@path, see ../Buffer.cpp.
631 unsigned long const checksum_in = included_file.checksum();
632 unsigned long const checksum_out = writefile.checksum();
634 if (checksum_in != checksum_out) {
635 if (!included_file.copyTo(writefile)) {
638 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
639 "into the temporary directory."),
640 from_utf8(included_file.absFileName()))));
646 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
647 "latex" : "pdflatex";
648 switch (type(params())) {
651 incfile = latex_path(incfile);
653 os << '\\' << from_ascii(params().getCmdName()) << '{'
654 << from_utf8(incfile) << '}';
658 runparams.exportdata->addExternalFile(tex_format, writefile,
661 // \input wants file with extension (default is .tex)
662 if (!isLyXFileName(included_file.absFileName())) {
663 incfile = latex_path(incfile);
665 os << '\\' << from_ascii(params().getCmdName())
666 << '{' << from_utf8(incfile) << '}';
668 incfile = changeExtension(incfile, ".tex");
669 incfile = latex_path(incfile);
671 os << '\\' << from_ascii(params().getCmdName())
672 << '{' << from_utf8(incfile) << '}';
677 os << '\\' << from_ascii(params().getCmdName());
678 string const opt = to_utf8(params()["lstparams"]);
679 // opt is set in QInclude dialog and should have passed validation.
680 InsetListingsParams params(opt);
681 if (!params.params().empty())
682 os << "[" << from_utf8(params.params()) << "]";
683 os << '{' << from_utf8(incfile) << '}';
687 runparams.exportdata->addExternalFile(tex_format, writefile,
690 // \include don't want extension and demands that the
691 // file really have .tex
692 incfile = changeExtension(incfile, string());
693 incfile = latex_path(incfile);
695 os << '\\' << from_ascii(params().getCmdName()) << '{'
696 << from_utf8(incfile) << '}';
705 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const &rp) const
710 // For verbatim and listings, we just include the contents of the file as-is.
711 // In the case of listings, we wrap it in <pre>.
712 bool const listing = isListings(params());
713 if (listing || isVerbatim(params())) {
715 xs << html::StartTag("pre");
716 // FIXME: We don't know the encoding of the file, default to UTF-8.
717 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
719 xs << html::EndTag("pre");
723 // We don't (yet) know how to Input or Include non-LyX files.
724 // (If we wanted to get really arcane, we could run some tex2html
725 // converter on the included file. But that's just masochistic.)
726 FileName const included_file = includedFileName(buffer(), params());
727 if (!isLyXFileName(included_file.absFileName())) {
728 frontend::Alert::warning(_("Unsupported Inclusion"),
729 bformat(_("LyX does not know how to include non-LyX files when "
730 "generating HTML output. Offending file:\n%1$s"),
731 params()["filename"]));
735 // In the other cases, we will generate the HTML and include it.
737 // Check we're not trying to include ourselves.
738 // FIXME RECURSIVE INCLUDE
739 if (buffer().absFileName() == included_file.absFileName()) {
740 Alert::error(_("Recursive input"),
741 bformat(_("Attempted to include file %1$s in itself! "
742 "Ignoring inclusion."), params()["filename"]));
746 Buffer const * const ibuf = loadIfNeeded();
749 ibuf->writeLyXHTMLSource(xs.os(), rp, true);
754 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
756 if (isVerbatim(params()) || isListings(params())) {
757 os << '[' << screenLabel() << '\n';
758 // FIXME: We don't know the encoding of the file, default to UTF-8.
759 os << includedFileName(buffer(), params()).fileContents("UTF-8");
761 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
763 docstring const str = '[' + screenLabel() + ']';
770 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
772 string incfile = to_utf8(params()["filename"]);
774 // Do nothing if no file name has been specified
778 string const included_file = includedFileName(buffer(), params()).absFileName();
780 // Check we're not trying to include ourselves.
781 // FIXME RECURSIVE INCLUDE
782 // This isn't sufficient, as the inclusion could be downstream.
783 // But it'll have to do for now.
784 if (buffer().absFileName() == included_file) {
785 Alert::error(_("Recursive input"),
786 bformat(_("Attempted to include file %1$s in itself! "
787 "Ignoring inclusion."), from_utf8(incfile)));
791 // write it to a file (so far the complete file)
792 string const exportfile = changeExtension(incfile, ".sgml");
793 DocFileName writefile(changeExtension(included_file, ".sgml"));
795 Buffer * tmp = loadIfNeeded();
797 string const mangled = writefile.mangledFileName();
798 writefile = makeAbsPath(mangled,
799 buffer().masterBuffer()->temppath());
803 LYXERR(Debug::LATEX, "incfile:" << incfile);
804 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
805 LYXERR(Debug::LATEX, "writefile:" << writefile);
807 tmp->makeDocBookFile(writefile, runparams, true);
810 runparams.exportdata->addExternalFile("docbook", writefile,
812 runparams.exportdata->addExternalFile("docbook-xml", writefile,
815 if (isVerbatim(params()) || isListings(params())) {
816 os << "<inlinegraphic fileref=\""
817 << '&' << include_label << ';'
818 << "\" format=\"linespecific\">";
820 os << '&' << include_label << ';';
826 void InsetInclude::validate(LaTeXFeatures & features) const
828 string incfile = to_utf8(params()["filename"]);
831 LASSERT(&buffer() == &features.buffer(), /**/);
833 string const included_file =
834 includedFileName(buffer(), params()).absFileName();
836 if (isLyXFileName(included_file))
837 writefile = changeExtension(included_file, ".sgml");
839 writefile = included_file;
841 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
842 incfile = DocFileName(writefile).mangledFileName();
843 writefile = makeAbsPath(incfile,
844 buffer().masterBuffer()->temppath()).absFileName();
847 features.includeFile(include_label, writefile);
849 if (isVerbatim(params()))
850 features.require("verbatim");
851 else if (isListings(params()))
852 features.require("listings");
854 // Here we must do the fun stuff...
855 // Load the file in the include if it needs
857 Buffer * const tmp = loadIfNeeded();
859 // the file is loaded
860 // make sure the buffer isn't us
861 // FIXME RECURSIVE INCLUDES
862 // This is not sufficient, as recursive includes could be
863 // more than a file away. But it will do for now.
864 if (tmp && tmp != &buffer()) {
865 // We must temporarily change features.buffer,
866 // otherwise it would always be the master buffer,
867 // and nested includes would not work.
868 features.setBuffer(*tmp);
869 tmp->validate(features);
870 features.setBuffer(buffer());
876 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
878 Buffer * child = loadIfNeeded();
881 child->collectBibKeys();
885 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
887 LASSERT(mi.base.bv, /**/);
889 bool use_preview = false;
890 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
891 graphics::PreviewImage const * pimage =
892 preview_->getPreviewImage(mi.base.bv->buffer());
893 use_preview = pimage && pimage->image();
897 preview_->metrics(mi, dim);
901 button_.update(screenLabel(), true);
903 button_.metrics(mi, dim);
906 Box b(0, dim.wid, -dim.asc, dim.des);
911 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
913 LASSERT(pi.base.bv, /**/);
915 bool use_preview = false;
916 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
917 graphics::PreviewImage const * pimage =
918 preview_->getPreviewImage(pi.base.bv->buffer());
919 use_preview = pimage && pimage->image();
923 preview_->draw(pi, x, y);
925 button_.draw(pi, x, y);
929 docstring InsetInclude::contextMenuName() const
931 return from_ascii("context-include");
935 Inset::DisplayType InsetInclude::display() const
937 return type(params()) == INPUT ? Inline : AlignCenter;
946 void InsetInclude::fileChanged() const
948 Buffer const * const buffer = updateFrontend();
952 preview_->removePreview(*buffer);
953 add_preview(*preview_.get(), *this, *buffer);
954 preview_->startLoading(*buffer);
960 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
962 FileName const included_file = includedFileName(buffer, params);
964 return type(params) == INPUT && params.preview() &&
965 included_file.isReadableFile();
969 docstring latexString(InsetInclude const & inset)
972 odocstringstream ods;
973 otexstream os(ods, texrow);
974 // We don't need to set runparams.encoding since this will be done
975 // by latex() anyway.
976 OutputParams runparams(0);
977 runparams.flavor = OutputParams::LATEX;
978 inset.latex(os, runparams);
984 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
985 Buffer const & buffer)
987 InsetCommandParams const & params = inset.params();
988 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
989 preview_wanted(params, buffer)) {
990 renderer.setAbsFile(includedFileName(buffer, params));
991 docstring const snippet = latexString(inset);
992 renderer.addPreview(snippet, buffer);
999 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1000 graphics::PreviewLoader & ploader) const
1002 Buffer const & buffer = ploader.buffer();
1003 if (!preview_wanted(params(), buffer))
1005 preview_->setAbsFile(includedFileName(buffer, params()));
1006 docstring const snippet = latexString(*this);
1007 preview_->addPreview(snippet, ploader);
1011 void InsetInclude::addToToc(DocIterator const & cpit) const
1013 TocBackend & backend = buffer().tocBackend();
1015 if (isListings(params())) {
1017 label_->addToToc(cpit);
1019 InsetListingsParams p(to_utf8(params()["lstparams"]));
1020 string caption = p.getParamValue("caption");
1021 if (caption.empty())
1023 Toc & toc = backend.toc("listing");
1024 docstring str = convert<docstring>(toc.size() + 1)
1025 + ". " + from_utf8(caption);
1026 DocIterator pit = cpit;
1027 toc.push_back(TocItem(pit, 0, str));
1030 Buffer const * const childbuffer = getChildBuffer();
1034 Toc & toc = backend.toc("child");
1035 docstring str = childbuffer->fileName().displayName();
1036 toc.push_back(TocItem(cpit, 0, str));
1038 TocList & toclist = backend.tocs();
1039 childbuffer->tocBackend().update();
1040 TocList const & childtoclist = childbuffer->tocBackend().tocs();
1041 TocList::const_iterator it = childtoclist.begin();
1042 TocList::const_iterator const end = childtoclist.end();
1043 for(; it != end; ++it)
1044 toclist[it->first].insert(toclist[it->first].end(),
1045 it->second.begin(), it->second.end());
1049 void InsetInclude::updateCommand()
1054 docstring old_label = label_->getParam("name");
1055 label_->updateCommand(old_label, false);
1056 // the label might have been adapted (duplicate)
1057 docstring new_label = label_->getParam("name");
1058 if (old_label == new_label)
1061 // update listings parameters...
1062 InsetCommandParams p(INCLUDE_CODE);
1064 InsetListingsParams par(to_utf8(params()["lstparams"]));
1065 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1066 p["lstparams"] = from_utf8(par.params());
1070 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1072 Buffer const * const childbuffer = getChildBuffer();
1074 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1077 if (!isListings(params()))
1081 label_->updateBuffer(it, utype);
1083 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1084 if (par.getParamValue("caption").empty()) {
1085 listings_label_ = buffer().B_("Program Listing");
1088 Buffer const & master = *buffer().masterBuffer();
1089 Counters & counters = master.params().documentClass().counters();
1090 docstring const cnt = from_ascii("listing");
1091 listings_label_ = master.B_("Program Listing");
1092 if (counters.hasCounter(cnt)) {
1093 counters.step(cnt, utype);
1094 listings_label_ += " " + convert<docstring>(counters.value(cnt));