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()
80 static unsigned int seed = 1000;
81 return "file" + convert<docstring>(++seed);
85 /// the type of inclusion
87 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
91 Types type(string const & s)
95 if (s == "verbatiminput")
97 if (s == "verbatiminput*")
99 if (s == "lstinputlisting")
107 Types type(InsetCommandParams const & params)
109 return type(params.getCmdName());
113 bool isListings(InsetCommandParams const & params)
115 return type(params) == LISTINGS;
119 bool isVerbatim(InsetCommandParams const & params)
121 Types const t = type(params);
122 return t == VERB || t == VERBAST;
126 bool isInputOrInclude(InsetCommandParams const & params)
128 Types const t = type(params);
129 return t == INPUT || t == INCLUDE;
133 FileName const masterFileName(Buffer const & buffer)
135 return buffer.masterBuffer()->fileName();
139 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
142 string const parentFileName(Buffer const & buffer)
144 return buffer.absFileName();
148 FileName const includedFileName(Buffer const & buffer,
149 InsetCommandParams const & params)
151 return makeAbsPath(to_utf8(params["filename"]),
152 onlyPath(parentFileName(buffer)));
156 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
158 if (label_str.empty())
160 InsetCommandParams icp(LABEL_CODE);
161 icp["name"] = label_str;
162 return new InsetLabel(buf, icp);
168 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
169 : InsetCommand(buf, p), include_label(uniqueID()),
170 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
171 set_label_(false), label_(0), child_buffer_(0)
173 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
175 if (isListings(params())) {
176 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
177 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
178 } else if (isInputOrInclude(params()) && buf)
183 InsetInclude::InsetInclude(InsetInclude const & other)
184 : InsetCommand(other), include_label(other.include_label),
185 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
186 set_label_(false), label_(0), child_buffer_(0)
188 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
191 label_ = new InsetLabel(*other.label_);
195 InsetInclude::~InsetInclude()
197 if (isBufferLoaded())
198 buffer().invalidateBibfileCache();
203 void InsetInclude::setBuffer(Buffer & buffer)
205 InsetCommand::setBuffer(buffer);
207 label_->setBuffer(buffer);
211 void InsetInclude::setChildBuffer(Buffer * buffer)
213 child_buffer_ = buffer;
217 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
220 // This is only correct for the case of listings, but it'll do for now.
221 // In the other cases, this second parameter should just be empty.
222 static ParamInfo param_info_;
223 if (param_info_.empty()) {
224 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
225 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
231 bool InsetInclude::isCompatibleCommand(string const & s)
233 return type(s) != NONE;
237 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
239 switch (cmd.action()) {
241 case LFUN_INSET_EDIT: {
242 editIncluded(to_utf8(params()["filename"]));
246 case LFUN_INSET_MODIFY: {
247 // It should be OK just to invalidate the cache in setParams()
249 // child_buffer_ = 0;
250 InsetCommandParams p(INCLUDE_CODE);
251 if (cmd.getArg(0) == "changetype") {
253 InsetCommand::doDispatch(cur, cmd);
256 InsetCommand::string2params(to_utf8(cmd.argument()), p);
257 if (!p.getCmdName().empty()) {
259 InsetListingsParams new_params(to_utf8(p["lstparams"]));
260 docstring const new_label =
261 from_utf8(new_params.getParamValue("label"));
263 if (new_label.empty()) {
269 old_label = label_->getParam("name");
271 label_ = createLabel(buffer_, new_label);
272 label_->setBuffer(buffer());
275 if (new_label != old_label) {
276 label_->updateLabelAndRefs(new_label, &cur);
277 // the label might have been adapted (duplicate)
278 if (new_label != label_->getParam("name")) {
279 new_params.addParam("label", "{" +
280 to_utf8(label_->getParam("name")) + "}", true);
281 p["lstparams"] = from_utf8(new_params.params());
288 cur.forceBufferUpdate();
290 cur.noScreenUpdate();
294 //pass everything else up the chain
296 InsetCommand::doDispatch(cur, cmd);
302 void InsetInclude::editIncluded(string const & file)
304 string const ext = support::getExtension(file);
306 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
309 // tex file or other text file in verbatim mode
310 formats.edit(buffer(),
311 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
316 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
317 FuncStatus & flag) const
319 switch (cmd.action()) {
321 case LFUN_INSET_EDIT:
322 flag.setEnabled(true);
325 case LFUN_INSET_MODIFY:
326 if (cmd.getArg(0) == "changetype")
327 return InsetCommand::getStatus(cur, cmd, flag);
329 flag.setEnabled(true);
333 return InsetCommand::getStatus(cur, cmd, flag);
338 void InsetInclude::setParams(InsetCommandParams const & p)
340 // invalidate the cache
343 InsetCommand::setParams(p);
346 if (preview_->monitoring())
347 preview_->stopMonitoring();
349 if (type(params()) == INPUT)
350 add_preview(*preview_, *this, buffer());
352 buffer().invalidateBibfileCache();
356 bool InsetInclude::isChildIncluded() const
358 std::list<std::string> includeonlys =
359 buffer().params().getIncludedChildren();
360 if (includeonlys.empty())
362 return (std::find(includeonlys.begin(),
364 to_utf8(params()["filename"])) != includeonlys.end());
368 docstring InsetInclude::screenLabel() const
372 switch (type(params())) {
374 temp = buffer().B_("Input");
377 temp = buffer().B_("Verbatim Input");
380 temp = buffer().B_("Verbatim Input*");
383 if (isChildIncluded())
384 temp = buffer().B_("Include");
386 temp += buffer().B_("Include (excluded)");
389 temp = listings_label_;
392 LASSERT(false, temp = buffer().B_("Unknown"));
398 if (params()["filename"].empty())
401 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
407 Buffer * InsetInclude::getChildBuffer() const
409 Buffer * childBuffer = loadIfNeeded();
411 // FIXME RECURSIVE INCLUDE
412 // This isn't sufficient, as the inclusion could be downstream.
413 // But it'll have to do for now.
414 return (childBuffer == &buffer()) ? 0 : childBuffer;
418 Buffer * InsetInclude::loadIfNeeded() const
420 // This is for background export and preview. We don't even want to
421 // try to load the cloned child document again.
422 if (buffer().isClone())
423 return child_buffer_;
425 // Don't try to load it again if we failed before.
426 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
429 FileName const included_file = includedFileName(buffer(), params());
430 // Use cached Buffer if possible.
431 if (child_buffer_ != 0) {
432 if (theBufferList().isLoaded(child_buffer_)
433 // additional sanity check: make sure the Buffer really is
434 // associated with the file we want.
435 && child_buffer_ == theBufferList().getBuffer(included_file))
436 return child_buffer_;
437 // Buffer vanished, so invalidate cache and try to reload.
441 if (!isLyXFileName(included_file.absFileName()))
444 Buffer * child = theBufferList().getBuffer(included_file);
446 // the readonly flag can/will be wrong, not anymore I think.
447 if (!included_file.exists())
450 child = theBufferList().newBuffer(included_file.absFileName());
452 // Buffer creation is not possible.
455 // Set parent before loading, such that macros can be tracked
456 child->setParent(&buffer());
458 if (child->loadLyXFile() != Buffer::ReadSuccess) {
459 failedtoload_ = true;
461 //close the buffer we just opened
462 theBufferList().release(child);
466 if (!child->errorList("Parse").empty()) {
467 // FIXME: Do something.
470 // The file was already loaded, so, simply
471 // inform parent buffer about local macros.
472 Buffer const * parent = &buffer();
473 child->setParent(parent);
475 child->listMacroNames(macros);
476 MacroNameSet::const_iterator cit = macros.begin();
477 MacroNameSet::const_iterator end = macros.end();
478 for (; cit != end; ++cit)
479 parent->usermacros.insert(*cit);
482 // Cache the child buffer.
483 child_buffer_ = child;
488 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
490 string incfile = to_utf8(params()["filename"]);
492 // Do nothing if no file name has been specified
496 FileName const included_file = includedFileName(buffer(), params());
498 // Check we're not trying to include ourselves.
499 // FIXME RECURSIVE INCLUDE
500 // This isn't sufficient, as the inclusion could be downstream.
501 // But it'll have to do for now.
502 if (isInputOrInclude(params()) &&
503 buffer().absFileName() == included_file.absFileName())
505 Alert::error(_("Recursive input"),
506 bformat(_("Attempted to include file %1$s in itself! "
507 "Ignoring inclusion."), from_utf8(incfile)));
511 Buffer const * const masterBuffer = buffer().masterBuffer();
513 // if incfile is relative, make it relative to the master
515 if (!FileName::isAbsolute(incfile)) {
517 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
518 from_utf8(masterBuffer->filePath())));
521 string exppath = incfile;
522 if (!runparams.export_folder.empty()) {
523 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
524 FileName(exppath).onlyPath().createPath();
527 // write it to a file (so far the complete file)
531 if (type(params()) == LISTINGS) {
532 exportfile = exppath;
533 mangled = DocFileName(included_file).mangledFileName();
535 exportfile = changeExtension(exppath, ".tex");
536 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
542 else if (!runparams.silent)
543 ; // no warning wanted
544 else if (!isValidLaTeXFileName(incfile)) {
545 frontend::Alert::warning(_("Invalid filename"),
546 _("The following filename will cause troubles "
547 "when running the exported file through LaTeX: ") +
549 } else if (!isValidDVIFileName(incfile)) {
550 frontend::Alert::warning(_("Problematic filename for DVI"),
551 _("The following filename can cause troubles "
552 "when running the exported file through LaTeX "
553 "and opening the resulting DVI: ") +
554 from_utf8(incfile), true);
557 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
559 LYXERR(Debug::LATEX, "incfile:" << incfile);
560 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
561 LYXERR(Debug::LATEX, "writefile:" << writefile);
563 string const tex_format = flavor2format(runparams.flavor);
565 switch (type(params())) {
568 incfile = latex_path(incfile);
570 os << '\\' << from_ascii(params().getCmdName()) << '{'
571 << from_utf8(incfile) << '}';
575 runparams.exportdata->addExternalFile(tex_format, writefile,
578 // \input wants file with extension (default is .tex)
579 if (!isLyXFileName(included_file.absFileName())) {
580 incfile = latex_path(incfile);
582 os << '\\' << from_ascii(params().getCmdName())
583 << '{' << from_utf8(incfile) << '}';
585 incfile = changeExtension(incfile, ".tex");
586 incfile = latex_path(incfile);
588 os << '\\' << from_ascii(params().getCmdName())
589 << '{' << from_utf8(incfile) << '}';
594 runparams.exportdata->addExternalFile(tex_format, writefile,
596 os << '\\' << from_ascii(params().getCmdName());
597 string const opt = to_utf8(params()["lstparams"]);
598 // opt is set in QInclude dialog and should have passed validation.
599 InsetListingsParams params(opt);
600 if (!params.params().empty())
601 os << "[" << from_utf8(params.params()) << "]";
602 os << '{' << from_utf8(incfile) << '}';
606 runparams.exportdata->addExternalFile(tex_format, writefile,
609 // \include don't want extension and demands that the
610 // file really have .tex
611 incfile = changeExtension(incfile, string());
612 incfile = latex_path(incfile);
614 os << '\\' << from_ascii(params().getCmdName()) << '{'
615 << from_utf8(incfile) << '}';
622 if (runparams.inComment || runparams.dryrun)
623 // Don't try to load or copy the file if we're
624 // in a comment or doing a dryrun
627 if (isInputOrInclude(params()) &&
628 isLyXFileName(included_file.absFileName())) {
629 // if it's a LyX file and we're inputting or including,
630 // try to load it so we can write the associated latex
632 Buffer * tmp = loadIfNeeded();
634 if (!runparams.silent) {
635 docstring text = bformat(_("Could not load included "
637 "Please, check whether it actually exists."),
638 included_file.displayName());
639 Alert::warning(_("Missing included file"), text);
644 if (!runparams.silent) {
645 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
647 docstring text = bformat(_("Included file `%1$s'\n"
648 "has textclass `%2$s'\n"
649 "while parent file has textclass `%3$s'."),
650 included_file.displayName(),
651 from_utf8(tmp->params().documentClass().name()),
652 from_utf8(masterBuffer->params().documentClass().name()));
653 Alert::warning(_("Different textclasses"), text, true);
656 // Make sure modules used in child are all included in master
657 // FIXME It might be worth loading the children's modules into the master
658 // over in BufferParams rather than doing this check.
659 LayoutModuleList const masterModules = masterBuffer->params().getModules();
660 LayoutModuleList const childModules = tmp->params().getModules();
661 LayoutModuleList::const_iterator it = childModules.begin();
662 LayoutModuleList::const_iterator end = childModules.end();
663 for (; it != end; ++it) {
664 string const module = *it;
665 LayoutModuleList::const_iterator found =
666 find(masterModules.begin(), masterModules.end(), module);
667 if (found == masterModules.end()) {
668 docstring text = bformat(_("Included file `%1$s'\n"
669 "uses module `%2$s'\n"
670 "which is not used in parent file."),
671 included_file.displayName(), from_utf8(module));
672 Alert::warning(_("Module not found"), text);
677 tmp->markDepClean(masterBuffer->temppath());
679 // Don't assume the child's format is latex
680 string const inc_format = tmp->params().bufferFormat();
681 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
682 formats.extension(inc_format)));
684 // FIXME: handle non existing files
685 // The included file might be written in a different encoding
687 Encoding const * const oldEnc = runparams.encoding;
688 Language const * const oldLang = runparams.master_language;
689 // If the master has full unicode flavor (XeTeX, LuaTeX),
690 // the children must be encoded in plain utf8!
691 runparams.encoding = runparams.isFullUnicode() ?
692 encodings.fromLyXName("utf8-plain")
693 : &tmp->params().encoding();
694 runparams.master_language = buffer().params().language;
695 runparams.par_begin = 0;
696 runparams.par_end = tmp->paragraphs().size();
697 runparams.is_child = true;
698 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
699 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
700 if (!runparams.silent) {
701 docstring msg = bformat(_("Included file `%1$s' "
702 "was not exported correctly.\nWarning: "
703 "LaTeX export is probably incomplete."),
704 included_file.displayName());
705 ErrorList const & el = tmp->errorList("Export");
707 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
708 msg, el.begin()->error,
709 el.begin()->description);
710 Alert::warning(_("Export failure"), msg);
713 runparams.encoding = oldEnc;
714 runparams.master_language = oldLang;
715 runparams.is_child = false;
717 // If needed, use converters to produce a latex file from the child
718 if (tmpwritefile != writefile) {
721 theConverters().convert(tmp, tmpwritefile, writefile,
723 inc_format, tex_format, el);
725 if (!success && !runparams.silent) {
726 docstring msg = bformat(_("Included file `%1$s' "
727 "was not exported correctly.\nWarning: "
728 "LaTeX export is probably incomplete."),
729 included_file.displayName());
731 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
732 msg, el.begin()->error,
733 el.begin()->description);
734 Alert::warning(_("Export failure"), msg);
738 // In this case, it's not a LyX file, so we copy the file
739 // to the temp dir, so that .aux files etc. are not created
740 // in the original dir. Files included by this file will be
741 // found via either the environment variable TEXINPUTS, or
742 // input@path, see ../Buffer.cpp.
743 unsigned long const checksum_in = included_file.checksum();
744 unsigned long const checksum_out = writefile.checksum();
746 if (checksum_in != checksum_out) {
747 if (!included_file.copyTo(writefile)) {
750 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
751 "into the temporary directory."),
752 from_utf8(included_file.absFileName()))));
760 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
765 // For verbatim and listings, we just include the contents of the file as-is.
766 // In the case of listings, we wrap it in <pre>.
767 bool const listing = isListings(params());
768 if (listing || isVerbatim(params())) {
770 xs << html::StartTag("pre");
771 // FIXME: We don't know the encoding of the file, default to UTF-8.
772 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
774 xs << html::EndTag("pre");
778 // We don't (yet) know how to Input or Include non-LyX files.
779 // (If we wanted to get really arcane, we could run some tex2html
780 // converter on the included file. But that's just masochistic.)
781 FileName const included_file = includedFileName(buffer(), params());
782 if (!isLyXFileName(included_file.absFileName())) {
784 frontend::Alert::warning(_("Unsupported Inclusion"),
785 bformat(_("LyX does not know how to include non-LyX files when "
786 "generating HTML output. Offending file:\n%1$s"),
787 params()["filename"]));
791 // In the other cases, we will generate the HTML and include it.
793 // Check we're not trying to include ourselves.
794 // FIXME RECURSIVE INCLUDE
795 if (buffer().absFileName() == included_file.absFileName()) {
796 Alert::error(_("Recursive input"),
797 bformat(_("Attempted to include file %1$s in itself! "
798 "Ignoring inclusion."), params()["filename"]));
802 Buffer const * const ibuf = loadIfNeeded();
806 // are we generating only some paragraphs, or all of them?
807 bool const all_pars = !rp.dryrun ||
808 (rp.par_begin == 0 &&
809 rp.par_end == (int)buffer().text().paragraphs().size());
811 OutputParams op = rp;
815 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
817 xs << XHTMLStream::ESCAPE_NONE
818 << "<!-- Included file: "
819 << from_utf8(included_file.absFileName())
820 << XHTMLStream::ESCAPE_NONE
826 int InsetInclude::plaintext(odocstringstream & os,
827 OutputParams const & op, size_t) const
829 // just write the filename if we're making a tooltip or toc entry,
830 // or are generating this for advanced search
831 if (op.for_tooltip || op.for_toc || op.for_search) {
832 os << '[' << screenLabel() << '\n'
833 << getParam("filename") << "\n]";
834 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
837 if (isVerbatim(params()) || isListings(params())) {
838 os << '[' << screenLabel() << '\n'
839 // FIXME: We don't know the encoding of the file, default to UTF-8.
840 << includedFileName(buffer(), params()).fileContents("UTF-8")
842 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
845 Buffer const * const ibuf = loadIfNeeded();
847 docstring const str = '[' + screenLabel() + ']';
851 writePlaintextFile(*ibuf, os, op);
856 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
858 string incfile = to_utf8(params()["filename"]);
860 // Do nothing if no file name has been specified
864 string const included_file = includedFileName(buffer(), params()).absFileName();
866 // Check we're not trying to include ourselves.
867 // FIXME RECURSIVE INCLUDE
868 // This isn't sufficient, as the inclusion could be downstream.
869 // But it'll have to do for now.
870 if (buffer().absFileName() == included_file) {
871 Alert::error(_("Recursive input"),
872 bformat(_("Attempted to include file %1$s in itself! "
873 "Ignoring inclusion."), from_utf8(incfile)));
877 string exppath = incfile;
878 if (!runparams.export_folder.empty()) {
879 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
880 FileName(exppath).onlyPath().createPath();
883 // write it to a file (so far the complete file)
884 string const exportfile = changeExtension(exppath, ".sgml");
885 DocFileName writefile(changeExtension(included_file, ".sgml"));
887 Buffer * tmp = loadIfNeeded();
889 string const mangled = writefile.mangledFileName();
890 writefile = makeAbsPath(mangled,
891 buffer().masterBuffer()->temppath());
895 LYXERR(Debug::LATEX, "incfile:" << incfile);
896 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
897 LYXERR(Debug::LATEX, "writefile:" << writefile);
899 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
902 runparams.exportdata->addExternalFile("docbook", writefile,
904 runparams.exportdata->addExternalFile("docbook-xml", writefile,
907 if (isVerbatim(params()) || isListings(params())) {
908 os << "<inlinegraphic fileref=\""
909 << '&' << include_label << ';'
910 << "\" format=\"linespecific\">";
912 os << '&' << include_label << ';';
918 void InsetInclude::validate(LaTeXFeatures & features) const
920 LATTEST(&buffer() == &features.buffer());
922 string incfile = to_utf8(params()["filename"]);
923 string const included_file =
924 includedFileName(buffer(), params()).absFileName();
927 if (isLyXFileName(included_file))
928 writefile = changeExtension(included_file, ".sgml");
930 writefile = included_file;
932 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
933 incfile = DocFileName(writefile).mangledFileName();
934 writefile = makeAbsPath(incfile,
935 buffer().masterBuffer()->temppath()).absFileName();
938 features.includeFile(include_label, writefile);
940 features.useInsetLayout(getLayout());
941 if (isVerbatim(params()))
942 features.require("verbatim");
943 else if (isListings(params()))
944 features.require("listings");
946 // Here we must do the fun stuff...
947 // Load the file in the include if it needs
949 Buffer * const tmp = loadIfNeeded();
951 // the file is loaded
952 // make sure the buffer isn't us
953 // FIXME RECURSIVE INCLUDES
954 // This is not sufficient, as recursive includes could be
955 // more than a file away. But it will do for now.
956 if (tmp && tmp != &buffer()) {
957 // We must temporarily change features.buffer,
958 // otherwise it would always be the master buffer,
959 // and nested includes would not work.
960 features.setBuffer(*tmp);
961 // Maybe this is already a child
962 bool const is_child =
963 features.runparams().is_child;
964 features.runparams().is_child = true;
965 tmp->validate(features);
966 features.runparams().is_child = is_child;
967 features.setBuffer(buffer());
973 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
975 Buffer * child = loadIfNeeded();
978 // FIXME RECURSIVE INCLUDE
979 // This isn't sufficient, as the inclusion could be downstream.
980 // But it'll have to do for now.
981 if (child == &buffer())
983 child->collectBibKeys();
987 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
991 bool use_preview = false;
992 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
993 graphics::PreviewImage const * pimage =
994 preview_->getPreviewImage(mi.base.bv->buffer());
995 use_preview = pimage && pimage->image();
999 preview_->metrics(mi, dim);
1003 button_.update(screenLabel(), true);
1005 button_.metrics(mi, dim);
1008 Box b(0, dim.wid, -dim.asc, dim.des);
1013 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1015 LBUFERR(pi.base.bv);
1017 bool use_preview = false;
1018 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
1019 graphics::PreviewImage const * pimage =
1020 preview_->getPreviewImage(pi.base.bv->buffer());
1021 use_preview = pimage && pimage->image();
1025 preview_->draw(pi, x, y);
1027 button_.draw(pi, x, y);
1031 string InsetInclude::contextMenuName() const
1033 return "context-include";
1037 Inset::DisplayType InsetInclude::display() const
1039 return type(params()) == INPUT ? Inline : AlignCenter;
1043 docstring InsetInclude::layoutName() const
1045 if (isListings(params()))
1046 return from_ascii("IncludeListings");
1047 return InsetCommand::layoutName();
1055 void InsetInclude::fileChanged() const
1057 Buffer const * const buffer = updateFrontend();
1061 preview_->removePreview(*buffer);
1062 add_preview(*preview_.get(), *this, *buffer);
1063 preview_->startLoading(*buffer);
1069 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1071 FileName const included_file = includedFileName(buffer, params);
1073 return type(params) == INPUT && params.preview() &&
1074 included_file.isReadableFile();
1078 docstring latexString(InsetInclude const & inset)
1081 odocstringstream ods;
1082 otexstream os(ods, texrow);
1083 // We don't need to set runparams.encoding since this will be done
1084 // by latex() anyway.
1085 OutputParams runparams(0);
1086 runparams.flavor = OutputParams::LATEX;
1087 inset.latex(os, runparams);
1093 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1094 Buffer const & buffer)
1096 InsetCommandParams const & params = inset.params();
1097 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
1098 preview_wanted(params, buffer)) {
1099 renderer.setAbsFile(includedFileName(buffer, params));
1100 docstring const snippet = latexString(inset);
1101 renderer.addPreview(snippet, buffer);
1108 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1109 graphics::PreviewLoader & ploader) const
1111 Buffer const & buffer = ploader.buffer();
1112 if (!preview_wanted(params(), buffer))
1114 preview_->setAbsFile(includedFileName(buffer, params()));
1115 docstring const snippet = latexString(*this);
1116 preview_->addPreview(snippet, ploader);
1120 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active) const
1122 TocBackend & backend = buffer().tocBackend();
1124 if (isListings(params())) {
1126 label_->addToToc(cpit, output_active);
1128 InsetListingsParams p(to_utf8(params()["lstparams"]));
1129 string caption = p.getParamValue("caption");
1130 if (caption.empty())
1132 Toc & toc = backend.toc("listing");
1133 docstring str = convert<docstring>(toc.size() + 1)
1134 + ". " + from_utf8(caption);
1135 DocIterator pit = cpit;
1136 toc.push_back(TocItem(pit, 0, str, output_active));
1139 Buffer const * const childbuffer = getChildBuffer();
1143 Toc & toc = backend.toc("child");
1144 docstring str = childbuffer->fileName().displayName();
1145 toc.push_back(TocItem(cpit, 0, str, output_active));
1147 TocList & toclist = backend.tocs();
1148 childbuffer->tocBackend().update(output_active);
1149 TocList const & childtoclist = childbuffer->tocBackend().tocs();
1150 TocList::const_iterator it = childtoclist.begin();
1151 TocList::const_iterator const end = childtoclist.end();
1152 for(; it != end; ++it)
1153 toclist[it->first].insert(toclist[it->first].end(),
1154 it->second.begin(), it->second.end());
1158 void InsetInclude::updateCommand()
1163 docstring old_label = label_->getParam("name");
1164 label_->updateLabel(old_label);
1165 // the label might have been adapted (duplicate)
1166 docstring new_label = label_->getParam("name");
1167 if (old_label == new_label)
1170 // update listings parameters...
1171 InsetCommandParams p(INCLUDE_CODE);
1173 InsetListingsParams par(to_utf8(params()["lstparams"]));
1174 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1175 p["lstparams"] = from_utf8(par.params());
1180 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1182 button_.update(screenLabel(), true);
1184 Buffer const * const childbuffer = getChildBuffer();
1186 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1189 if (!isListings(params()))
1193 label_->updateBuffer(it, utype);
1195 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1196 if (par.getParamValue("caption").empty()) {
1197 listings_label_ = buffer().B_("Program Listing");
1200 Buffer const & master = *buffer().masterBuffer();
1201 Counters & counters = master.params().documentClass().counters();
1202 docstring const cnt = from_ascii("listing");
1203 listings_label_ = master.B_("Program Listing");
1204 if (counters.hasCounter(cnt)) {
1205 counters.step(cnt, utype);
1206 listings_label_ += " " + convert<docstring>(counters.value(cnt));