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 "texstream.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"
64 #include "support/mutex.h"
65 #include "support/ExceptionMessage.h"
67 #include "support/bind.h"
70 using namespace lyx::support;
74 namespace Alert = frontend::Alert;
79 docstring const uniqueID()
81 static unsigned int seed = 1000;
83 Mutex::Locker lock(&mutex);
84 return "file" + convert<docstring>(++seed);
88 /// the type of inclusion
90 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
94 Types type(string const & s)
98 if (s == "verbatiminput")
100 if (s == "verbatiminput*")
102 if (s == "lstinputlisting")
110 Types type(InsetCommandParams const & params)
112 return type(params.getCmdName());
116 bool isListings(InsetCommandParams const & params)
118 return type(params) == LISTINGS;
122 bool isVerbatim(InsetCommandParams const & params)
124 Types const t = type(params);
125 return t == VERB || t == VERBAST;
129 bool isInputOrInclude(InsetCommandParams const & params)
131 Types const t = type(params);
132 return t == INPUT || t == INCLUDE;
136 FileName const masterFileName(Buffer const & buffer)
138 return buffer.masterBuffer()->fileName();
142 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
145 string const parentFileName(Buffer const & buffer)
147 return buffer.absFileName();
151 FileName const includedFileName(Buffer const & buffer,
152 InsetCommandParams const & params)
154 return makeAbsPath(to_utf8(params["filename"]),
155 onlyPath(parentFileName(buffer)));
159 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
161 if (label_str.empty())
163 InsetCommandParams icp(LABEL_CODE);
164 icp["name"] = label_str;
165 return new InsetLabel(buf, icp);
171 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
172 : InsetCommand(buf, p), include_label(uniqueID()),
173 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
174 set_label_(false), label_(0), child_buffer_(0)
176 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
178 if (isListings(params())) {
179 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
180 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
181 } else if (isInputOrInclude(params()) && buf)
186 InsetInclude::InsetInclude(InsetInclude const & other)
187 : InsetCommand(other), include_label(other.include_label),
188 preview_(new RenderMonitoredPreview(this)), failedtoload_(false),
189 set_label_(false), label_(0), child_buffer_(0)
191 preview_->fileChanged(bind(&InsetInclude::fileChanged, this));
194 label_ = new InsetLabel(*other.label_);
198 InsetInclude::~InsetInclude()
200 if (isBufferLoaded())
201 buffer().invalidateBibfileCache();
206 void InsetInclude::setBuffer(Buffer & buffer)
208 InsetCommand::setBuffer(buffer);
210 label_->setBuffer(buffer);
214 void InsetInclude::setChildBuffer(Buffer * buffer)
216 child_buffer_ = buffer;
220 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
223 // This is only correct for the case of listings, but it'll do for now.
224 // In the other cases, this second parameter should just be empty.
225 static ParamInfo param_info_;
226 if (param_info_.empty()) {
227 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
228 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
234 bool InsetInclude::isCompatibleCommand(string const & s)
236 return type(s) != NONE;
240 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
242 switch (cmd.action()) {
244 case LFUN_INSET_EDIT: {
245 editIncluded(to_utf8(params()["filename"]));
249 case LFUN_INSET_MODIFY: {
250 // It should be OK just to invalidate the cache in setParams()
252 // child_buffer_ = 0;
253 InsetCommandParams p(INCLUDE_CODE);
254 if (cmd.getArg(0) == "changetype") {
256 InsetCommand::doDispatch(cur, cmd);
259 InsetCommand::string2params(to_utf8(cmd.argument()), p);
260 if (!p.getCmdName().empty()) {
262 InsetListingsParams new_params(to_utf8(p["lstparams"]));
263 docstring const new_label =
264 from_utf8(new_params.getParamValue("label"));
266 if (new_label.empty()) {
272 old_label = label_->getParam("name");
274 label_ = createLabel(buffer_, new_label);
275 label_->setBuffer(buffer());
278 if (new_label != old_label) {
279 label_->updateLabelAndRefs(new_label, &cur);
280 // the label might have been adapted (duplicate)
281 if (new_label != label_->getParam("name")) {
282 new_params.addParam("label", "{" +
283 to_utf8(label_->getParam("name")) + "}", true);
284 p["lstparams"] = from_utf8(new_params.params());
291 cur.forceBufferUpdate();
293 cur.noScreenUpdate();
297 //pass everything else up the chain
299 InsetCommand::doDispatch(cur, cmd);
305 void InsetInclude::editIncluded(string const & file)
307 string const ext = support::getExtension(file);
309 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
312 // tex file or other text file in verbatim mode
313 formats.edit(buffer(),
314 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
319 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
320 FuncStatus & flag) const
322 switch (cmd.action()) {
324 case LFUN_INSET_EDIT:
325 flag.setEnabled(true);
328 case LFUN_INSET_MODIFY:
329 if (cmd.getArg(0) == "changetype")
330 return InsetCommand::getStatus(cur, cmd, flag);
332 flag.setEnabled(true);
336 return InsetCommand::getStatus(cur, cmd, flag);
341 void InsetInclude::setParams(InsetCommandParams const & p)
343 // invalidate the cache
346 InsetCommand::setParams(p);
349 if (preview_->monitoring())
350 preview_->stopMonitoring();
352 if (type(params()) == INPUT)
353 add_preview(*preview_, *this, buffer());
355 buffer().invalidateBibfileCache();
359 bool InsetInclude::isChildIncluded() const
361 std::list<std::string> includeonlys =
362 buffer().params().getIncludedChildren();
363 if (includeonlys.empty())
365 return (std::find(includeonlys.begin(),
367 to_utf8(params()["filename"])) != includeonlys.end());
371 docstring InsetInclude::screenLabel() const
375 switch (type(params())) {
377 temp = buffer().B_("Input");
380 temp = buffer().B_("Verbatim Input");
383 temp = buffer().B_("Verbatim Input*");
386 if (isChildIncluded())
387 temp = buffer().B_("Include");
389 temp += buffer().B_("Include (excluded)");
392 temp = listings_label_;
395 LASSERT(false, temp = buffer().B_("Unknown"));
401 if (params()["filename"].empty())
404 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
410 Buffer * InsetInclude::getChildBuffer() const
412 Buffer * childBuffer = loadIfNeeded();
414 // FIXME RECURSIVE INCLUDE
415 // This isn't sufficient, as the inclusion could be downstream.
416 // But it'll have to do for now.
417 return (childBuffer == &buffer()) ? 0 : childBuffer;
421 Buffer * InsetInclude::loadIfNeeded() const
423 // This is for background export and preview. We don't even want to
424 // try to load the cloned child document again.
425 if (buffer().isClone())
426 return child_buffer_;
428 // Don't try to load it again if we failed before.
429 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
432 FileName const included_file = includedFileName(buffer(), params());
433 // Use cached Buffer if possible.
434 if (child_buffer_ != 0) {
435 if (theBufferList().isLoaded(child_buffer_)
436 // additional sanity check: make sure the Buffer really is
437 // associated with the file we want.
438 && child_buffer_ == theBufferList().getBuffer(included_file))
439 return child_buffer_;
440 // Buffer vanished, so invalidate cache and try to reload.
444 if (!isLyXFileName(included_file.absFileName()))
447 Buffer * child = theBufferList().getBuffer(included_file);
449 // the readonly flag can/will be wrong, not anymore I think.
450 if (!included_file.exists())
453 child = theBufferList().newBuffer(included_file.absFileName());
455 // Buffer creation is not possible.
458 // Set parent before loading, such that macros can be tracked
459 child->setParent(&buffer());
461 if (child->loadLyXFile() != Buffer::ReadSuccess) {
462 failedtoload_ = true;
464 //close the buffer we just opened
465 theBufferList().release(child);
469 if (!child->errorList("Parse").empty()) {
470 // FIXME: Do something.
473 // The file was already loaded, so, simply
474 // inform parent buffer about local macros.
475 Buffer const * parent = &buffer();
476 child->setParent(parent);
478 child->listMacroNames(macros);
479 MacroNameSet::const_iterator cit = macros.begin();
480 MacroNameSet::const_iterator end = macros.end();
481 for (; cit != end; ++cit)
482 parent->usermacros.insert(*cit);
485 // Cache the child buffer.
486 child_buffer_ = child;
491 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
493 string incfile = to_utf8(params()["filename"]);
495 // Do nothing if no file name has been specified
499 FileName const included_file = includedFileName(buffer(), params());
501 // Check we're not trying to include ourselves.
502 // FIXME RECURSIVE INCLUDE
503 // This isn't sufficient, as the inclusion could be downstream.
504 // But it'll have to do for now.
505 if (isInputOrInclude(params()) &&
506 buffer().absFileName() == included_file.absFileName())
508 Alert::error(_("Recursive input"),
509 bformat(_("Attempted to include file %1$s in itself! "
510 "Ignoring inclusion."), from_utf8(incfile)));
514 Buffer const * const masterBuffer = buffer().masterBuffer();
516 // if incfile is relative, make it relative to the master
518 if (!FileName::isAbsolute(incfile)) {
520 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
521 from_utf8(masterBuffer->filePath())));
524 string exppath = incfile;
525 if (!runparams.export_folder.empty()) {
526 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
527 FileName(exppath).onlyPath().createPath();
530 // write it to a file (so far the complete file)
534 if (type(params()) == LISTINGS) {
535 exportfile = exppath;
536 mangled = DocFileName(included_file).mangledFileName();
538 exportfile = changeExtension(exppath, ".tex");
539 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
545 else if (!runparams.silent)
546 ; // no warning wanted
547 else if (!isValidLaTeXFileName(incfile)) {
548 frontend::Alert::warning(_("Invalid filename"),
549 _("The following filename will cause troubles "
550 "when running the exported file through LaTeX: ") +
552 } else if (!isValidDVIFileName(incfile)) {
553 frontend::Alert::warning(_("Problematic filename for DVI"),
554 _("The following filename can cause troubles "
555 "when running the exported file through LaTeX "
556 "and opening the resulting DVI: ") +
557 from_utf8(incfile), true);
560 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
561 buffer().temppath() : masterBuffer->temppath()));
563 LYXERR(Debug::LATEX, "incfile:" << incfile);
564 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
565 LYXERR(Debug::LATEX, "writefile:" << writefile);
567 string const tex_format = flavor2format(runparams.flavor);
569 switch (type(params())) {
572 incfile = latex_path(incfile);
574 os << '\\' << from_ascii(params().getCmdName()) << '{'
575 << from_utf8(incfile) << '}';
579 runparams.exportdata->addExternalFile(tex_format, writefile,
582 // \input wants file with extension (default is .tex)
583 if (!isLyXFileName(included_file.absFileName())) {
584 incfile = latex_path(incfile);
586 os << '\\' << from_ascii(params().getCmdName())
587 << '{' << from_utf8(incfile) << '}';
589 incfile = changeExtension(incfile, ".tex");
590 incfile = latex_path(incfile);
592 os << '\\' << from_ascii(params().getCmdName())
593 << '{' << from_utf8(incfile) << '}';
598 runparams.exportdata->addExternalFile(tex_format, writefile,
600 os << '\\' << from_ascii(params().getCmdName());
601 string const opt = to_utf8(params()["lstparams"]);
602 // opt is set in QInclude dialog and should have passed validation.
603 InsetListingsParams params(opt);
604 if (!params.params().empty())
605 os << "[" << from_utf8(params.params()) << "]";
606 os << '{' << from_utf8(incfile) << '}';
610 runparams.exportdata->addExternalFile(tex_format, writefile,
613 // \include don't want extension and demands that the
614 // file really have .tex
615 incfile = changeExtension(incfile, string());
616 incfile = latex_path(incfile);
618 os << '\\' << from_ascii(params().getCmdName()) << '{'
619 << from_utf8(incfile) << '}';
626 if (runparams.inComment || runparams.dryrun)
627 // Don't try to load or copy the file if we're
628 // in a comment or doing a dryrun
631 if (isInputOrInclude(params()) &&
632 isLyXFileName(included_file.absFileName())) {
633 // if it's a LyX file and we're inputting or including,
634 // try to load it so we can write the associated latex
636 Buffer * tmp = loadIfNeeded();
638 if (!runparams.silent) {
639 docstring text = bformat(_("Could not load included "
641 "Please, check whether it actually exists."),
642 included_file.displayName());
643 Alert::warning(_("Missing included file"), text);
648 if (!runparams.silent) {
649 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
651 docstring text = bformat(_("Included file `%1$s'\n"
652 "has textclass `%2$s'\n"
653 "while parent file has textclass `%3$s'."),
654 included_file.displayName(),
655 from_utf8(tmp->params().documentClass().name()),
656 from_utf8(masterBuffer->params().documentClass().name()));
657 Alert::warning(_("Different textclasses"), text, true);
660 // Make sure modules used in child are all included in master
661 // FIXME It might be worth loading the children's modules into the master
662 // over in BufferParams rather than doing this check.
663 LayoutModuleList const masterModules = masterBuffer->params().getModules();
664 LayoutModuleList const childModules = tmp->params().getModules();
665 LayoutModuleList::const_iterator it = childModules.begin();
666 LayoutModuleList::const_iterator end = childModules.end();
667 for (; it != end; ++it) {
668 string const module = *it;
669 LayoutModuleList::const_iterator found =
670 find(masterModules.begin(), masterModules.end(), module);
671 if (found == masterModules.end()) {
672 docstring text = bformat(_("Included file `%1$s'\n"
673 "uses module `%2$s'\n"
674 "which is not used in parent file."),
675 included_file.displayName(), from_utf8(module));
676 Alert::warning(_("Module not found"), text);
681 tmp->markDepClean(masterBuffer->temppath());
683 // Don't assume the child's format is latex
684 string const inc_format = tmp->params().bufferFormat();
685 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
686 formats.extension(inc_format)));
688 // FIXME: handle non existing files
689 // The included file might be written in a different encoding
691 Encoding const * const oldEnc = runparams.encoding;
692 Language const * const oldLang = runparams.master_language;
693 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
694 // the children must be encoded in plain utf8!
695 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
696 encodings.fromLyXName("utf8-plain")
697 : &tmp->params().encoding();
698 runparams.master_language = buffer().params().language;
699 runparams.par_begin = 0;
700 runparams.par_end = tmp->paragraphs().size();
701 runparams.is_child = true;
702 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
703 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
704 if (!runparams.silent) {
705 docstring msg = bformat(_("Included file `%1$s' "
706 "was not exported correctly.\n "
707 "LaTeX export is probably incomplete."),
708 included_file.displayName());
709 ErrorList const & el = tmp->errorList("Export");
711 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
712 msg, el.begin()->error,
713 el.begin()->description);
714 throw ExceptionMessage(ErrorException, _("Error: "),
718 runparams.encoding = oldEnc;
719 runparams.master_language = oldLang;
720 runparams.is_child = false;
722 // If needed, use converters to produce a latex file from the child
723 if (tmpwritefile != writefile) {
726 theConverters().convert(tmp, tmpwritefile, writefile,
728 inc_format, tex_format, el);
730 if (!success && !runparams.silent) {
731 docstring msg = bformat(_("Included file `%1$s' "
732 "was not exported correctly.\n "
733 "LaTeX export is probably incomplete."),
734 included_file.displayName());
736 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
737 msg, el.begin()->error,
738 el.begin()->description);
739 throw ExceptionMessage(ErrorException, _("Error: "),
744 // In this case, it's not a LyX file, so we copy the file
745 // to the temp dir, so that .aux files etc. are not created
746 // in the original dir. Files included by this file will be
747 // found via either the environment variable TEXINPUTS, or
748 // input@path, see ../Buffer.cpp.
749 unsigned long const checksum_in = included_file.checksum();
750 unsigned long const checksum_out = writefile.checksum();
752 if (checksum_in != checksum_out) {
753 if (!included_file.copyTo(writefile)) {
756 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
757 "into the temporary directory."),
758 from_utf8(included_file.absFileName()))));
766 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
771 // For verbatim and listings, we just include the contents of the file as-is.
772 // In the case of listings, we wrap it in <pre>.
773 bool const listing = isListings(params());
774 if (listing || isVerbatim(params())) {
776 xs << html::StartTag("pre");
777 // FIXME: We don't know the encoding of the file, default to UTF-8.
778 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
780 xs << html::EndTag("pre");
784 // We don't (yet) know how to Input or Include non-LyX files.
785 // (If we wanted to get really arcane, we could run some tex2html
786 // converter on the included file. But that's just masochistic.)
787 FileName const included_file = includedFileName(buffer(), params());
788 if (!isLyXFileName(included_file.absFileName())) {
790 frontend::Alert::warning(_("Unsupported Inclusion"),
791 bformat(_("LyX does not know how to include non-LyX files when "
792 "generating HTML output. Offending file:\n%1$s"),
793 params()["filename"]));
797 // In the other cases, we will generate the HTML and include it.
799 // Check we're not trying to include ourselves.
800 // FIXME RECURSIVE INCLUDE
801 if (buffer().absFileName() == included_file.absFileName()) {
802 Alert::error(_("Recursive input"),
803 bformat(_("Attempted to include file %1$s in itself! "
804 "Ignoring inclusion."), params()["filename"]));
808 Buffer const * const ibuf = loadIfNeeded();
812 // are we generating only some paragraphs, or all of them?
813 bool const all_pars = !rp.dryrun ||
814 (rp.par_begin == 0 &&
815 rp.par_end == (int)buffer().text().paragraphs().size());
817 OutputParams op = rp;
821 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
823 xs << XHTMLStream::ESCAPE_NONE
824 << "<!-- Included file: "
825 << from_utf8(included_file.absFileName())
826 << XHTMLStream::ESCAPE_NONE
832 int InsetInclude::plaintext(odocstringstream & os,
833 OutputParams const & op, size_t) const
835 // just write the filename if we're making a tooltip or toc entry,
836 // or are generating this for advanced search
837 if (op.for_tooltip || op.for_toc || op.for_search) {
838 os << '[' << screenLabel() << '\n'
839 << getParam("filename") << "\n]";
840 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
843 if (isVerbatim(params()) || isListings(params())) {
844 os << '[' << screenLabel() << '\n'
845 // FIXME: We don't know the encoding of the file, default to UTF-8.
846 << includedFileName(buffer(), params()).fileContents("UTF-8")
848 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
851 Buffer const * const ibuf = loadIfNeeded();
853 docstring const str = '[' + screenLabel() + ']';
857 writePlaintextFile(*ibuf, os, op);
862 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
864 string incfile = to_utf8(params()["filename"]);
866 // Do nothing if no file name has been specified
870 string const included_file = includedFileName(buffer(), params()).absFileName();
872 // Check we're not trying to include ourselves.
873 // FIXME RECURSIVE INCLUDE
874 // This isn't sufficient, as the inclusion could be downstream.
875 // But it'll have to do for now.
876 if (buffer().absFileName() == included_file) {
877 Alert::error(_("Recursive input"),
878 bformat(_("Attempted to include file %1$s in itself! "
879 "Ignoring inclusion."), from_utf8(incfile)));
883 string exppath = incfile;
884 if (!runparams.export_folder.empty()) {
885 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
886 FileName(exppath).onlyPath().createPath();
889 // write it to a file (so far the complete file)
890 string const exportfile = changeExtension(exppath, ".sgml");
891 DocFileName writefile(changeExtension(included_file, ".sgml"));
893 Buffer * tmp = loadIfNeeded();
895 string const mangled = writefile.mangledFileName();
896 writefile = makeAbsPath(mangled,
897 buffer().masterBuffer()->temppath());
901 LYXERR(Debug::LATEX, "incfile:" << incfile);
902 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
903 LYXERR(Debug::LATEX, "writefile:" << writefile);
905 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
908 runparams.exportdata->addExternalFile("docbook", writefile,
910 runparams.exportdata->addExternalFile("docbook-xml", writefile,
913 if (isVerbatim(params()) || isListings(params())) {
914 os << "<inlinegraphic fileref=\""
915 << '&' << include_label << ';'
916 << "\" format=\"linespecific\">";
918 os << '&' << include_label << ';';
924 void InsetInclude::validate(LaTeXFeatures & features) const
926 LATTEST(&buffer() == &features.buffer());
928 string incfile = to_utf8(params()["filename"]);
929 string const included_file =
930 includedFileName(buffer(), params()).absFileName();
933 if (isLyXFileName(included_file))
934 writefile = changeExtension(included_file, ".sgml");
936 writefile = included_file;
938 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
939 incfile = DocFileName(writefile).mangledFileName();
940 writefile = makeAbsPath(incfile,
941 buffer().masterBuffer()->temppath()).absFileName();
944 features.includeFile(include_label, writefile);
946 features.useInsetLayout(getLayout());
947 if (isVerbatim(params()))
948 features.require("verbatim");
949 else if (isListings(params()))
950 features.require("listings");
952 // Here we must do the fun stuff...
953 // Load the file in the include if it needs
955 Buffer * const tmp = loadIfNeeded();
957 // the file is loaded
958 // make sure the buffer isn't us
959 // FIXME RECURSIVE INCLUDES
960 // This is not sufficient, as recursive includes could be
961 // more than a file away. But it will do for now.
962 if (tmp && tmp != &buffer()) {
963 // We must temporarily change features.buffer,
964 // otherwise it would always be the master buffer,
965 // and nested includes would not work.
966 features.setBuffer(*tmp);
967 // Maybe this is already a child
968 bool const is_child =
969 features.runparams().is_child;
970 features.runparams().is_child = true;
971 tmp->validate(features);
972 features.runparams().is_child = is_child;
973 features.setBuffer(buffer());
979 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
981 Buffer * child = loadIfNeeded();
984 // FIXME RECURSIVE INCLUDE
985 // This isn't sufficient, as the inclusion could be downstream.
986 // But it'll have to do for now.
987 if (child == &buffer())
989 child->collectBibKeys();
993 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
997 bool use_preview = false;
998 if (RenderPreview::previewText()) {
999 graphics::PreviewImage const * pimage =
1000 preview_->getPreviewImage(mi.base.bv->buffer());
1001 use_preview = pimage && pimage->image();
1005 preview_->metrics(mi, dim);
1009 button_.update(screenLabel(), true);
1011 button_.metrics(mi, dim);
1014 Box b(0, dim.wid, -dim.asc, dim.des);
1019 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1021 LBUFERR(pi.base.bv);
1023 bool use_preview = false;
1024 if (RenderPreview::previewText()) {
1025 graphics::PreviewImage const * pimage =
1026 preview_->getPreviewImage(pi.base.bv->buffer());
1027 use_preview = pimage && pimage->image();
1031 preview_->draw(pi, x, y);
1033 button_.draw(pi, x, y);
1037 void InsetInclude::write(ostream & os) const
1039 params().Write(os, &buffer());
1043 string InsetInclude::contextMenuName() const
1045 return "context-include";
1049 Inset::DisplayType InsetInclude::display() const
1051 return type(params()) == INPUT ? Inline : AlignCenter;
1055 docstring InsetInclude::layoutName() const
1057 if (isListings(params()))
1058 return from_ascii("IncludeListings");
1059 return InsetCommand::layoutName();
1067 void InsetInclude::fileChanged() const
1069 Buffer const * const buffer = updateFrontend();
1073 preview_->removePreview(*buffer);
1074 add_preview(*preview_, *this, *buffer);
1075 preview_->startLoading(*buffer);
1081 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1083 FileName const included_file = includedFileName(buffer, params);
1085 return type(params) == INPUT && params.preview() &&
1086 included_file.isReadableFile();
1090 docstring latexString(InsetInclude const & inset)
1092 odocstringstream ods;
1094 // We don't need to set runparams.encoding since this will be done
1095 // by latex() anyway.
1096 OutputParams runparams(0);
1097 runparams.flavor = OutputParams::LATEX;
1098 runparams.for_preview = true;
1099 inset.latex(os, runparams);
1105 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1106 Buffer const & buffer)
1108 InsetCommandParams const & params = inset.params();
1109 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1110 renderer.setAbsFile(includedFileName(buffer, params));
1111 docstring const snippet = latexString(inset);
1112 renderer.addPreview(snippet, buffer);
1119 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1120 graphics::PreviewLoader & ploader) const
1122 Buffer const & buffer = ploader.buffer();
1123 if (!preview_wanted(params(), buffer))
1125 preview_->setAbsFile(includedFileName(buffer, params()));
1126 docstring const snippet = latexString(*this);
1127 preview_->addPreview(snippet, ploader);
1131 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1132 UpdateType utype) const
1134 TocBackend & backend = buffer().tocBackend();
1136 if (isListings(params())) {
1138 label_->addToToc(cpit, output_active, utype);
1140 InsetListingsParams p(to_utf8(params()["lstparams"]));
1141 string caption = p.getParamValue("caption");
1142 if (caption.empty())
1144 shared_ptr<Toc> toc = backend.toc("listing");
1145 docstring str = convert<docstring>(toc->size() + 1)
1146 + ". " + from_utf8(caption);
1147 DocIterator pit = cpit;
1148 toc->push_back(TocItem(pit, 0, str, output_active));
1150 Buffer const * const childbuffer = getChildBuffer();
1154 shared_ptr<Toc> toc = backend.toc("child");
1155 docstring str = childbuffer->fileName().displayName();
1156 toc->push_back(TocItem(cpit, 0, str, output_active));
1158 childbuffer->tocBackend().update(output_active, utype);
1159 TocList const & childtoclist = childbuffer->tocBackend().tocs();
1160 TocList::const_iterator it = childtoclist.begin();
1161 TocList::const_iterator const end = childtoclist.end();
1162 for(; it != end; ++it) {
1163 shared_ptr<Toc> toc = backend.toc(it->first);
1164 toc->insert(toc->end(), it->second->begin(), it->second->end());
1170 void InsetInclude::updateCommand()
1175 docstring old_label = label_->getParam("name");
1176 label_->updateLabel(old_label);
1177 // the label might have been adapted (duplicate)
1178 docstring new_label = label_->getParam("name");
1179 if (old_label == new_label)
1182 // update listings parameters...
1183 InsetCommandParams p(INCLUDE_CODE);
1185 InsetListingsParams par(to_utf8(params()["lstparams"]));
1186 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1187 p["lstparams"] = from_utf8(par.params());
1192 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1194 button_.update(screenLabel(), true);
1196 Buffer const * const childbuffer = getChildBuffer();
1198 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1201 if (!isListings(params()))
1205 label_->updateBuffer(it, utype);
1207 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1208 if (par.getParamValue("caption").empty()) {
1209 listings_label_ = buffer().B_("Program Listing");
1212 Buffer const & master = *buffer().masterBuffer();
1213 Counters & counters = master.params().documentClass().counters();
1214 docstring const cnt = from_ascii("listing");
1215 listings_label_ = master.B_("Program Listing");
1216 if (counters.hasCounter(cnt)) {
1217 counters.step(cnt, utype);
1218 listings_label_ += " " + convert<docstring>(counters.value(cnt));