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, temp = buffer().B_("Unknown"));
397 if (params()["filename"].empty())
400 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
406 Buffer * InsetInclude::getChildBuffer() const
408 Buffer * childBuffer = loadIfNeeded();
410 // FIXME: recursive includes
411 return (childBuffer == &buffer()) ? 0 : childBuffer;
415 Buffer * InsetInclude::loadIfNeeded() const
417 // This is for background export and preview. We don't even want to
418 // try to load the cloned child document again.
419 if (buffer().isClone())
420 return child_buffer_;
422 // Don't try to load it again if we failed before.
423 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
426 FileName const included_file = includedFileName(buffer(), params());
427 // Use cached Buffer if possible.
428 if (child_buffer_ != 0) {
429 if (theBufferList().isLoaded(child_buffer_)
430 // additional sanity check: make sure the Buffer really is
431 // associated with the file we want.
432 && child_buffer_ == theBufferList().getBuffer(included_file))
433 return child_buffer_;
434 // Buffer vanished, so invalidate cache and try to reload.
438 if (!isLyXFileName(included_file.absFileName()))
441 Buffer * child = theBufferList().getBuffer(included_file);
443 // the readonly flag can/will be wrong, not anymore I think.
444 if (!included_file.exists())
447 child = theBufferList().newBuffer(included_file.absFileName());
449 // Buffer creation is not possible.
452 // Set parent before loading, such that macros can be tracked
453 child->setParent(&buffer());
455 if (child->loadLyXFile() != Buffer::ReadSuccess) {
456 failedtoload_ = true;
458 //close the buffer we just opened
459 theBufferList().release(child);
463 if (!child->errorList("Parse").empty()) {
464 // FIXME: Do something.
467 // The file was already loaded, so, simply
468 // inform parent buffer about local macros.
469 Buffer const * parent = &buffer();
470 child->setParent(parent);
472 child->listMacroNames(macros);
473 MacroNameSet::const_iterator cit = macros.begin();
474 MacroNameSet::const_iterator end = macros.end();
475 for (; cit != end; ++cit)
476 parent->usermacros.insert(*cit);
479 // Cache the child buffer.
480 child_buffer_ = child;
485 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
487 string incfile = to_utf8(params()["filename"]);
489 // Do nothing if no file name has been specified
493 FileName const included_file = includedFileName(buffer(), params());
495 // Check we're not trying to include ourselves.
496 // FIXME RECURSIVE INCLUDE
497 // This isn't sufficient, as the inclusion could be downstream.
498 // But it'll have to do for now.
499 if (isInputOrInclude(params()) &&
500 buffer().absFileName() == included_file.absFileName())
502 Alert::error(_("Recursive input"),
503 bformat(_("Attempted to include file %1$s in itself! "
504 "Ignoring inclusion."), from_utf8(incfile)));
508 Buffer const * const masterBuffer = buffer().masterBuffer();
510 // if incfile is relative, make it relative to the master
512 if (!FileName::isAbsolute(incfile)) {
514 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
515 from_utf8(masterBuffer->filePath())));
518 string exppath = incfile;
519 if (!runparams.export_folder.empty()) {
520 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
521 FileName(exppath).onlyPath().createPath();
524 // write it to a file (so far the complete file)
528 if (type(params()) == LISTINGS) {
529 exportfile = exppath;
530 mangled = DocFileName(included_file).mangledFileName();
532 exportfile = changeExtension(exppath, ".tex");
533 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
539 else if (!runparams.silent)
540 ; // no warning wanted
541 else if (!isValidLaTeXFileName(incfile)) {
542 frontend::Alert::warning(_("Invalid filename"),
543 _("The following filename will cause troubles "
544 "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);
554 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
556 LYXERR(Debug::LATEX, "incfile:" << incfile);
557 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
558 LYXERR(Debug::LATEX, "writefile:" << writefile);
560 string const tex_format = flavor2format(runparams.flavor);
562 switch (type(params())) {
565 incfile = latex_path(incfile);
567 os << '\\' << from_ascii(params().getCmdName()) << '{'
568 << from_utf8(incfile) << '}';
572 runparams.exportdata->addExternalFile(tex_format, writefile,
575 // \input wants file with extension (default is .tex)
576 if (!isLyXFileName(included_file.absFileName())) {
577 incfile = latex_path(incfile);
579 os << '\\' << from_ascii(params().getCmdName())
580 << '{' << from_utf8(incfile) << '}';
582 incfile = changeExtension(incfile, ".tex");
583 incfile = latex_path(incfile);
585 os << '\\' << from_ascii(params().getCmdName())
586 << '{' << from_utf8(incfile) << '}';
591 runparams.exportdata->addExternalFile(tex_format, writefile,
593 os << '\\' << from_ascii(params().getCmdName());
594 string const opt = to_utf8(params()["lstparams"]);
595 // opt is set in QInclude dialog and should have passed validation.
596 InsetListingsParams params(opt);
597 if (!params.params().empty())
598 os << "[" << from_utf8(params.params()) << "]";
599 os << '{' << from_utf8(incfile) << '}';
603 runparams.exportdata->addExternalFile(tex_format, writefile,
606 // \include don't want extension and demands that the
607 // file really have .tex
608 incfile = changeExtension(incfile, string());
609 incfile = latex_path(incfile);
611 os << '\\' << from_ascii(params().getCmdName()) << '{'
612 << from_utf8(incfile) << '}';
619 if (runparams.inComment || runparams.dryrun)
620 // Don't try to load or copy the file if we're
621 // in a comment or doing a dryrun
624 if (isInputOrInclude(params()) &&
625 isLyXFileName(included_file.absFileName())) {
626 // if it's a LyX file and we're inputting or including,
627 // try to load it so we can write the associated latex
629 Buffer * tmp = loadIfNeeded();
631 if (!runparams.silent) {
632 docstring text = bformat(_("Could not load included "
634 "Please, check whether it actually exists."),
635 included_file.displayName());
636 Alert::warning(_("Missing included file"), text);
641 if (!runparams.silent) {
642 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
644 docstring text = bformat(_("Included file `%1$s'\n"
645 "has textclass `%2$s'\n"
646 "while parent file has textclass `%3$s'."),
647 included_file.displayName(),
648 from_utf8(tmp->params().documentClass().name()),
649 from_utf8(masterBuffer->params().documentClass().name()));
650 Alert::warning(_("Different textclasses"), text, true);
653 // Make sure modules used in child are all included in master
654 // FIXME It might be worth loading the children's modules into the master
655 // over in BufferParams rather than doing this check.
656 LayoutModuleList const masterModules = masterBuffer->params().getModules();
657 LayoutModuleList const childModules = tmp->params().getModules();
658 LayoutModuleList::const_iterator it = childModules.begin();
659 LayoutModuleList::const_iterator end = childModules.end();
660 for (; it != end; ++it) {
661 string const module = *it;
662 LayoutModuleList::const_iterator found =
663 find(masterModules.begin(), masterModules.end(), module);
664 if (found == masterModules.end()) {
665 docstring text = bformat(_("Included file `%1$s'\n"
666 "uses module `%2$s'\n"
667 "which is not used in parent file."),
668 included_file.displayName(), from_utf8(module));
669 Alert::warning(_("Module not found"), text);
674 tmp->markDepClean(masterBuffer->temppath());
676 // Don't assume the child's format is latex
677 string const inc_format = tmp->params().bufferFormat();
678 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
679 formats.extension(inc_format)));
681 // FIXME: handle non existing files
682 // The included file might be written in a different encoding
684 Encoding const * const oldEnc = runparams.encoding;
685 Language const * const oldLang = runparams.master_language;
686 // If the master has full unicode flavor (XeTeX, LuaTeX),
687 // the children must be encoded in plain utf8!
688 runparams.encoding = runparams.isFullUnicode() ?
689 encodings.fromLyXName("utf8-plain")
690 : &tmp->params().encoding();
691 runparams.master_language = buffer().params().language;
692 runparams.par_begin = 0;
693 runparams.par_end = tmp->paragraphs().size();
694 runparams.is_child = true;
695 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
696 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
697 if (!runparams.silent) {
698 docstring msg = bformat(_("Included file `%1$s' "
699 "was not exported correctly.\nWarning: "
700 "LaTeX export is probably incomplete."),
701 included_file.displayName());
702 ErrorList const & el = tmp->errorList("Export");
704 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
705 msg, el.begin()->error,
706 el.begin()->description);
707 Alert::warning(_("Export failure"), msg);
710 runparams.encoding = oldEnc;
711 runparams.master_language = oldLang;
712 runparams.is_child = false;
714 // If needed, use converters to produce a latex file from the child
715 if (tmpwritefile != writefile) {
718 theConverters().convert(tmp, tmpwritefile, writefile,
720 inc_format, tex_format, el);
722 if (!success && !runparams.silent) {
723 docstring msg = bformat(_("Included file `%1$s' "
724 "was not exported correctly.\nWarning: "
725 "LaTeX export is probably incomplete."),
726 included_file.displayName());
728 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
729 msg, el.begin()->error,
730 el.begin()->description);
731 Alert::warning(_("Export failure"), msg);
735 // In this case, it's not a LyX file, so we copy the file
736 // to the temp dir, so that .aux files etc. are not created
737 // in the original dir. Files included by this file will be
738 // found via either the environment variable TEXINPUTS, or
739 // input@path, see ../Buffer.cpp.
740 unsigned long const checksum_in = included_file.checksum();
741 unsigned long const checksum_out = writefile.checksum();
743 if (checksum_in != checksum_out) {
744 if (!included_file.copyTo(writefile)) {
747 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
748 "into the temporary directory."),
749 from_utf8(included_file.absFileName()))));
757 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
762 // For verbatim and listings, we just include the contents of the file as-is.
763 // In the case of listings, we wrap it in <pre>.
764 bool const listing = isListings(params());
765 if (listing || isVerbatim(params())) {
767 xs << html::StartTag("pre");
768 // FIXME: We don't know the encoding of the file, default to UTF-8.
769 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
771 xs << html::EndTag("pre");
775 // We don't (yet) know how to Input or Include non-LyX files.
776 // (If we wanted to get really arcane, we could run some tex2html
777 // converter on the included file. But that's just masochistic.)
778 FileName const included_file = includedFileName(buffer(), params());
779 if (!isLyXFileName(included_file.absFileName())) {
781 frontend::Alert::warning(_("Unsupported Inclusion"),
782 bformat(_("LyX does not know how to include non-LyX files when "
783 "generating HTML output. Offending file:\n%1$s"),
784 params()["filename"]));
788 // In the other cases, we will generate the HTML and include it.
790 // Check we're not trying to include ourselves.
791 // FIXME RECURSIVE INCLUDE
792 if (buffer().absFileName() == included_file.absFileName()) {
793 Alert::error(_("Recursive input"),
794 bformat(_("Attempted to include file %1$s in itself! "
795 "Ignoring inclusion."), params()["filename"]));
799 Buffer const * const ibuf = loadIfNeeded();
803 // are we generating only some paragraphs, or all of them?
804 bool const all_pars = !rp.dryrun ||
805 (rp.par_begin == 0 &&
806 rp.par_end == (int)buffer().text().paragraphs().size());
808 OutputParams op = rp;
812 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
814 xs << XHTMLStream::ESCAPE_NONE
815 << "<!-- Included file: "
816 << from_utf8(included_file.absFileName())
817 << XHTMLStream::ESCAPE_NONE
823 int InsetInclude::plaintext(odocstringstream & os,
824 OutputParams const & op, size_t) const
826 // just write the filename if we're making a tooltip or toc entry,
827 // or are generating this for advanced search
828 if (op.for_tooltip || op.for_toc || op.for_search) {
829 os << '[' << screenLabel() << '\n'
830 << getParam("filename") << "\n]";
831 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
834 if (isVerbatim(params()) || isListings(params())) {
835 os << '[' << screenLabel() << '\n'
836 // FIXME: We don't know the encoding of the file, default to UTF-8.
837 << includedFileName(buffer(), params()).fileContents("UTF-8")
839 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
842 Buffer const * const ibuf = loadIfNeeded();
844 docstring const str = '[' + screenLabel() + ']';
848 writePlaintextFile(*ibuf, os, op);
853 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
855 string incfile = to_utf8(params()["filename"]);
857 // Do nothing if no file name has been specified
861 string const included_file = includedFileName(buffer(), params()).absFileName();
863 // Check we're not trying to include ourselves.
864 // FIXME RECURSIVE INCLUDE
865 // This isn't sufficient, as the inclusion could be downstream.
866 // But it'll have to do for now.
867 if (buffer().absFileName() == included_file) {
868 Alert::error(_("Recursive input"),
869 bformat(_("Attempted to include file %1$s in itself! "
870 "Ignoring inclusion."), from_utf8(incfile)));
874 string exppath = incfile;
875 if (!runparams.export_folder.empty()) {
876 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
877 FileName(exppath).onlyPath().createPath();
880 // write it to a file (so far the complete file)
881 string const exportfile = changeExtension(exppath, ".sgml");
882 DocFileName writefile(changeExtension(included_file, ".sgml"));
884 Buffer * tmp = loadIfNeeded();
886 string const mangled = writefile.mangledFileName();
887 writefile = makeAbsPath(mangled,
888 buffer().masterBuffer()->temppath());
892 LYXERR(Debug::LATEX, "incfile:" << incfile);
893 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
894 LYXERR(Debug::LATEX, "writefile:" << writefile);
896 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
899 runparams.exportdata->addExternalFile("docbook", writefile,
901 runparams.exportdata->addExternalFile("docbook-xml", writefile,
904 if (isVerbatim(params()) || isListings(params())) {
905 os << "<inlinegraphic fileref=\""
906 << '&' << include_label << ';'
907 << "\" format=\"linespecific\">";
909 os << '&' << include_label << ';';
915 void InsetInclude::validate(LaTeXFeatures & features) const
917 LATTEST(&buffer() == &features.buffer());
919 string incfile = to_utf8(params()["filename"]);
920 string const included_file =
921 includedFileName(buffer(), params()).absFileName();
924 if (isLyXFileName(included_file))
925 writefile = changeExtension(included_file, ".sgml");
927 writefile = included_file;
929 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
930 incfile = DocFileName(writefile).mangledFileName();
931 writefile = makeAbsPath(incfile,
932 buffer().masterBuffer()->temppath()).absFileName();
935 features.includeFile(include_label, writefile);
937 features.useInsetLayout(getLayout());
938 if (isVerbatim(params()))
939 features.require("verbatim");
940 else if (isListings(params()))
941 features.require("listings");
943 // Here we must do the fun stuff...
944 // Load the file in the include if it needs
946 Buffer * const tmp = loadIfNeeded();
948 // the file is loaded
949 // make sure the buffer isn't us
950 // FIXME RECURSIVE INCLUDES
951 // This is not sufficient, as recursive includes could be
952 // more than a file away. But it will do for now.
953 if (tmp && tmp != &buffer()) {
954 // We must temporarily change features.buffer,
955 // otherwise it would always be the master buffer,
956 // and nested includes would not work.
957 features.setBuffer(*tmp);
958 // Maybe this is already a child
959 bool const is_child =
960 features.runparams().is_child;
961 features.runparams().is_child = true;
962 tmp->validate(features);
963 features.runparams().is_child = is_child;
964 features.setBuffer(buffer());
970 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
972 Buffer * child = loadIfNeeded();
975 child->collectBibKeys();
979 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
983 bool use_preview = false;
984 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
985 graphics::PreviewImage const * pimage =
986 preview_->getPreviewImage(mi.base.bv->buffer());
987 use_preview = pimage && pimage->image();
991 preview_->metrics(mi, dim);
995 button_.update(screenLabel(), true);
997 button_.metrics(mi, dim);
1000 Box b(0, dim.wid, -dim.asc, dim.des);
1005 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1007 LBUFERR(pi.base.bv);
1009 bool use_preview = false;
1010 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
1011 graphics::PreviewImage const * pimage =
1012 preview_->getPreviewImage(pi.base.bv->buffer());
1013 use_preview = pimage && pimage->image();
1017 preview_->draw(pi, x, y);
1019 button_.draw(pi, x, y);
1023 string InsetInclude::contextMenuName() const
1025 return "context-include";
1029 Inset::DisplayType InsetInclude::display() const
1031 return type(params()) == INPUT ? Inline : AlignCenter;
1035 docstring InsetInclude::layoutName() const
1037 if (isListings(params()))
1038 return from_ascii("IncludeListings");
1039 return InsetCommand::layoutName();
1047 void InsetInclude::fileChanged() const
1049 Buffer const * const buffer = updateFrontend();
1053 preview_->removePreview(*buffer);
1054 add_preview(*preview_.get(), *this, *buffer);
1055 preview_->startLoading(*buffer);
1061 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1063 FileName const included_file = includedFileName(buffer, params);
1065 return type(params) == INPUT && params.preview() &&
1066 included_file.isReadableFile();
1070 docstring latexString(InsetInclude const & inset)
1073 odocstringstream ods;
1074 otexstream os(ods, texrow);
1075 // We don't need to set runparams.encoding since this will be done
1076 // by latex() anyway.
1077 OutputParams runparams(0);
1078 runparams.flavor = OutputParams::LATEX;
1079 inset.latex(os, runparams);
1085 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1086 Buffer const & buffer)
1088 InsetCommandParams const & params = inset.params();
1089 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
1090 preview_wanted(params, buffer)) {
1091 renderer.setAbsFile(includedFileName(buffer, params));
1092 docstring const snippet = latexString(inset);
1093 renderer.addPreview(snippet, buffer);
1100 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1101 graphics::PreviewLoader & ploader) const
1103 Buffer const & buffer = ploader.buffer();
1104 if (!preview_wanted(params(), buffer))
1106 preview_->setAbsFile(includedFileName(buffer, params()));
1107 docstring const snippet = latexString(*this);
1108 preview_->addPreview(snippet, ploader);
1112 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active) const
1114 TocBackend & backend = buffer().tocBackend();
1116 if (isListings(params())) {
1118 label_->addToToc(cpit, output_active);
1120 InsetListingsParams p(to_utf8(params()["lstparams"]));
1121 string caption = p.getParamValue("caption");
1122 if (caption.empty())
1124 Toc & toc = backend.toc("listing");
1125 docstring str = convert<docstring>(toc.size() + 1)
1126 + ". " + from_utf8(caption);
1127 DocIterator pit = cpit;
1128 toc.push_back(TocItem(pit, 0, str, output_active));
1131 Buffer const * const childbuffer = getChildBuffer();
1135 Toc & toc = backend.toc("child");
1136 docstring str = childbuffer->fileName().displayName();
1137 toc.push_back(TocItem(cpit, 0, str, output_active));
1139 TocList & toclist = backend.tocs();
1140 childbuffer->tocBackend().update(output_active);
1141 TocList const & childtoclist = childbuffer->tocBackend().tocs();
1142 TocList::const_iterator it = childtoclist.begin();
1143 TocList::const_iterator const end = childtoclist.end();
1144 for(; it != end; ++it)
1145 toclist[it->first].insert(toclist[it->first].end(),
1146 it->second.begin(), it->second.end());
1150 void InsetInclude::updateCommand()
1155 docstring old_label = label_->getParam("name");
1156 label_->updateLabel(old_label);
1157 // the label might have been adapted (duplicate)
1158 docstring new_label = label_->getParam("name");
1159 if (old_label == new_label)
1162 // update listings parameters...
1163 InsetCommandParams p(INCLUDE_CODE);
1165 InsetListingsParams par(to_utf8(params()["lstparams"]));
1166 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1167 p["lstparams"] = from_utf8(par.params());
1172 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1174 button_.update(screenLabel(), true);
1176 Buffer const * const childbuffer = getChildBuffer();
1178 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1181 if (!isListings(params()))
1185 label_->updateBuffer(it, utype);
1187 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1188 if (par.getParamValue("caption").empty()) {
1189 listings_label_ = buffer().B_("Program Listing");
1192 Buffer const & master = *buffer().masterBuffer();
1193 Counters & counters = master.params().documentClass().counters();
1194 docstring const cnt = from_ascii("listing");
1195 listings_label_ = master.B_("Program Listing");
1196 if (counters.hasCounter(cnt)) {
1197 counters.step(cnt, utype);
1198 listings_label_ += " " + convert<docstring>(counters.value(cnt));