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 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
661 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
662 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
663 docstring text = bformat(_("Included file `%1$s'\n"
664 "has use-non-TeX-fonts set to `%2$s'\n"
665 "while parent file has use-non-TeX-fonts set to `%3$s'."),
666 included_file.displayName(),
668 from_utf8(master_tf));
669 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
672 // Make sure modules used in child are all included in master
673 // FIXME It might be worth loading the children's modules into the master
674 // over in BufferParams rather than doing this check.
675 LayoutModuleList const masterModules = masterBuffer->params().getModules();
676 LayoutModuleList const childModules = tmp->params().getModules();
677 LayoutModuleList::const_iterator it = childModules.begin();
678 LayoutModuleList::const_iterator end = childModules.end();
679 for (; it != end; ++it) {
680 string const module = *it;
681 LayoutModuleList::const_iterator found =
682 find(masterModules.begin(), masterModules.end(), module);
683 if (found == masterModules.end()) {
684 docstring text = bformat(_("Included file `%1$s'\n"
685 "uses module `%2$s'\n"
686 "which is not used in parent file."),
687 included_file.displayName(), from_utf8(module));
688 Alert::warning(_("Module not found"), text);
693 tmp->markDepClean(masterBuffer->temppath());
695 // Don't assume the child's format is latex
696 string const inc_format = tmp->params().bufferFormat();
697 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
698 formats.extension(inc_format)));
700 // FIXME: handle non existing files
701 // The included file might be written in a different encoding
703 Encoding const * const oldEnc = runparams.encoding;
704 Language const * const oldLang = runparams.master_language;
705 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
706 // the children must be encoded in plain utf8!
707 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
708 encodings.fromLyXName("utf8-plain")
709 : &tmp->params().encoding();
710 runparams.master_language = buffer().params().language;
711 runparams.par_begin = 0;
712 runparams.par_end = tmp->paragraphs().size();
713 runparams.is_child = true;
714 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
715 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
716 if (!runparams.silent) {
717 docstring msg = bformat(_("Included file `%1$s' "
718 "was not exported correctly.\n "
719 "LaTeX export is probably incomplete."),
720 included_file.displayName());
721 ErrorList const & el = tmp->errorList("Export");
723 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
724 msg, el.begin()->error,
725 el.begin()->description);
726 throw ExceptionMessage(ErrorException, _("Error: "),
730 runparams.encoding = oldEnc;
731 runparams.master_language = oldLang;
732 runparams.is_child = false;
734 // If needed, use converters to produce a latex file from the child
735 if (tmpwritefile != writefile) {
738 theConverters().convert(tmp, tmpwritefile, writefile,
740 inc_format, tex_format, el);
742 if (!success && !runparams.silent) {
743 docstring msg = bformat(_("Included file `%1$s' "
744 "was not exported correctly.\n "
745 "LaTeX export is probably incomplete."),
746 included_file.displayName());
748 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
749 msg, el.begin()->error,
750 el.begin()->description);
751 throw ExceptionMessage(ErrorException, _("Error: "),
756 // In this case, it's not a LyX file, so we copy the file
757 // to the temp dir, so that .aux files etc. are not created
758 // in the original dir. Files included by this file will be
759 // found via either the environment variable TEXINPUTS, or
760 // input@path, see ../Buffer.cpp.
761 unsigned long const checksum_in = included_file.checksum();
762 unsigned long const checksum_out = writefile.checksum();
764 if (checksum_in != checksum_out) {
765 if (!included_file.copyTo(writefile)) {
768 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
769 "into the temporary directory."),
770 from_utf8(included_file.absFileName()))));
778 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
783 // For verbatim and listings, we just include the contents of the file as-is.
784 // In the case of listings, we wrap it in <pre>.
785 bool const listing = isListings(params());
786 if (listing || isVerbatim(params())) {
788 xs << html::StartTag("pre");
789 // FIXME: We don't know the encoding of the file, default to UTF-8.
790 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
792 xs << html::EndTag("pre");
796 // We don't (yet) know how to Input or Include non-LyX files.
797 // (If we wanted to get really arcane, we could run some tex2html
798 // converter on the included file. But that's just masochistic.)
799 FileName const included_file = includedFileName(buffer(), params());
800 if (!isLyXFileName(included_file.absFileName())) {
802 frontend::Alert::warning(_("Unsupported Inclusion"),
803 bformat(_("LyX does not know how to include non-LyX files when "
804 "generating HTML output. Offending file:\n%1$s"),
805 params()["filename"]));
809 // In the other cases, we will generate the HTML and include it.
811 // Check we're not trying to include ourselves.
812 // FIXME RECURSIVE INCLUDE
813 if (buffer().absFileName() == included_file.absFileName()) {
814 Alert::error(_("Recursive input"),
815 bformat(_("Attempted to include file %1$s in itself! "
816 "Ignoring inclusion."), params()["filename"]));
820 Buffer const * const ibuf = loadIfNeeded();
824 // are we generating only some paragraphs, or all of them?
825 bool const all_pars = !rp.dryrun ||
826 (rp.par_begin == 0 &&
827 rp.par_end == (int)buffer().text().paragraphs().size());
829 OutputParams op = rp;
833 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
835 xs << XHTMLStream::ESCAPE_NONE
836 << "<!-- Included file: "
837 << from_utf8(included_file.absFileName())
838 << XHTMLStream::ESCAPE_NONE
844 int InsetInclude::plaintext(odocstringstream & os,
845 OutputParams const & op, size_t) const
847 // just write the filename if we're making a tooltip or toc entry,
848 // or are generating this for advanced search
849 if (op.for_tooltip || op.for_toc || op.for_search) {
850 os << '[' << screenLabel() << '\n'
851 << getParam("filename") << "\n]";
852 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
855 if (isVerbatim(params()) || isListings(params())) {
856 os << '[' << screenLabel() << '\n'
857 // FIXME: We don't know the encoding of the file, default to UTF-8.
858 << includedFileName(buffer(), params()).fileContents("UTF-8")
860 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
863 Buffer const * const ibuf = loadIfNeeded();
865 docstring const str = '[' + screenLabel() + ']';
869 writePlaintextFile(*ibuf, os, op);
874 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
876 string incfile = to_utf8(params()["filename"]);
878 // Do nothing if no file name has been specified
882 string const included_file = includedFileName(buffer(), params()).absFileName();
884 // Check we're not trying to include ourselves.
885 // FIXME RECURSIVE INCLUDE
886 // This isn't sufficient, as the inclusion could be downstream.
887 // But it'll have to do for now.
888 if (buffer().absFileName() == included_file) {
889 Alert::error(_("Recursive input"),
890 bformat(_("Attempted to include file %1$s in itself! "
891 "Ignoring inclusion."), from_utf8(incfile)));
895 string exppath = incfile;
896 if (!runparams.export_folder.empty()) {
897 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
898 FileName(exppath).onlyPath().createPath();
901 // write it to a file (so far the complete file)
902 string const exportfile = changeExtension(exppath, ".sgml");
903 DocFileName writefile(changeExtension(included_file, ".sgml"));
905 Buffer * tmp = loadIfNeeded();
907 string const mangled = writefile.mangledFileName();
908 writefile = makeAbsPath(mangled,
909 buffer().masterBuffer()->temppath());
913 LYXERR(Debug::LATEX, "incfile:" << incfile);
914 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
915 LYXERR(Debug::LATEX, "writefile:" << writefile);
917 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
920 runparams.exportdata->addExternalFile("docbook", writefile,
922 runparams.exportdata->addExternalFile("docbook-xml", writefile,
925 if (isVerbatim(params()) || isListings(params())) {
926 os << "<inlinegraphic fileref=\""
927 << '&' << include_label << ';'
928 << "\" format=\"linespecific\">";
930 os << '&' << include_label << ';';
936 void InsetInclude::validate(LaTeXFeatures & features) const
938 LATTEST(&buffer() == &features.buffer());
940 string incfile = to_utf8(params()["filename"]);
941 string const included_file =
942 includedFileName(buffer(), params()).absFileName();
945 if (isLyXFileName(included_file))
946 writefile = changeExtension(included_file, ".sgml");
948 writefile = included_file;
950 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
951 incfile = DocFileName(writefile).mangledFileName();
952 writefile = makeAbsPath(incfile,
953 buffer().masterBuffer()->temppath()).absFileName();
956 features.includeFile(include_label, writefile);
958 features.useInsetLayout(getLayout());
959 if (isVerbatim(params()))
960 features.require("verbatim");
961 else if (isListings(params()))
962 features.require("listings");
964 // Here we must do the fun stuff...
965 // Load the file in the include if it needs
967 Buffer * const tmp = loadIfNeeded();
969 // the file is loaded
970 // make sure the buffer isn't us
971 // FIXME RECURSIVE INCLUDES
972 // This is not sufficient, as recursive includes could be
973 // more than a file away. But it will do for now.
974 if (tmp && tmp != &buffer()) {
975 // We must temporarily change features.buffer,
976 // otherwise it would always be the master buffer,
977 // and nested includes would not work.
978 features.setBuffer(*tmp);
979 // Maybe this is already a child
980 bool const is_child =
981 features.runparams().is_child;
982 features.runparams().is_child = true;
983 tmp->validate(features);
984 features.runparams().is_child = is_child;
985 features.setBuffer(buffer());
991 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
993 Buffer * child = loadIfNeeded();
996 // FIXME RECURSIVE INCLUDE
997 // This isn't sufficient, as the inclusion could be downstream.
998 // But it'll have to do for now.
999 if (child == &buffer())
1001 child->collectBibKeys();
1005 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1007 LBUFERR(mi.base.bv);
1009 bool use_preview = false;
1010 if (RenderPreview::previewText()) {
1011 graphics::PreviewImage const * pimage =
1012 preview_->getPreviewImage(mi.base.bv->buffer());
1013 use_preview = pimage && pimage->image();
1017 preview_->metrics(mi, dim);
1021 button_.update(screenLabel(), true);
1023 button_.metrics(mi, dim);
1026 Box b(0, dim.wid, -dim.asc, dim.des);
1031 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1033 LBUFERR(pi.base.bv);
1035 bool use_preview = false;
1036 if (RenderPreview::previewText()) {
1037 graphics::PreviewImage const * pimage =
1038 preview_->getPreviewImage(pi.base.bv->buffer());
1039 use_preview = pimage && pimage->image();
1043 preview_->draw(pi, x, y);
1045 button_.draw(pi, x, y);
1049 void InsetInclude::write(ostream & os) const
1051 params().Write(os, &buffer());
1055 string InsetInclude::contextMenuName() const
1057 return "context-include";
1061 Inset::DisplayType InsetInclude::display() const
1063 return type(params()) == INPUT ? Inline : AlignCenter;
1067 docstring InsetInclude::layoutName() const
1069 if (isListings(params()))
1070 return from_ascii("IncludeListings");
1071 return InsetCommand::layoutName();
1079 void InsetInclude::fileChanged() const
1081 Buffer const * const buffer = updateFrontend();
1085 preview_->removePreview(*buffer);
1086 add_preview(*preview_, *this, *buffer);
1087 preview_->startLoading(*buffer);
1093 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1095 FileName const included_file = includedFileName(buffer, params);
1097 return type(params) == INPUT && params.preview() &&
1098 included_file.isReadableFile();
1102 docstring latexString(InsetInclude const & inset)
1104 odocstringstream ods;
1106 // We don't need to set runparams.encoding since this will be done
1107 // by latex() anyway.
1108 OutputParams runparams(0);
1109 runparams.flavor = OutputParams::LATEX;
1110 runparams.for_preview = true;
1111 inset.latex(os, runparams);
1117 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1118 Buffer const & buffer)
1120 InsetCommandParams const & params = inset.params();
1121 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1122 renderer.setAbsFile(includedFileName(buffer, params));
1123 docstring const snippet = latexString(inset);
1124 renderer.addPreview(snippet, buffer);
1131 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1132 graphics::PreviewLoader & ploader) const
1134 Buffer const & buffer = ploader.buffer();
1135 if (!preview_wanted(params(), buffer))
1137 preview_->setAbsFile(includedFileName(buffer, params()));
1138 docstring const snippet = latexString(*this);
1139 preview_->addPreview(snippet, ploader);
1143 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1144 UpdateType utype, TocBackend & backend) const
1146 if (isListings(params())) {
1148 label_->addToToc(cpit, output_active, utype, backend);
1149 TocBuilder & b = backend.builder("listing");
1150 b.pushItem(cpit, screenLabel(), output_active);
1151 InsetListingsParams p(to_utf8(params()["lstparams"]));
1152 b.argumentItem(from_utf8(p.getParamValue("caption")));
1155 Buffer const * const childbuffer = getChildBuffer();
1157 TocBuilder & b = backend.builder("child");
1158 docstring str = childbuffer ? childbuffer->fileName().displayName()
1160 b.pushItem(cpit, str, output_active);
1166 // Include Tocs from children
1167 childbuffer->inset().addToToc(cpit, output_active, utype, backend);
1168 //Copy missing outliner names (though the user has been warned against
1169 //having different document class and module selection between master
1171 for (pair<string, docstring> const & name
1172 : childbuffer->params().documentClass().outlinerNames())
1173 backend.addName(name.first, translateIfPossible(name.second));
1178 void InsetInclude::updateCommand()
1183 docstring old_label = label_->getParam("name");
1184 label_->updateLabel(old_label);
1185 // the label might have been adapted (duplicate)
1186 docstring new_label = label_->getParam("name");
1187 if (old_label == new_label)
1190 // update listings parameters...
1191 InsetCommandParams p(INCLUDE_CODE);
1193 InsetListingsParams par(to_utf8(params()["lstparams"]));
1194 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1195 p["lstparams"] = from_utf8(par.params());
1200 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1202 button_.update(screenLabel(), true);
1204 Buffer const * const childbuffer = getChildBuffer();
1206 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1209 if (!isListings(params()))
1213 label_->updateBuffer(it, utype);
1215 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1216 if (par.getParamValue("caption").empty()) {
1217 listings_label_ = buffer().B_("Program Listing");
1220 Buffer const & master = *buffer().masterBuffer();
1221 Counters & counters = master.params().documentClass().counters();
1222 docstring const cnt = from_ascii("listing");
1223 listings_label_ = master.B_("Program Listing");
1224 if (counters.hasCounter(cnt)) {
1225 counters.step(cnt, utype);
1226 listings_label_ += " " + convert<docstring>(counters.value(cnt));