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_xhtml.h"
38 #include "OutputParams.h"
39 #include "TextClass.h"
40 #include "TocBackend.h"
42 #include "frontends/alert.h"
43 #include "frontends/Painter.h"
45 #include "graphics/PreviewImage.h"
46 #include "graphics/PreviewLoader.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetListingsParams.h"
50 #include "insets/RenderPreview.h"
52 #include "mathed/MacroTable.h"
54 #include "support/convert.h"
55 #include "support/debug.h"
56 #include "support/docstream.h"
57 #include "support/FileNameList.h"
58 #include "support/filetools.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/lstrings.h" // contains
62 #include "support/lyxalgo.h"
64 #include "support/bind.h"
67 using namespace lyx::support;
71 namespace Alert = frontend::Alert;
76 docstring const uniqueID()
78 static unsigned int seed = 1000;
79 return "file" + convert<docstring>(++seed);
83 /// the type of inclusion
85 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
89 Types type(string const & s)
93 if (s == "verbatiminput")
95 if (s == "verbatiminput*")
97 if (s == "lstinputlisting")
105 Types type(InsetCommandParams const & params)
107 return type(params.getCmdName());
111 bool isListings(InsetCommandParams const & params)
113 return type(params) == LISTINGS;
117 bool isVerbatim(InsetCommandParams const & params)
119 Types const t = type(params);
120 return t == VERB || t == VERBAST;
124 bool isInputOrInclude(InsetCommandParams const & params)
126 Types const t = type(params);
127 return t == INPUT || t == INCLUDE;
131 FileName const masterFileName(Buffer const & buffer)
133 return buffer.masterBuffer()->fileName();
137 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
140 string const parentFileName(Buffer const & buffer)
142 return buffer.absFileName();
146 FileName const includedFileName(Buffer const & buffer,
147 InsetCommandParams const & params)
149 return makeAbsPath(to_utf8(params["filename"]),
150 onlyPath(parentFileName(buffer)));
154 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
156 if (label_str.empty())
158 InsetCommandParams icp(LABEL_CODE);
159 icp["name"] = label_str;
160 return new InsetLabel(buf, icp);
166 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
167 : InsetCommand(buf, p), include_label(uniqueID()),
168 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
169 set_label_(false), label_(0), child_buffer_(0)
171 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
173 if (isListings(params())) {
174 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
175 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
176 } else if (isInputOrInclude(params()) && buf)
181 InsetInclude::InsetInclude(InsetInclude const & other)
182 : InsetCommand(other), include_label(other.include_label),
183 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
184 set_label_(false), label_(0), child_buffer_(0)
186 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
189 label_ = new InsetLabel(*other.label_);
193 InsetInclude::~InsetInclude()
195 if (isBufferLoaded())
196 buffer().invalidateBibfileCache();
201 void InsetInclude::setBuffer(Buffer & buffer)
203 InsetCommand::setBuffer(buffer);
205 label_->setBuffer(buffer);
209 void InsetInclude::setChildBuffer(Buffer * buffer)
211 child_buffer_ = buffer;
215 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
218 // This is only correct for the case of listings, but it'll do for now.
219 // In the other cases, this second parameter should just be empty.
220 static ParamInfo param_info_;
221 if (param_info_.empty()) {
222 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
223 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
229 bool InsetInclude::isCompatibleCommand(string const & s)
231 return type(s) != NONE;
235 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
237 switch (cmd.action()) {
239 case LFUN_INSET_EDIT: {
240 editIncluded(to_utf8(params()["filename"]));
244 case LFUN_INSET_MODIFY: {
245 // It should be OK just to invalidate the cache in setParams()
247 // child_buffer_ = 0;
248 InsetCommandParams p(INCLUDE_CODE);
249 if (cmd.getArg(0) == "changetype") {
251 InsetCommand::doDispatch(cur, cmd);
254 InsetCommand::string2params(to_utf8(cmd.argument()), p);
255 if (!p.getCmdName().empty()) {
257 InsetListingsParams new_params(to_utf8(p["lstparams"]));
258 docstring const new_label =
259 from_utf8(new_params.getParamValue("label"));
261 if (new_label.empty()) {
267 old_label = label_->getParam("name");
269 label_ = createLabel(buffer_, new_label);
270 label_->setBuffer(buffer());
273 if (new_label != old_label) {
274 label_->updateLabelAndRefs(new_label, &cur);
275 // the label might have been adapted (duplicate)
276 if (new_label != label_->getParam("name")) {
277 new_params.addParam("label", "{" +
278 to_utf8(label_->getParam("name")) + "}", true);
279 p["lstparams"] = from_utf8(new_params.params());
286 cur.forceBufferUpdate();
288 cur.noScreenUpdate();
292 //pass everything else up the chain
294 InsetCommand::doDispatch(cur, cmd);
300 void InsetInclude::editIncluded(string const & file)
302 string const ext = support::getExtension(file);
304 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
307 // tex file or other text file in verbatim mode
308 formats.edit(buffer(),
309 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
314 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
315 FuncStatus & flag) const
317 switch (cmd.action()) {
319 case LFUN_INSET_EDIT:
320 flag.setEnabled(true);
323 case LFUN_INSET_MODIFY:
324 if (cmd.getArg(0) == "changetype")
325 return InsetCommand::getStatus(cur, cmd, flag);
327 flag.setEnabled(true);
331 return InsetCommand::getStatus(cur, cmd, flag);
336 void InsetInclude::setParams(InsetCommandParams const & p)
338 // invalidate the cache
341 InsetCommand::setParams(p);
344 if (preview_->monitoring())
345 preview_->stopMonitoring();
347 if (type(params()) == INPUT)
348 add_preview(*preview_, *this, buffer());
350 buffer().invalidateBibfileCache();
354 bool InsetInclude::isChildIncluded() const
356 std::list<std::string> includeonlys =
357 buffer().params().getIncludedChildren();
358 if (includeonlys.empty())
360 return (std::find(includeonlys.begin(),
362 to_utf8(params()["filename"])) != includeonlys.end());
366 docstring InsetInclude::screenLabel() const
370 switch (type(params())) {
372 temp = buffer().B_("Input");
375 temp = buffer().B_("Verbatim Input");
378 temp = buffer().B_("Verbatim Input*");
381 if (isChildIncluded())
382 temp = buffer().B_("Include");
384 temp += buffer().B_("Include (excluded)");
387 temp = listings_label_;
390 LASSERT(false, /**/);
395 if (params()["filename"].empty())
398 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
404 Buffer * InsetInclude::getChildBuffer() const
406 Buffer * childBuffer = loadIfNeeded();
408 // FIXME: recursive includes
409 return (childBuffer == &buffer()) ? 0 : childBuffer;
413 Buffer * InsetInclude::loadIfNeeded() const
415 // This is for background export and preview. We don't even want to
416 // try to load the cloned child document again.
417 if (buffer().isClone())
418 return child_buffer_;
420 // Don't try to load it again if we failed before.
421 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
424 FileName const included_file = includedFileName(buffer(), params());
425 // Use cached Buffer if possible.
426 if (child_buffer_ != 0) {
427 if (theBufferList().isLoaded(child_buffer_)
428 // additional sanity check: make sure the Buffer really is
429 // associated with the file we want.
430 && child_buffer_ == theBufferList().getBuffer(included_file))
431 return child_buffer_;
432 // Buffer vanished, so invalidate cache and try to reload.
436 if (!isLyXFileName(included_file.absFileName()))
439 Buffer * child = theBufferList().getBuffer(included_file);
441 // the readonly flag can/will be wrong, not anymore I think.
442 if (!included_file.exists())
445 child = theBufferList().newBuffer(included_file.absFileName());
447 // Buffer creation is not possible.
450 // Set parent before loading, such that macros can be tracked
451 child->setParent(&buffer());
453 if (child->loadLyXFile() != Buffer::ReadSuccess) {
454 failedtoload_ = true;
456 //close the buffer we just opened
457 theBufferList().release(child);
461 if (!child->errorList("Parse").empty()) {
462 // FIXME: Do something.
465 // The file was already loaded, so, simply
466 // inform parent buffer about local macros.
467 Buffer const * parent = &buffer();
468 child->setParent(parent);
470 child->listMacroNames(macros);
471 MacroNameSet::const_iterator cit = macros.begin();
472 MacroNameSet::const_iterator end = macros.end();
473 for (; cit != end; ++cit)
474 parent->usermacros.insert(*cit);
477 // Cache the child buffer.
478 child_buffer_ = child;
483 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
485 string incfile = to_utf8(params()["filename"]);
487 // Do nothing if no file name has been specified
491 FileName const included_file = includedFileName(buffer(), params());
493 // Check we're not trying to include ourselves.
494 // FIXME RECURSIVE INCLUDE
495 // This isn't sufficient, as the inclusion could be downstream.
496 // But it'll have to do for now.
497 if (isInputOrInclude(params()) &&
498 buffer().absFileName() == included_file.absFileName())
500 Alert::error(_("Recursive input"),
501 bformat(_("Attempted to include file %1$s in itself! "
502 "Ignoring inclusion."), from_utf8(incfile)));
506 Buffer const * const masterBuffer = buffer().masterBuffer();
508 // if incfile is relative, make it relative to the master
510 if (!FileName::isAbsolute(incfile)) {
512 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
513 from_utf8(masterBuffer->filePath())));
516 // write it to a file (so far the complete file)
520 if (type(params()) == LISTINGS) {
521 exportfile = incfile;
522 mangled = DocFileName(included_file).mangledFileName();
524 exportfile = changeExtension(incfile, ".tex");
525 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
529 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
533 else if (!isValidLaTeXFileName(incfile)) {
534 frontend::Alert::warning(_("Invalid filename"),
535 _("The following filename will cause troubles "
536 "when running the exported file through LaTeX: ") +
539 else if (!isValidDVIFileName(incfile)) {
540 frontend::Alert::warning(_("Problematic filename for DVI"),
541 _("The following filename can cause troubles "
542 "when running the exported file through LaTeX "
543 "and opening the resulting DVI: ") +
544 from_utf8(incfile), true);
546 LYXERR(Debug::LATEX, "incfile:" << incfile);
547 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
548 LYXERR(Debug::LATEX, "writefile:" << writefile);
550 string const tex_format = flavor2format(runparams.flavor);
551 if (runparams.inComment || runparams.dryrun) {
552 //Don't try to load or copy the file if we're
553 //in a comment or doing a dryrun
554 } else if (isInputOrInclude(params()) &&
555 isLyXFileName(included_file.absFileName())) {
556 // if it's a LyX file and we're inputting or including,
557 // try to load it so we can write the associated latex
559 Buffer * tmp = loadIfNeeded();
561 docstring text = bformat(_("Could not load included "
563 "Please, check whether it actually exists."),
564 included_file.displayName());
565 Alert::warning(_("Missing included file"), text);
569 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
571 docstring text = bformat(_("Included file `%1$s'\n"
572 "has textclass `%2$s'\n"
573 "while parent file has textclass `%3$s'."),
574 included_file.displayName(),
575 from_utf8(tmp->params().documentClass().name()),
576 from_utf8(masterBuffer->params().documentClass().name()));
577 Alert::warning(_("Different textclasses"), text, true);
580 // Make sure modules used in child are all included in master
581 // FIXME It might be worth loading the children's modules into the master
582 // over in BufferParams rather than doing this check.
583 LayoutModuleList const masterModules = masterBuffer->params().getModules();
584 LayoutModuleList const childModules = tmp->params().getModules();
585 LayoutModuleList::const_iterator it = childModules.begin();
586 LayoutModuleList::const_iterator end = childModules.end();
587 for (; it != end; ++it) {
588 string const module = *it;
589 LayoutModuleList::const_iterator found =
590 find(masterModules.begin(), masterModules.end(), module);
591 if (found == masterModules.end()) {
592 docstring text = bformat(_("Included file `%1$s'\n"
593 "uses module `%2$s'\n"
594 "which is not used in parent file."),
595 included_file.displayName(), from_utf8(module));
596 Alert::warning(_("Module not found"), text);
600 tmp->markDepClean(masterBuffer->temppath());
602 // Don't assume the child's format is latex
603 string const inc_format = tmp->params().bufferFormat();
604 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
605 formats.extension(inc_format)));
607 // FIXME: handle non existing files
608 // FIXME: Second argument is irrelevant!
609 // since only_body is true, makeLaTeXFile will not look at second
610 // argument. Should we set it to string(), or should makeLaTeXFile
611 // make use of it somehow? (JMarc 20031002)
612 // The included file might be written in a different encoding
614 Encoding const * const oldEnc = runparams.encoding;
615 Language const * const oldLang = runparams.master_language;
616 // If the master has full unicode flavor (XeTeX, LuaTeX),
617 // the children must be encoded in plain utf8!
618 runparams.encoding = runparams.isFullUnicode() ?
619 encodings.fromLyXName("utf8-plain")
620 : &tmp->params().encoding();
621 runparams.master_language = buffer().params().language;
622 runparams.par_begin = 0;
623 runparams.par_end = tmp->paragraphs().size();
624 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
625 onlyPath().absFileName(), runparams, false)) {
626 docstring msg = bformat(_("Included file `%1$s' "
627 "was not exported correctly.\nWarning: "
628 "LaTeX export is probably incomplete."),
629 included_file.displayName());
630 ErrorList const & el = tmp->errorList("Export");
632 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
633 msg, el.begin()->error,
634 el.begin()->description);
635 Alert::warning(_("Export failure"), msg);
637 runparams.encoding = oldEnc;
638 runparams.master_language = oldLang;
640 // If needed, use converters to produce a latex file from the child
641 if (tmpwritefile != writefile) {
644 theConverters().convert(tmp, tmpwritefile, writefile,
646 inc_format, tex_format, el);
649 docstring msg = bformat(_("Included file `%1$s' "
650 "was not exported correctly.\nWarning: "
651 "LaTeX export is probably incomplete."),
652 included_file.displayName());
654 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
655 msg, el.begin()->error,
656 el.begin()->description);
657 Alert::warning(_("Export failure"), msg);
661 // In this case, it's not a LyX file, so we copy the file
662 // to the temp dir, so that .aux files etc. are not created
663 // in the original dir. Files included by this file will be
664 // found via input@path, see ../Buffer.cpp.
665 unsigned long const checksum_in = included_file.checksum();
666 unsigned long const checksum_out = writefile.checksum();
668 if (checksum_in != checksum_out) {
669 if (!included_file.copyTo(writefile)) {
672 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
673 "into the temporary directory."),
674 from_utf8(included_file.absFileName()))));
680 switch (type(params())) {
683 incfile = latex_path(incfile);
685 os << '\\' << from_ascii(params().getCmdName()) << '{'
686 << from_utf8(incfile) << '}';
690 runparams.exportdata->addExternalFile(tex_format, writefile,
693 // \input wants file with extension (default is .tex)
694 if (!isLyXFileName(included_file.absFileName())) {
695 incfile = latex_path(incfile);
697 os << '\\' << from_ascii(params().getCmdName())
698 << '{' << from_utf8(incfile) << '}';
700 incfile = changeExtension(incfile, ".tex");
701 incfile = latex_path(incfile);
703 os << '\\' << from_ascii(params().getCmdName())
704 << '{' << from_utf8(incfile) << '}';
709 os << '\\' << from_ascii(params().getCmdName());
710 string const opt = to_utf8(params()["lstparams"]);
711 // opt is set in QInclude dialog and should have passed validation.
712 InsetListingsParams params(opt);
713 if (!params.params().empty())
714 os << "[" << from_utf8(params.params()) << "]";
715 os << '{' << from_utf8(incfile) << '}';
719 runparams.exportdata->addExternalFile(tex_format, writefile,
722 // \include don't want extension and demands that the
723 // file really have .tex
724 incfile = changeExtension(incfile, string());
725 incfile = latex_path(incfile);
727 os << '\\' << from_ascii(params().getCmdName()) << '{'
728 << from_utf8(incfile) << '}';
737 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
742 // For verbatim and listings, we just include the contents of the file as-is.
743 // In the case of listings, we wrap it in <pre>.
744 bool const listing = isListings(params());
745 if (listing || isVerbatim(params())) {
747 xs << html::StartTag("pre");
748 // FIXME: We don't know the encoding of the file, default to UTF-8.
749 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
751 xs << html::EndTag("pre");
755 // We don't (yet) know how to Input or Include non-LyX files.
756 // (If we wanted to get really arcane, we could run some tex2html
757 // converter on the included file. But that's just masochistic.)
758 FileName const included_file = includedFileName(buffer(), params());
759 if (!isLyXFileName(included_file.absFileName())) {
760 frontend::Alert::warning(_("Unsupported Inclusion"),
761 bformat(_("LyX does not know how to include non-LyX files when "
762 "generating HTML output. Offending file:\n%1$s"),
763 params()["filename"]));
767 // In the other cases, we will generate the HTML and include it.
769 // Check we're not trying to include ourselves.
770 // FIXME RECURSIVE INCLUDE
771 if (buffer().absFileName() == included_file.absFileName()) {
772 Alert::error(_("Recursive input"),
773 bformat(_("Attempted to include file %1$s in itself! "
774 "Ignoring inclusion."), params()["filename"]));
778 Buffer const * const ibuf = loadIfNeeded();
782 // are we generating only some paragraphs, or all of them?
783 bool const all_pars = !rp.dryrun ||
784 (rp.par_begin == 0 &&
785 rp.par_end == (int)buffer().text().paragraphs().size());
787 OutputParams op = rp;
791 ibuf->writeLyXHTMLSource(xs.os(), op, true);
793 xs << XHTMLStream::ESCAPE_NONE
794 << "<!-- Included file: "
795 << from_utf8(included_file.absFileName())
796 << XHTMLStream::ESCAPE_NONE
802 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
804 if (isVerbatim(params()) || isListings(params())) {
805 os << '[' << screenLabel() << '\n';
806 // FIXME: We don't know the encoding of the file, default to UTF-8.
807 os << includedFileName(buffer(), params()).fileContents("UTF-8");
809 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
811 docstring const str = '[' + screenLabel() + ']';
818 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
820 string incfile = to_utf8(params()["filename"]);
822 // Do nothing if no file name has been specified
826 string const included_file = includedFileName(buffer(), params()).absFileName();
828 // Check we're not trying to include ourselves.
829 // FIXME RECURSIVE INCLUDE
830 // This isn't sufficient, as the inclusion could be downstream.
831 // But it'll have to do for now.
832 if (buffer().absFileName() == included_file) {
833 Alert::error(_("Recursive input"),
834 bformat(_("Attempted to include file %1$s in itself! "
835 "Ignoring inclusion."), from_utf8(incfile)));
839 // write it to a file (so far the complete file)
840 string const exportfile = changeExtension(incfile, ".sgml");
841 DocFileName writefile(changeExtension(included_file, ".sgml"));
843 Buffer * tmp = loadIfNeeded();
845 string const mangled = writefile.mangledFileName();
846 writefile = makeAbsPath(mangled,
847 buffer().masterBuffer()->temppath());
851 LYXERR(Debug::LATEX, "incfile:" << incfile);
852 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
853 LYXERR(Debug::LATEX, "writefile:" << writefile);
855 tmp->makeDocBookFile(writefile, runparams, true);
858 runparams.exportdata->addExternalFile("docbook", writefile,
860 runparams.exportdata->addExternalFile("docbook-xml", writefile,
863 if (isVerbatim(params()) || isListings(params())) {
864 os << "<inlinegraphic fileref=\""
865 << '&' << include_label << ';'
866 << "\" format=\"linespecific\">";
868 os << '&' << include_label << ';';
874 void InsetInclude::validate(LaTeXFeatures & features) const
876 string incfile = to_utf8(params()["filename"]);
879 LASSERT(&buffer() == &features.buffer(), /**/);
881 string const included_file =
882 includedFileName(buffer(), params()).absFileName();
884 if (isLyXFileName(included_file))
885 writefile = changeExtension(included_file, ".sgml");
887 writefile = included_file;
889 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
890 incfile = DocFileName(writefile).mangledFileName();
891 writefile = makeAbsPath(incfile,
892 buffer().masterBuffer()->temppath()).absFileName();
895 features.includeFile(include_label, writefile);
897 if (isVerbatim(params()))
898 features.require("verbatim");
899 else if (isListings(params()))
900 features.require("listings");
902 // Here we must do the fun stuff...
903 // Load the file in the include if it needs
905 Buffer * const tmp = loadIfNeeded();
907 // the file is loaded
908 // make sure the buffer isn't us
909 // FIXME RECURSIVE INCLUDES
910 // This is not sufficient, as recursive includes could be
911 // more than a file away. But it will do for now.
912 if (tmp && tmp != &buffer()) {
913 // We must temporarily change features.buffer,
914 // otherwise it would always be the master buffer,
915 // and nested includes would not work.
916 features.setBuffer(*tmp);
917 tmp->validate(features);
918 features.setBuffer(buffer());
924 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
926 Buffer * child = loadIfNeeded();
929 child->collectBibKeys();
933 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
935 LASSERT(mi.base.bv, /**/);
937 bool use_preview = false;
938 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
939 graphics::PreviewImage const * pimage =
940 preview_->getPreviewImage(mi.base.bv->buffer());
941 use_preview = pimage && pimage->image();
945 preview_->metrics(mi, dim);
949 button_.update(screenLabel(), true);
951 button_.metrics(mi, dim);
954 Box b(0, dim.wid, -dim.asc, dim.des);
959 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
961 LASSERT(pi.base.bv, /**/);
963 bool use_preview = false;
964 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
965 graphics::PreviewImage const * pimage =
966 preview_->getPreviewImage(pi.base.bv->buffer());
967 use_preview = pimage && pimage->image();
971 preview_->draw(pi, x, y);
973 button_.draw(pi, x, y);
977 docstring InsetInclude::contextMenuName() const
979 return from_ascii("context-include");
983 Inset::DisplayType InsetInclude::display() const
985 return type(params()) == INPUT ? Inline : AlignCenter;
994 void InsetInclude::fileChanged() const
996 Buffer const * const buffer = updateFrontend();
1000 preview_->removePreview(*buffer);
1001 add_preview(*preview_.get(), *this, *buffer);
1002 preview_->startLoading(*buffer);
1008 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1010 FileName const included_file = includedFileName(buffer, params);
1012 return type(params) == INPUT && params.preview() &&
1013 included_file.isReadableFile();
1017 docstring latexString(InsetInclude const & inset)
1020 odocstringstream ods;
1021 otexstream os(ods, texrow);
1022 // We don't need to set runparams.encoding since this will be done
1023 // by latex() anyway.
1024 OutputParams runparams(0);
1025 runparams.flavor = OutputParams::LATEX;
1026 inset.latex(os, runparams);
1032 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1033 Buffer const & buffer)
1035 InsetCommandParams const & params = inset.params();
1036 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
1037 preview_wanted(params, buffer)) {
1038 renderer.setAbsFile(includedFileName(buffer, params));
1039 docstring const snippet = latexString(inset);
1040 renderer.addPreview(snippet, buffer);
1047 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1048 graphics::PreviewLoader & ploader) const
1050 Buffer const & buffer = ploader.buffer();
1051 if (!preview_wanted(params(), buffer))
1053 preview_->setAbsFile(includedFileName(buffer, params()));
1054 docstring const snippet = latexString(*this);
1055 preview_->addPreview(snippet, ploader);
1059 void InsetInclude::addToToc(DocIterator const & cpit) const
1061 TocBackend & backend = buffer().tocBackend();
1063 if (isListings(params())) {
1065 label_->addToToc(cpit);
1067 InsetListingsParams p(to_utf8(params()["lstparams"]));
1068 string caption = p.getParamValue("caption");
1069 if (caption.empty())
1071 Toc & toc = backend.toc("listing");
1072 docstring str = convert<docstring>(toc.size() + 1)
1073 + ". " + from_utf8(caption);
1074 DocIterator pit = cpit;
1075 toc.push_back(TocItem(pit, 0, str));
1078 Buffer const * const childbuffer = getChildBuffer();
1082 Toc & toc = backend.toc("child");
1083 docstring str = childbuffer->fileName().displayName();
1084 toc.push_back(TocItem(cpit, 0, str));
1086 TocList & toclist = backend.tocs();
1087 childbuffer->tocBackend().update();
1088 TocList const & childtoclist = childbuffer->tocBackend().tocs();
1089 TocList::const_iterator it = childtoclist.begin();
1090 TocList::const_iterator const end = childtoclist.end();
1091 for(; it != end; ++it)
1092 toclist[it->first].insert(toclist[it->first].end(),
1093 it->second.begin(), it->second.end());
1097 void InsetInclude::updateCommand()
1102 docstring old_label = label_->getParam("name");
1103 label_->updateLabel(old_label);
1104 // the label might have been adapted (duplicate)
1105 docstring new_label = label_->getParam("name");
1106 if (old_label == new_label)
1109 // update listings parameters...
1110 InsetCommandParams p(INCLUDE_CODE);
1112 InsetListingsParams par(to_utf8(params()["lstparams"]));
1113 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1114 p["lstparams"] = from_utf8(par.params());
1119 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1121 Buffer const * const childbuffer = getChildBuffer();
1123 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1126 if (!isListings(params()))
1130 label_->updateBuffer(it, utype);
1132 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1133 if (par.getParamValue("caption").empty()) {
1134 listings_label_ = buffer().B_("Program Listing");
1137 Buffer const & master = *buffer().masterBuffer();
1138 Counters & counters = master.params().documentClass().counters();
1139 docstring const cnt = from_ascii("listing");
1140 listings_label_ = master.B_("Program Listing");
1141 if (counters.hasCounter(cnt)) {
1142 counters.step(cnt, utype);
1143 listings_label_ += " " + convert<docstring>(counters.value(cnt));