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"
35 #include "MetricsInfo.h"
36 #include "output_plaintext.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"
63 #include "support/mutex.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;
81 Mutex::Locker lock(&mutex);
82 return "file" + convert<docstring>(++seed);
86 /// the type of inclusion
88 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
92 Types type(string const & s)
96 if (s == "verbatiminput")
98 if (s == "verbatiminput*")
100 if (s == "lstinputlisting")
108 Types type(InsetCommandParams const & params)
110 return type(params.getCmdName());
114 bool isListings(InsetCommandParams const & params)
116 return type(params) == LISTINGS;
120 bool isVerbatim(InsetCommandParams const & params)
122 Types const t = type(params);
123 return t == VERB || t == VERBAST;
127 bool isInputOrInclude(InsetCommandParams const & params)
129 Types const t = type(params);
130 return t == INPUT || t == INCLUDE;
134 FileName const masterFileName(Buffer const & buffer)
136 return buffer.masterBuffer()->fileName();
140 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
143 string const parentFileName(Buffer const & buffer)
145 return buffer.absFileName();
149 FileName const includedFileName(Buffer const & buffer,
150 InsetCommandParams const & params)
152 return makeAbsPath(to_utf8(params["filename"]),
153 onlyPath(parentFileName(buffer)));
157 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
159 if (label_str.empty())
161 InsetCommandParams icp(LABEL_CODE);
162 icp["name"] = label_str;
163 return new InsetLabel(buf, icp);
169 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
170 : InsetCommand(buf, p), include_label(uniqueID()),
171 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
172 set_label_(false), label_(0), child_buffer_(0)
174 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
176 if (isListings(params())) {
177 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
178 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
179 } else if (isInputOrInclude(params()) && buf)
184 InsetInclude::InsetInclude(InsetInclude const & other)
185 : InsetCommand(other), include_label(other.include_label),
186 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
187 set_label_(false), label_(0), child_buffer_(0)
189 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
192 label_ = new InsetLabel(*other.label_);
196 InsetInclude::~InsetInclude()
198 if (isBufferLoaded())
199 buffer().invalidateBibfileCache();
204 void InsetInclude::setBuffer(Buffer & buffer)
206 InsetCommand::setBuffer(buffer);
208 label_->setBuffer(buffer);
212 void InsetInclude::setChildBuffer(Buffer * buffer)
214 child_buffer_ = buffer;
218 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
221 // This is only correct for the case of listings, but it'll do for now.
222 // In the other cases, this second parameter should just be empty.
223 static ParamInfo param_info_;
224 if (param_info_.empty()) {
225 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
226 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
232 bool InsetInclude::isCompatibleCommand(string const & s)
234 return type(s) != NONE;
238 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
240 switch (cmd.action()) {
242 case LFUN_INSET_EDIT: {
243 editIncluded(to_utf8(params()["filename"]));
247 case LFUN_INSET_MODIFY: {
248 // It should be OK just to invalidate the cache in setParams()
250 // child_buffer_ = 0;
251 InsetCommandParams p(INCLUDE_CODE);
252 if (cmd.getArg(0) == "changetype") {
254 InsetCommand::doDispatch(cur, cmd);
257 InsetCommand::string2params(to_utf8(cmd.argument()), p);
258 if (!p.getCmdName().empty()) {
260 InsetListingsParams new_params(to_utf8(p["lstparams"]));
261 docstring const new_label =
262 from_utf8(new_params.getParamValue("label"));
264 if (new_label.empty()) {
270 old_label = label_->getParam("name");
272 label_ = createLabel(buffer_, new_label);
273 label_->setBuffer(buffer());
276 if (new_label != old_label) {
277 label_->updateLabelAndRefs(new_label, &cur);
278 // the label might have been adapted (duplicate)
279 if (new_label != label_->getParam("name")) {
280 new_params.addParam("label", "{" +
281 to_utf8(label_->getParam("name")) + "}", true);
282 p["lstparams"] = from_utf8(new_params.params());
289 cur.forceBufferUpdate();
291 cur.noScreenUpdate();
295 //pass everything else up the chain
297 InsetCommand::doDispatch(cur, cmd);
303 void InsetInclude::editIncluded(string const & file)
305 string const ext = support::getExtension(file);
307 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
310 // tex file or other text file in verbatim mode
311 formats.edit(buffer(),
312 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
317 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
318 FuncStatus & flag) const
320 switch (cmd.action()) {
322 case LFUN_INSET_EDIT:
323 flag.setEnabled(true);
326 case LFUN_INSET_MODIFY:
327 if (cmd.getArg(0) == "changetype")
328 return InsetCommand::getStatus(cur, cmd, flag);
330 flag.setEnabled(true);
334 return InsetCommand::getStatus(cur, cmd, flag);
339 void InsetInclude::setParams(InsetCommandParams const & p)
341 // invalidate the cache
344 InsetCommand::setParams(p);
347 if (preview_->monitoring())
348 preview_->stopMonitoring();
350 if (type(params()) == INPUT)
351 add_preview(*preview_, *this, buffer());
353 buffer().invalidateBibfileCache();
357 bool InsetInclude::isChildIncluded() const
359 std::list<std::string> includeonlys =
360 buffer().params().getIncludedChildren();
361 if (includeonlys.empty())
363 return (std::find(includeonlys.begin(),
365 to_utf8(params()["filename"])) != includeonlys.end());
369 docstring InsetInclude::screenLabel() const
373 switch (type(params())) {
375 temp = buffer().B_("Input");
378 temp = buffer().B_("Verbatim Input");
381 temp = buffer().B_("Verbatim Input*");
384 if (isChildIncluded())
385 temp = buffer().B_("Include");
387 temp += buffer().B_("Include (excluded)");
390 temp = listings_label_;
393 LASSERT(false, temp = buffer().B_("Unknown"));
399 if (params()["filename"].empty())
402 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
408 Buffer * InsetInclude::getChildBuffer() const
410 Buffer * childBuffer = loadIfNeeded();
412 // FIXME RECURSIVE INCLUDE
413 // This isn't sufficient, as the inclusion could be downstream.
414 // But it'll have to do for now.
415 return (childBuffer == &buffer()) ? 0 : childBuffer;
419 Buffer * InsetInclude::loadIfNeeded() const
421 // This is for background export and preview. We don't even want to
422 // try to load the cloned child document again.
423 if (buffer().isClone())
424 return child_buffer_;
426 // Don't try to load it again if we failed before.
427 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
430 FileName const included_file = includedFileName(buffer(), params());
431 // Use cached Buffer if possible.
432 if (child_buffer_ != 0) {
433 if (theBufferList().isLoaded(child_buffer_)
434 // additional sanity check: make sure the Buffer really is
435 // associated with the file we want.
436 && child_buffer_ == theBufferList().getBuffer(included_file))
437 return child_buffer_;
438 // Buffer vanished, so invalidate cache and try to reload.
442 if (!isLyXFileName(included_file.absFileName()))
445 Buffer * child = theBufferList().getBuffer(included_file);
447 // the readonly flag can/will be wrong, not anymore I think.
448 if (!included_file.exists())
451 child = theBufferList().newBuffer(included_file.absFileName());
453 // Buffer creation is not possible.
456 // Set parent before loading, such that macros can be tracked
457 child->setParent(&buffer());
459 if (child->loadLyXFile() != Buffer::ReadSuccess) {
460 failedtoload_ = true;
462 //close the buffer we just opened
463 theBufferList().release(child);
467 if (!child->errorList("Parse").empty()) {
468 // FIXME: Do something.
471 // The file was already loaded, so, simply
472 // inform parent buffer about local macros.
473 Buffer const * parent = &buffer();
474 child->setParent(parent);
476 child->listMacroNames(macros);
477 MacroNameSet::const_iterator cit = macros.begin();
478 MacroNameSet::const_iterator end = macros.end();
479 for (; cit != end; ++cit)
480 parent->usermacros.insert(*cit);
483 // Cache the child buffer.
484 child_buffer_ = child;
489 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
491 string incfile = to_utf8(params()["filename"]);
493 // Do nothing if no file name has been specified
497 FileName const included_file = includedFileName(buffer(), params());
499 // Check we're not trying to include ourselves.
500 // FIXME RECURSIVE INCLUDE
501 // This isn't sufficient, as the inclusion could be downstream.
502 // But it'll have to do for now.
503 if (isInputOrInclude(params()) &&
504 buffer().absFileName() == included_file.absFileName())
506 Alert::error(_("Recursive input"),
507 bformat(_("Attempted to include file %1$s in itself! "
508 "Ignoring inclusion."), from_utf8(incfile)));
512 Buffer const * const masterBuffer = buffer().masterBuffer();
514 // if incfile is relative, make it relative to the master
516 if (!FileName::isAbsolute(incfile)) {
518 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
519 from_utf8(masterBuffer->filePath())));
522 string exppath = incfile;
523 if (!runparams.export_folder.empty()) {
524 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
525 FileName(exppath).onlyPath().createPath();
528 // write it to a file (so far the complete file)
532 if (type(params()) == LISTINGS) {
533 exportfile = exppath;
534 mangled = DocFileName(included_file).mangledFileName();
536 exportfile = changeExtension(exppath, ".tex");
537 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
543 else if (!runparams.silent)
544 ; // no warning wanted
545 else if (!isValidLaTeXFileName(incfile)) {
546 frontend::Alert::warning(_("Invalid filename"),
547 _("The following filename will cause troubles "
548 "when running the exported file through LaTeX: ") +
550 } else if (!isValidDVIFileName(incfile)) {
551 frontend::Alert::warning(_("Problematic filename for DVI"),
552 _("The following filename can cause troubles "
553 "when running the exported file through LaTeX "
554 "and opening the resulting DVI: ") +
555 from_utf8(incfile), true);
558 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
559 buffer().temppath() : masterBuffer->temppath()));
561 LYXERR(Debug::LATEX, "incfile:" << incfile);
562 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
563 LYXERR(Debug::LATEX, "writefile:" << writefile);
565 string const tex_format = flavor2format(runparams.flavor);
567 switch (type(params())) {
570 incfile = latex_path(incfile);
572 os << '\\' << from_ascii(params().getCmdName()) << '{'
573 << from_utf8(incfile) << '}';
577 runparams.exportdata->addExternalFile(tex_format, writefile,
580 // \input wants file with extension (default is .tex)
581 if (!isLyXFileName(included_file.absFileName())) {
582 incfile = latex_path(incfile);
584 os << '\\' << from_ascii(params().getCmdName())
585 << '{' << from_utf8(incfile) << '}';
587 incfile = changeExtension(incfile, ".tex");
588 incfile = latex_path(incfile);
590 os << '\\' << from_ascii(params().getCmdName())
591 << '{' << from_utf8(incfile) << '}';
596 runparams.exportdata->addExternalFile(tex_format, writefile,
598 os << '\\' << from_ascii(params().getCmdName());
599 string const opt = to_utf8(params()["lstparams"]);
600 // opt is set in QInclude dialog and should have passed validation.
601 InsetListingsParams params(opt);
602 if (!params.params().empty())
603 os << "[" << from_utf8(params.params()) << "]";
604 os << '{' << from_utf8(incfile) << '}';
608 runparams.exportdata->addExternalFile(tex_format, writefile,
611 // \include don't want extension and demands that the
612 // file really have .tex
613 incfile = changeExtension(incfile, string());
614 incfile = latex_path(incfile);
616 os << '\\' << from_ascii(params().getCmdName()) << '{'
617 << from_utf8(incfile) << '}';
624 if (runparams.inComment || runparams.dryrun)
625 // Don't try to load or copy the file if we're
626 // in a comment or doing a dryrun
629 if (isInputOrInclude(params()) &&
630 isLyXFileName(included_file.absFileName())) {
631 // if it's a LyX file and we're inputting or including,
632 // try to load it so we can write the associated latex
634 Buffer * tmp = loadIfNeeded();
636 if (!runparams.silent) {
637 docstring text = bformat(_("Could not load included "
639 "Please, check whether it actually exists."),
640 included_file.displayName());
641 Alert::warning(_("Missing included file"), text);
646 if (!runparams.silent) {
647 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
649 docstring text = bformat(_("Included file `%1$s'\n"
650 "has textclass `%2$s'\n"
651 "while parent file has textclass `%3$s'."),
652 included_file.displayName(),
653 from_utf8(tmp->params().documentClass().name()),
654 from_utf8(masterBuffer->params().documentClass().name()));
655 Alert::warning(_("Different textclasses"), text, true);
658 // Make sure modules used in child are all included in master
659 // FIXME It might be worth loading the children's modules into the master
660 // over in BufferParams rather than doing this check.
661 LayoutModuleList const masterModules = masterBuffer->params().getModules();
662 LayoutModuleList const childModules = tmp->params().getModules();
663 LayoutModuleList::const_iterator it = childModules.begin();
664 LayoutModuleList::const_iterator end = childModules.end();
665 for (; it != end; ++it) {
666 string const module = *it;
667 LayoutModuleList::const_iterator found =
668 find(masterModules.begin(), masterModules.end(), module);
669 if (found == masterModules.end()) {
670 docstring text = bformat(_("Included file `%1$s'\n"
671 "uses module `%2$s'\n"
672 "which is not used in parent file."),
673 included_file.displayName(), from_utf8(module));
674 Alert::warning(_("Module not found"), text);
679 tmp->markDepClean(masterBuffer->temppath());
681 // Don't assume the child's format is latex
682 string const inc_format = tmp->params().bufferFormat();
683 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
684 formats.extension(inc_format)));
686 // FIXME: handle non existing files
687 // The included file might be written in a different encoding
689 Encoding const * const oldEnc = runparams.encoding;
690 Language const * const oldLang = runparams.master_language;
691 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
692 // the children must be encoded in plain utf8!
693 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
694 encodings.fromLyXName("utf8-plain")
695 : &tmp->params().encoding();
696 runparams.master_language = buffer().params().language;
697 runparams.par_begin = 0;
698 runparams.par_end = tmp->paragraphs().size();
699 runparams.is_child = true;
700 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
701 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
702 if (!runparams.silent) {
703 docstring msg = bformat(_("Included file `%1$s' "
704 "was not exported correctly.\nWarning: "
705 "LaTeX export is probably incomplete."),
706 included_file.displayName());
707 ErrorList const & el = tmp->errorList("Export");
709 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
710 msg, el.begin()->error,
711 el.begin()->description);
712 Alert::warning(_("Export failure"), msg);
715 runparams.encoding = oldEnc;
716 runparams.master_language = oldLang;
717 runparams.is_child = false;
719 // If needed, use converters to produce a latex file from the child
720 if (tmpwritefile != writefile) {
723 theConverters().convert(tmp, tmpwritefile, writefile,
725 inc_format, tex_format, el);
727 if (!success && !runparams.silent) {
728 docstring msg = bformat(_("Included file `%1$s' "
729 "was not exported correctly.\nWarning: "
730 "LaTeX export is probably incomplete."),
731 included_file.displayName());
733 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
734 msg, el.begin()->error,
735 el.begin()->description);
736 Alert::warning(_("Export failure"), msg);
740 // In this case, it's not a LyX file, so we copy the file
741 // to the temp dir, so that .aux files etc. are not created
742 // in the original dir. Files included by this file will be
743 // found via either the environment variable TEXINPUTS, or
744 // input@path, see ../Buffer.cpp.
745 unsigned long const checksum_in = included_file.checksum();
746 unsigned long const checksum_out = writefile.checksum();
748 if (checksum_in != checksum_out) {
749 if (!included_file.copyTo(writefile)) {
752 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
753 "into the temporary directory."),
754 from_utf8(included_file.absFileName()))));
762 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
767 // For verbatim and listings, we just include the contents of the file as-is.
768 // In the case of listings, we wrap it in <pre>.
769 bool const listing = isListings(params());
770 if (listing || isVerbatim(params())) {
772 xs << html::StartTag("pre");
773 // FIXME: We don't know the encoding of the file, default to UTF-8.
774 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
776 xs << html::EndTag("pre");
780 // We don't (yet) know how to Input or Include non-LyX files.
781 // (If we wanted to get really arcane, we could run some tex2html
782 // converter on the included file. But that's just masochistic.)
783 FileName const included_file = includedFileName(buffer(), params());
784 if (!isLyXFileName(included_file.absFileName())) {
786 frontend::Alert::warning(_("Unsupported Inclusion"),
787 bformat(_("LyX does not know how to include non-LyX files when "
788 "generating HTML output. Offending file:\n%1$s"),
789 params()["filename"]));
793 // In the other cases, we will generate the HTML and include it.
795 // Check we're not trying to include ourselves.
796 // FIXME RECURSIVE INCLUDE
797 if (buffer().absFileName() == included_file.absFileName()) {
798 Alert::error(_("Recursive input"),
799 bformat(_("Attempted to include file %1$s in itself! "
800 "Ignoring inclusion."), params()["filename"]));
804 Buffer const * const ibuf = loadIfNeeded();
808 // are we generating only some paragraphs, or all of them?
809 bool const all_pars = !rp.dryrun ||
810 (rp.par_begin == 0 &&
811 rp.par_end == (int)buffer().text().paragraphs().size());
813 OutputParams op = rp;
817 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
819 xs << XHTMLStream::ESCAPE_NONE
820 << "<!-- Included file: "
821 << from_utf8(included_file.absFileName())
822 << XHTMLStream::ESCAPE_NONE
828 int InsetInclude::plaintext(odocstringstream & os,
829 OutputParams const & op, size_t) const
831 // just write the filename if we're making a tooltip or toc entry,
832 // or are generating this for advanced search
833 if (op.for_tooltip || op.for_toc || op.for_search) {
834 os << '[' << screenLabel() << '\n'
835 << getParam("filename") << "\n]";
836 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
839 if (isVerbatim(params()) || isListings(params())) {
840 os << '[' << screenLabel() << '\n'
841 // FIXME: We don't know the encoding of the file, default to UTF-8.
842 << includedFileName(buffer(), params()).fileContents("UTF-8")
844 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
847 Buffer const * const ibuf = loadIfNeeded();
849 docstring const str = '[' + screenLabel() + ']';
853 writePlaintextFile(*ibuf, os, op);
858 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
860 string incfile = to_utf8(params()["filename"]);
862 // Do nothing if no file name has been specified
866 string const included_file = includedFileName(buffer(), params()).absFileName();
868 // Check we're not trying to include ourselves.
869 // FIXME RECURSIVE INCLUDE
870 // This isn't sufficient, as the inclusion could be downstream.
871 // But it'll have to do for now.
872 if (buffer().absFileName() == included_file) {
873 Alert::error(_("Recursive input"),
874 bformat(_("Attempted to include file %1$s in itself! "
875 "Ignoring inclusion."), from_utf8(incfile)));
879 string exppath = incfile;
880 if (!runparams.export_folder.empty()) {
881 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
882 FileName(exppath).onlyPath().createPath();
885 // write it to a file (so far the complete file)
886 string const exportfile = changeExtension(exppath, ".sgml");
887 DocFileName writefile(changeExtension(included_file, ".sgml"));
889 Buffer * tmp = loadIfNeeded();
891 string const mangled = writefile.mangledFileName();
892 writefile = makeAbsPath(mangled,
893 buffer().masterBuffer()->temppath());
897 LYXERR(Debug::LATEX, "incfile:" << incfile);
898 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
899 LYXERR(Debug::LATEX, "writefile:" << writefile);
901 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
904 runparams.exportdata->addExternalFile("docbook", writefile,
906 runparams.exportdata->addExternalFile("docbook-xml", writefile,
909 if (isVerbatim(params()) || isListings(params())) {
910 os << "<inlinegraphic fileref=\""
911 << '&' << include_label << ';'
912 << "\" format=\"linespecific\">";
914 os << '&' << include_label << ';';
920 void InsetInclude::validate(LaTeXFeatures & features) const
922 LATTEST(&buffer() == &features.buffer());
924 string incfile = to_utf8(params()["filename"]);
925 string const included_file =
926 includedFileName(buffer(), params()).absFileName();
929 if (isLyXFileName(included_file))
930 writefile = changeExtension(included_file, ".sgml");
932 writefile = included_file;
934 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
935 incfile = DocFileName(writefile).mangledFileName();
936 writefile = makeAbsPath(incfile,
937 buffer().masterBuffer()->temppath()).absFileName();
940 features.includeFile(include_label, writefile);
942 features.useInsetLayout(getLayout());
943 if (isVerbatim(params()))
944 features.require("verbatim");
945 else if (isListings(params()))
946 features.require("listings");
948 // Here we must do the fun stuff...
949 // Load the file in the include if it needs
951 Buffer * const tmp = loadIfNeeded();
953 // the file is loaded
954 // make sure the buffer isn't us
955 // FIXME RECURSIVE INCLUDES
956 // This is not sufficient, as recursive includes could be
957 // more than a file away. But it will do for now.
958 if (tmp && tmp != &buffer()) {
959 // We must temporarily change features.buffer,
960 // otherwise it would always be the master buffer,
961 // and nested includes would not work.
962 features.setBuffer(*tmp);
963 // Maybe this is already a child
964 bool const is_child =
965 features.runparams().is_child;
966 features.runparams().is_child = true;
967 tmp->validate(features);
968 features.runparams().is_child = is_child;
969 features.setBuffer(buffer());
975 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
977 Buffer * child = loadIfNeeded();
980 // FIXME RECURSIVE INCLUDE
981 // This isn't sufficient, as the inclusion could be downstream.
982 // But it'll have to do for now.
983 if (child == &buffer())
985 child->collectBibKeys();
989 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
993 bool use_preview = false;
994 if (RenderPreview::previewText()) {
995 graphics::PreviewImage const * pimage =
996 preview_->getPreviewImage(mi.base.bv->buffer());
997 use_preview = pimage && pimage->image();
1001 preview_->metrics(mi, dim);
1005 button_.update(screenLabel(), true);
1007 button_.metrics(mi, dim);
1010 Box b(0, dim.wid, -dim.asc, dim.des);
1015 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1017 LBUFERR(pi.base.bv);
1019 bool use_preview = false;
1020 if (RenderPreview::previewText()) {
1021 graphics::PreviewImage const * pimage =
1022 preview_->getPreviewImage(pi.base.bv->buffer());
1023 use_preview = pimage && pimage->image();
1027 preview_->draw(pi, x, y);
1029 button_.draw(pi, x, y);
1033 void InsetInclude::write(ostream & os) const
1035 params().Write(os, &buffer());
1039 string InsetInclude::contextMenuName() const
1041 return "context-include";
1045 Inset::DisplayType InsetInclude::display() const
1047 return type(params()) == INPUT ? Inline : AlignCenter;
1051 docstring InsetInclude::layoutName() const
1053 if (isListings(params()))
1054 return from_ascii("IncludeListings");
1055 return InsetCommand::layoutName();
1063 void InsetInclude::fileChanged() const
1065 Buffer const * const buffer = updateFrontend();
1069 preview_->removePreview(*buffer);
1070 add_preview(*preview_.get(), *this, *buffer);
1071 preview_->startLoading(*buffer);
1077 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1079 FileName const included_file = includedFileName(buffer, params);
1081 return type(params) == INPUT && params.preview() &&
1082 included_file.isReadableFile();
1086 docstring latexString(InsetInclude const & inset)
1089 odocstringstream ods;
1090 otexstream os(ods, texrow);
1091 // We don't need to set runparams.encoding since this will be done
1092 // by latex() anyway.
1093 OutputParams runparams(0);
1094 runparams.flavor = OutputParams::LATEX;
1095 runparams.for_preview = true;
1096 inset.latex(os, runparams);
1102 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1103 Buffer const & buffer)
1105 InsetCommandParams const & params = inset.params();
1106 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1107 renderer.setAbsFile(includedFileName(buffer, params));
1108 docstring const snippet = latexString(inset);
1109 renderer.addPreview(snippet, buffer);
1116 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1117 graphics::PreviewLoader & ploader) const
1119 Buffer const & buffer = ploader.buffer();
1120 if (!preview_wanted(params(), buffer))
1122 preview_->setAbsFile(includedFileName(buffer, params()));
1123 docstring const snippet = latexString(*this);
1124 preview_->addPreview(snippet, ploader);
1128 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1129 UpdateType utype) const
1131 TocBackend & backend = buffer().tocBackend();
1133 if (isListings(params())) {
1135 label_->addToToc(cpit, output_active, utype);
1137 InsetListingsParams p(to_utf8(params()["lstparams"]));
1138 string caption = p.getParamValue("caption");
1139 if (caption.empty())
1141 shared_ptr<Toc> toc = backend.toc("listing");
1142 docstring str = convert<docstring>(toc->size() + 1)
1143 + ". " + from_utf8(caption);
1144 DocIterator pit = cpit;
1145 toc->push_back(TocItem(pit, 0, str, output_active));
1147 Buffer const * const childbuffer = getChildBuffer();
1151 shared_ptr<Toc> toc = backend.toc("child");
1152 docstring str = childbuffer->fileName().displayName();
1153 toc->push_back(TocItem(cpit, 0, str, output_active));
1155 childbuffer->tocBackend().update(output_active, utype);
1156 TocList const & childtoclist = childbuffer->tocBackend().tocs();
1157 TocList::const_iterator it = childtoclist.begin();
1158 TocList::const_iterator const end = childtoclist.end();
1159 for(; it != end; ++it) {
1160 shared_ptr<Toc> toc = backend.toc(it->first);
1161 toc->insert(toc->end(), it->second->begin(), it->second->end());
1167 void InsetInclude::updateCommand()
1172 docstring old_label = label_->getParam("name");
1173 label_->updateLabel(old_label);
1174 // the label might have been adapted (duplicate)
1175 docstring new_label = label_->getParam("name");
1176 if (old_label == new_label)
1179 // update listings parameters...
1180 InsetCommandParams p(INCLUDE_CODE);
1182 InsetListingsParams par(to_utf8(params()["lstparams"]));
1183 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1184 p["lstparams"] = from_utf8(par.params());
1189 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1191 button_.update(screenLabel(), true);
1193 Buffer const * const childbuffer = getChildBuffer();
1195 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1198 if (!isListings(params()))
1202 label_->updateBuffer(it, utype);
1204 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1205 if (par.getParamValue("caption").empty()) {
1206 listings_label_ = buffer().B_("Program Listing");
1209 Buffer const & master = *buffer().masterBuffer();
1210 Counters & counters = master.params().documentClass().counters();
1211 docstring const cnt = from_ascii("listing");
1212 listings_label_ = master.B_("Program Listing");
1213 if (counters.hasCounter(cnt)) {
1214 counters.step(cnt, utype);
1215 listings_label_ += " " + convert<docstring>(counters.value(cnt));