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" || s == "inputminted")
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_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
174 set_label_(false), label_(0), child_buffer_(0)
176 preview_->connect([=](){ fileChanged(); });
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_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
189 set_label_(false), label_(0), child_buffer_(0)
191 preview_->connect([=](){ fileChanged(); });
194 label_ = new InsetLabel(*other.label_);
198 InsetInclude::~InsetInclude()
200 if (isBufferLoaded())
201 /* We do not use buffer() because Coverity believes that this
202 * may throw an exception. Actually this code path is not
203 * taken when buffer_ == 0 */
204 buffer_->invalidateBibfileCache();
209 void InsetInclude::setBuffer(Buffer & buffer)
211 InsetCommand::setBuffer(buffer);
213 label_->setBuffer(buffer);
217 void InsetInclude::setChildBuffer(Buffer * buffer)
219 child_buffer_ = buffer;
223 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
226 // This is only correct for the case of listings, but it'll do for now.
227 // In the other cases, this second parameter should just be empty.
228 static ParamInfo param_info_;
229 if (param_info_.empty()) {
230 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
231 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
237 bool InsetInclude::isCompatibleCommand(string const & s)
239 return type(s) != NONE;
243 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
245 switch (cmd.action()) {
247 case LFUN_INSET_EDIT: {
248 editIncluded(to_utf8(params()["filename"]));
252 case LFUN_INSET_MODIFY: {
253 // It should be OK just to invalidate the cache in setParams()
255 // child_buffer_ = 0;
256 InsetCommandParams p(INCLUDE_CODE);
257 if (cmd.getArg(0) == "changetype") {
259 InsetCommand::doDispatch(cur, cmd);
262 InsetCommand::string2params(to_utf8(cmd.argument()), p);
263 if (!p.getCmdName().empty()) {
265 InsetListingsParams new_params(to_utf8(p["lstparams"]));
266 docstring const new_label =
267 from_utf8(new_params.getParamValue("label"));
269 if (new_label.empty()) {
275 old_label = label_->getParam("name");
277 label_ = createLabel(buffer_, new_label);
278 label_->setBuffer(buffer());
281 if (new_label != old_label) {
282 label_->updateLabelAndRefs(new_label, &cur);
283 // the label might have been adapted (duplicate)
284 if (new_label != label_->getParam("name")) {
285 new_params.addParam("label", "{" +
286 to_utf8(label_->getParam("name")) + "}", true);
287 p["lstparams"] = from_utf8(new_params.params());
294 cur.forceBufferUpdate();
296 cur.noScreenUpdate();
300 //pass everything else up the chain
302 InsetCommand::doDispatch(cur, cmd);
308 void InsetInclude::editIncluded(string const & file)
310 string const ext = support::getExtension(file);
312 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
315 // tex file or other text file in verbatim mode
316 theFormats().edit(buffer(),
317 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
322 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
323 FuncStatus & flag) const
325 switch (cmd.action()) {
327 case LFUN_INSET_EDIT:
328 flag.setEnabled(true);
331 case LFUN_INSET_MODIFY:
332 if (cmd.getArg(0) == "changetype")
333 return InsetCommand::getStatus(cur, cmd, flag);
335 flag.setEnabled(true);
339 return InsetCommand::getStatus(cur, cmd, flag);
344 void InsetInclude::setParams(InsetCommandParams const & p)
346 // invalidate the cache
349 InsetCommand::setParams(p);
352 if (preview_->monitoring())
353 preview_->stopMonitoring();
355 if (type(params()) == INPUT)
356 add_preview(*preview_, *this, buffer());
358 buffer().invalidateBibfileCache();
362 bool InsetInclude::isChildIncluded() const
364 std::list<std::string> includeonlys =
365 buffer().params().getIncludedChildren();
366 if (includeonlys.empty())
368 return (std::find(includeonlys.begin(),
370 to_utf8(params()["filename"])) != includeonlys.end());
374 docstring InsetInclude::screenLabel() const
378 switch (type(params())) {
380 temp = buffer().B_("Input");
383 temp = buffer().B_("Verbatim Input");
386 temp = buffer().B_("Verbatim Input*");
389 if (isChildIncluded())
390 temp = buffer().B_("Include");
392 temp += buffer().B_("Include (excluded)");
395 temp = listings_label_;
398 LASSERT(false, temp = buffer().B_("Unknown"));
404 if (params()["filename"].empty())
407 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
413 Buffer * InsetInclude::getChildBuffer() const
415 Buffer * childBuffer = loadIfNeeded();
417 // FIXME RECURSIVE INCLUDE
418 // This isn't sufficient, as the inclusion could be downstream.
419 // But it'll have to do for now.
420 return (childBuffer == &buffer()) ? 0 : childBuffer;
424 Buffer * InsetInclude::loadIfNeeded() const
426 // This is for background export and preview. We don't even want to
427 // try to load the cloned child document again.
428 if (buffer().isClone())
429 return child_buffer_;
431 // Don't try to load it again if we failed before.
432 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
435 FileName const included_file = includedFileName(buffer(), params());
436 // Use cached Buffer if possible.
437 if (child_buffer_ != 0) {
438 if (theBufferList().isLoaded(child_buffer_)
439 // additional sanity check: make sure the Buffer really is
440 // associated with the file we want.
441 && child_buffer_ == theBufferList().getBuffer(included_file))
442 return child_buffer_;
443 // Buffer vanished, so invalidate cache and try to reload.
447 if (!isLyXFileName(included_file.absFileName()))
450 Buffer * child = theBufferList().getBuffer(included_file);
452 // the readonly flag can/will be wrong, not anymore I think.
453 if (!included_file.exists())
456 child = theBufferList().newBuffer(included_file.absFileName());
458 // Buffer creation is not possible.
461 // Set parent before loading, such that macros can be tracked
462 child->setParent(&buffer());
464 if (child->loadLyXFile() != Buffer::ReadSuccess) {
465 failedtoload_ = true;
467 //close the buffer we just opened
468 theBufferList().release(child);
472 if (!child->errorList("Parse").empty()) {
473 // FIXME: Do something.
476 // The file was already loaded, so, simply
477 // inform parent buffer about local macros.
478 Buffer const * parent = &buffer();
479 child->setParent(parent);
481 child->listMacroNames(macros);
482 MacroNameSet::const_iterator cit = macros.begin();
483 MacroNameSet::const_iterator end = macros.end();
484 for (; cit != end; ++cit)
485 parent->usermacros.insert(*cit);
488 // Cache the child buffer.
489 child_buffer_ = child;
494 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
496 string incfile = to_utf8(params()["filename"]);
498 // Do nothing if no file name has been specified
502 FileName const included_file = includedFileName(buffer(), params());
504 // Check we're not trying to include ourselves.
505 // FIXME RECURSIVE INCLUDE
506 // This isn't sufficient, as the inclusion could be downstream.
507 // But it'll have to do for now.
508 if (isInputOrInclude(params()) &&
509 buffer().absFileName() == included_file.absFileName())
511 Alert::error(_("Recursive input"),
512 bformat(_("Attempted to include file %1$s in itself! "
513 "Ignoring inclusion."), from_utf8(incfile)));
517 Buffer const * const masterBuffer = buffer().masterBuffer();
519 // if incfile is relative, make it relative to the master
521 if (!FileName::isAbsolute(incfile)) {
523 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
524 from_utf8(masterBuffer->filePath())));
527 string exppath = incfile;
528 if (!runparams.export_folder.empty()) {
529 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
530 FileName(exppath).onlyPath().createPath();
533 // write it to a file (so far the complete file)
537 if (type(params()) == LISTINGS) {
538 exportfile = exppath;
539 mangled = DocFileName(included_file).mangledFileName();
541 exportfile = changeExtension(exppath, ".tex");
542 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
548 else if (!runparams.silent)
549 ; // no warning wanted
550 else if (!isValidLaTeXFileName(incfile)) {
551 frontend::Alert::warning(_("Invalid filename"),
552 _("The following filename will cause troubles "
553 "when running the exported file through LaTeX: ") +
555 } else if (!isValidDVIFileName(incfile)) {
556 frontend::Alert::warning(_("Problematic filename for DVI"),
557 _("The following filename can cause troubles "
558 "when running the exported file through LaTeX "
559 "and opening the resulting DVI: ") +
560 from_utf8(incfile), true);
563 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
564 buffer().temppath() : masterBuffer->temppath()));
566 LYXERR(Debug::LATEX, "incfile:" << incfile);
567 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
568 LYXERR(Debug::LATEX, "writefile:" << writefile);
570 string const tex_format = flavor2format(runparams.flavor);
572 switch (type(params())) {
575 incfile = latex_path(incfile);
577 os << '\\' << from_ascii(params().getCmdName()) << '{'
578 << from_utf8(incfile) << '}';
582 runparams.exportdata->addExternalFile(tex_format, writefile,
585 // \input wants file with extension (default is .tex)
586 if (!isLyXFileName(included_file.absFileName())) {
587 incfile = latex_path(incfile);
589 os << '\\' << from_ascii(params().getCmdName())
590 << '{' << from_utf8(incfile) << '}';
592 incfile = changeExtension(incfile, ".tex");
593 incfile = latex_path(incfile);
595 os << '\\' << from_ascii(params().getCmdName())
596 << '{' << from_utf8(incfile) << '}';
601 // Here, listings and minted have sligthly different behaviors.
602 // Using listings, it is always possible to have a caption,
603 // even for non-floats. Using minted, only floats can have a
604 // caption. So, with minted we use the following strategy.
605 // If a caption was specified but the float parameter was not,
606 // we ourselves add a caption above the listing (because the
607 // listing comes from a file and might span several pages).
608 // Otherwise, if float was specified, the floating listing
609 // environment provided by minted is used. In either case, the
610 // label parameter is taken as the label by which the float
611 // can be referenced, otherwise it will have the meaning
612 // intended by minted. In this last case, the label will
613 // serve as a sort of caption that, however, will be shown
614 // by minted only if the frame parameter is also specified.
615 bool const use_minted = buffer().params().use_minted;
616 runparams.exportdata->addExternalFile(tex_format, writefile,
618 string const opt = to_utf8(params()["lstparams"]);
619 // opt is set in QInclude dialog and should have passed validation.
620 InsetListingsParams lstparams(opt);
621 string parameters = lstparams.params();
626 bool isfloat = lstparams.isFloat();
628 // Get float placement, language, caption, and
629 // label, then remove the relative options.
630 vector<string> opts =
631 getVectorFromString(parameters, ",", false);
632 for (size_t i = 0; i < opts.size(); ++i) {
633 if (prefixIs(opts[i], "float")) {
634 if (prefixIs(opts[i], "float="))
635 placement = opts[i].substr(6);
636 opts.erase(opts.begin() + i--);
637 } else if (prefixIs(opts[i], "language=")) {
638 language = opts[i].substr(9);
639 opts.erase(opts.begin() + i--);
640 } else if (prefixIs(opts[i], "caption=")) {
641 caption = opts[i].substr(8);
642 opts.erase(opts.begin() + i--);
643 } else if (prefixIs(opts[i], "label=")) {
644 label = opts[i].substr(6);
645 opts.erase(opts.begin() + i--);
648 if (!label.empty()) {
649 if (isfloat || !caption.empty())
650 label = trim(label, "{}");
652 opts.push_back("label=" + label);
654 parameters = getStringFromVector(opts, ",");
656 if (language.empty())
658 if (use_minted && isfloat) {
659 os << breakln << "\\begin{listing}";
660 if (!placement.empty())
661 os << '[' << placement << "]";
663 } else if (use_minted && !caption.empty()) {
664 os << breakln << "\\lyxmintcaption[t]{" << caption;
666 os << "\\label{" << label << "}";
669 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
670 if (!parameters.empty())
671 os << "[" << parameters << "]";
673 os << '{' << ascii_lowercase(language) << '}';
674 os << '{' << incfile << '}';
675 if (use_minted && isfloat) {
676 if (!caption.empty())
677 os << breakln << "\\caption{" << caption << "}";
679 os << breakln << "\\label{" << label << "}";
680 os << breakln << "\\end{listing}\n";
685 runparams.exportdata->addExternalFile(tex_format, writefile,
688 // \include don't want extension and demands that the
689 // file really have .tex
690 incfile = changeExtension(incfile, string());
691 incfile = latex_path(incfile);
693 os << '\\' << from_ascii(params().getCmdName()) << '{'
694 << from_utf8(incfile) << '}';
701 if (runparams.inComment || runparams.dryrun)
702 // Don't try to load or copy the file if we're
703 // in a comment or doing a dryrun
706 if (isInputOrInclude(params()) &&
707 isLyXFileName(included_file.absFileName())) {
708 // if it's a LyX file and we're inputting or including,
709 // try to load it so we can write the associated latex
711 Buffer * tmp = loadIfNeeded();
713 if (!runparams.silent) {
714 docstring text = bformat(_("Could not load included "
716 "Please, check whether it actually exists."),
717 included_file.displayName());
718 throw ExceptionMessage(ErrorException, _("Error: "),
724 if (!runparams.silent) {
725 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
727 docstring text = bformat(_("Included file `%1$s'\n"
728 "has textclass `%2$s'\n"
729 "while parent file has textclass `%3$s'."),
730 included_file.displayName(),
731 from_utf8(tmp->params().documentClass().name()),
732 from_utf8(masterBuffer->params().documentClass().name()));
733 Alert::warning(_("Different textclasses"), text, true);
736 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
737 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
738 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
739 docstring text = bformat(_("Included file `%1$s'\n"
740 "has use-non-TeX-fonts set to `%2$s'\n"
741 "while parent file has use-non-TeX-fonts set to `%3$s'."),
742 included_file.displayName(),
744 from_utf8(master_tf));
745 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
748 // Make sure modules used in child are all included in master
749 // FIXME It might be worth loading the children's modules into the master
750 // over in BufferParams rather than doing this check.
751 LayoutModuleList const masterModules = masterBuffer->params().getModules();
752 LayoutModuleList const childModules = tmp->params().getModules();
753 LayoutModuleList::const_iterator it = childModules.begin();
754 LayoutModuleList::const_iterator end = childModules.end();
755 for (; it != end; ++it) {
756 string const module = *it;
757 LayoutModuleList::const_iterator found =
758 find(masterModules.begin(), masterModules.end(), module);
759 if (found == masterModules.end()) {
760 docstring text = bformat(_("Included file `%1$s'\n"
761 "uses module `%2$s'\n"
762 "which is not used in parent file."),
763 included_file.displayName(), from_utf8(module));
764 Alert::warning(_("Module not found"), text);
769 tmp->markDepClean(masterBuffer->temppath());
771 // Don't assume the child's format is latex
772 string const inc_format = tmp->params().bufferFormat();
773 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
774 theFormats().extension(inc_format)));
776 // FIXME: handle non existing files
777 // The included file might be written in a different encoding
779 Encoding const * const oldEnc = runparams.encoding;
780 Language const * const oldLang = runparams.master_language;
781 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
782 // the children must be encoded in plain utf8!
783 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
784 encodings.fromLyXName("utf8-plain")
785 : &tmp->params().encoding();
786 runparams.master_language = buffer().params().language;
787 runparams.par_begin = 0;
788 runparams.par_end = tmp->paragraphs().size();
789 runparams.is_child = true;
790 if (!tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
791 onlyPath().absFileName(), runparams, Buffer::OnlyBody)) {
792 if (!runparams.silent) {
793 docstring msg = bformat(_("Included file `%1$s' "
794 "was not exported correctly.\n "
795 "LaTeX export is probably incomplete."),
796 included_file.displayName());
797 ErrorList const & el = tmp->errorList("Export");
799 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
800 msg, el.begin()->error,
801 el.begin()->description);
802 throw ExceptionMessage(ErrorException, _("Error: "),
806 runparams.encoding = oldEnc;
807 runparams.master_language = oldLang;
808 runparams.is_child = false;
810 // If needed, use converters to produce a latex file from the child
811 if (tmpwritefile != writefile) {
814 theConverters().convert(tmp, tmpwritefile, writefile,
816 inc_format, tex_format, el);
818 if (!success && !runparams.silent) {
819 docstring msg = bformat(_("Included file `%1$s' "
820 "was not exported correctly.\n "
821 "LaTeX export is probably incomplete."),
822 included_file.displayName());
824 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
825 msg, el.begin()->error,
826 el.begin()->description);
827 throw ExceptionMessage(ErrorException, _("Error: "),
832 // In this case, it's not a LyX file, so we copy the file
833 // to the temp dir, so that .aux files etc. are not created
834 // in the original dir. Files included by this file will be
835 // found via either the environment variable TEXINPUTS, or
836 // input@path, see ../Buffer.cpp.
837 unsigned long const checksum_in = included_file.checksum();
838 unsigned long const checksum_out = writefile.checksum();
840 if (checksum_in != checksum_out) {
841 if (!included_file.copyTo(writefile)) {
844 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
845 "into the temporary directory."),
846 from_utf8(included_file.absFileName()))));
854 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
859 // For verbatim and listings, we just include the contents of the file as-is.
860 // In the case of listings, we wrap it in <pre>.
861 bool const listing = isListings(params());
862 if (listing || isVerbatim(params())) {
864 xs << html::StartTag("pre");
865 // FIXME: We don't know the encoding of the file, default to UTF-8.
866 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
868 xs << html::EndTag("pre");
872 // We don't (yet) know how to Input or Include non-LyX files.
873 // (If we wanted to get really arcane, we could run some tex2html
874 // converter on the included file. But that's just masochistic.)
875 FileName const included_file = includedFileName(buffer(), params());
876 if (!isLyXFileName(included_file.absFileName())) {
878 frontend::Alert::warning(_("Unsupported Inclusion"),
879 bformat(_("LyX does not know how to include non-LyX files when "
880 "generating HTML output. Offending file:\n%1$s"),
881 params()["filename"]));
885 // In the other cases, we will generate the HTML and include it.
887 // Check we're not trying to include ourselves.
888 // FIXME RECURSIVE INCLUDE
889 if (buffer().absFileName() == included_file.absFileName()) {
890 Alert::error(_("Recursive input"),
891 bformat(_("Attempted to include file %1$s in itself! "
892 "Ignoring inclusion."), params()["filename"]));
896 Buffer const * const ibuf = loadIfNeeded();
900 // are we generating only some paragraphs, or all of them?
901 bool const all_pars = !rp.dryrun ||
902 (rp.par_begin == 0 &&
903 rp.par_end == (int)buffer().text().paragraphs().size());
905 OutputParams op = rp;
909 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
911 xs << XHTMLStream::ESCAPE_NONE
912 << "<!-- Included file: "
913 << from_utf8(included_file.absFileName())
914 << XHTMLStream::ESCAPE_NONE
920 int InsetInclude::plaintext(odocstringstream & os,
921 OutputParams const & op, size_t) const
923 // just write the filename if we're making a tooltip or toc entry,
924 // or are generating this for advanced search
925 if (op.for_tooltip || op.for_toc || op.for_search) {
926 os << '[' << screenLabel() << '\n'
927 << getParam("filename") << "\n]";
928 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
931 if (isVerbatim(params()) || isListings(params())) {
932 os << '[' << screenLabel() << '\n'
933 // FIXME: We don't know the encoding of the file, default to UTF-8.
934 << includedFileName(buffer(), params()).fileContents("UTF-8")
936 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
939 Buffer const * const ibuf = loadIfNeeded();
941 docstring const str = '[' + screenLabel() + ']';
945 writePlaintextFile(*ibuf, os, op);
950 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
952 string incfile = to_utf8(params()["filename"]);
954 // Do nothing if no file name has been specified
958 string const included_file = includedFileName(buffer(), params()).absFileName();
960 // Check we're not trying to include ourselves.
961 // FIXME RECURSIVE INCLUDE
962 // This isn't sufficient, as the inclusion could be downstream.
963 // But it'll have to do for now.
964 if (buffer().absFileName() == included_file) {
965 Alert::error(_("Recursive input"),
966 bformat(_("Attempted to include file %1$s in itself! "
967 "Ignoring inclusion."), from_utf8(incfile)));
971 string exppath = incfile;
972 if (!runparams.export_folder.empty()) {
973 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
974 FileName(exppath).onlyPath().createPath();
977 // write it to a file (so far the complete file)
978 string const exportfile = changeExtension(exppath, ".sgml");
979 DocFileName writefile(changeExtension(included_file, ".sgml"));
981 Buffer * tmp = loadIfNeeded();
983 string const mangled = writefile.mangledFileName();
984 writefile = makeAbsPath(mangled,
985 buffer().masterBuffer()->temppath());
989 LYXERR(Debug::LATEX, "incfile:" << incfile);
990 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
991 LYXERR(Debug::LATEX, "writefile:" << writefile);
993 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
996 runparams.exportdata->addExternalFile("docbook", writefile,
998 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1001 if (isVerbatim(params()) || isListings(params())) {
1002 os << "<inlinegraphic fileref=\""
1003 << '&' << include_label << ';'
1004 << "\" format=\"linespecific\">";
1006 os << '&' << include_label << ';';
1012 void InsetInclude::validate(LaTeXFeatures & features) const
1014 LATTEST(&buffer() == &features.buffer());
1016 string incfile = to_utf8(params()["filename"]);
1017 string const included_file =
1018 includedFileName(buffer(), params()).absFileName();
1021 if (isLyXFileName(included_file))
1022 writefile = changeExtension(included_file, ".sgml");
1024 writefile = included_file;
1026 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1027 incfile = DocFileName(writefile).mangledFileName();
1028 writefile = makeAbsPath(incfile,
1029 buffer().masterBuffer()->temppath()).absFileName();
1032 features.includeFile(include_label, writefile);
1034 features.useInsetLayout(getLayout());
1035 if (isVerbatim(params()))
1036 features.require("verbatim");
1037 else if (isListings(params())) {
1038 if (buffer().params().use_minted) {
1039 features.require("minted");
1040 string const opts = to_utf8(params()["lstparams"]);
1041 InsetListingsParams lstpars(opts);
1042 if (!lstpars.isFloat() && contains(opts, "caption="))
1043 features.require("lyxmintcaption");
1045 features.require("listings");
1048 // Here we must do the fun stuff...
1049 // Load the file in the include if it needs
1051 Buffer * const tmp = loadIfNeeded();
1053 // the file is loaded
1054 // make sure the buffer isn't us
1055 // FIXME RECURSIVE INCLUDES
1056 // This is not sufficient, as recursive includes could be
1057 // more than a file away. But it will do for now.
1058 if (tmp && tmp != &buffer()) {
1059 // We must temporarily change features.buffer,
1060 // otherwise it would always be the master buffer,
1061 // and nested includes would not work.
1062 features.setBuffer(*tmp);
1063 // Maybe this is already a child
1064 bool const is_child =
1065 features.runparams().is_child;
1066 features.runparams().is_child = true;
1067 tmp->validate(features);
1068 features.runparams().is_child = is_child;
1069 features.setBuffer(buffer());
1075 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/) const
1077 Buffer * child = loadIfNeeded();
1080 // FIXME RECURSIVE INCLUDE
1081 // This isn't sufficient, as the inclusion could be downstream.
1082 // But it'll have to do for now.
1083 if (child == &buffer())
1085 child->collectBibKeys();
1089 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1091 LBUFERR(mi.base.bv);
1093 bool use_preview = false;
1094 if (RenderPreview::previewText()) {
1095 graphics::PreviewImage const * pimage =
1096 preview_->getPreviewImage(mi.base.bv->buffer());
1097 use_preview = pimage && pimage->image();
1101 preview_->metrics(mi, dim);
1105 button_.update(screenLabel(), true, false);
1107 button_.metrics(mi, dim);
1110 Box b(0, dim.wid, -dim.asc, dim.des);
1115 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1117 LBUFERR(pi.base.bv);
1119 bool use_preview = false;
1120 if (RenderPreview::previewText()) {
1121 graphics::PreviewImage const * pimage =
1122 preview_->getPreviewImage(pi.base.bv->buffer());
1123 use_preview = pimage && pimage->image();
1127 preview_->draw(pi, x, y);
1129 button_.draw(pi, x, y);
1133 void InsetInclude::write(ostream & os) const
1135 params().Write(os, &buffer());
1139 string InsetInclude::contextMenuName() const
1141 return "context-include";
1145 Inset::DisplayType InsetInclude::display() const
1147 return type(params()) == INPUT ? Inline : AlignCenter;
1151 docstring InsetInclude::layoutName() const
1153 if (isListings(params()))
1154 return from_ascii("IncludeListings");
1155 return InsetCommand::layoutName();
1163 void InsetInclude::fileChanged() const
1165 Buffer const * const buffer = updateFrontend();
1169 preview_->removePreview(*buffer);
1170 add_preview(*preview_, *this, *buffer);
1171 preview_->startLoading(*buffer);
1177 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1179 FileName const included_file = includedFileName(buffer, params);
1181 return type(params) == INPUT && params.preview() &&
1182 included_file.isReadableFile();
1186 docstring latexString(InsetInclude const & inset)
1188 odocstringstream ods;
1190 // We don't need to set runparams.encoding since this will be done
1191 // by latex() anyway.
1192 OutputParams runparams(0);
1193 runparams.flavor = OutputParams::LATEX;
1194 runparams.for_preview = true;
1195 inset.latex(os, runparams);
1201 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1202 Buffer const & buffer)
1204 InsetCommandParams const & params = inset.params();
1205 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1206 renderer.setAbsFile(includedFileName(buffer, params));
1207 docstring const snippet = latexString(inset);
1208 renderer.addPreview(snippet, buffer);
1215 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1216 graphics::PreviewLoader & ploader) const
1218 Buffer const & buffer = ploader.buffer();
1219 if (!preview_wanted(params(), buffer))
1221 preview_->setAbsFile(includedFileName(buffer, params()));
1222 docstring const snippet = latexString(*this);
1223 preview_->addPreview(snippet, ploader);
1227 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1228 UpdateType utype, TocBackend & backend) const
1230 if (isListings(params())) {
1232 label_->addToToc(cpit, output_active, utype, backend);
1233 TocBuilder & b = backend.builder("listing");
1234 b.pushItem(cpit, screenLabel(), output_active);
1235 InsetListingsParams p(to_utf8(params()["lstparams"]));
1236 b.argumentItem(from_utf8(p.getParamValue("caption")));
1239 Buffer const * const childbuffer = getChildBuffer();
1241 TocBuilder & b = backend.builder("child");
1242 docstring str = childbuffer ? childbuffer->fileName().displayName()
1244 b.pushItem(cpit, str, output_active);
1250 // Update the child's tocBackend. The outliner uses the master's, but
1251 // the navigation menu uses the child's.
1252 childbuffer->tocBackend().update(output_active, utype);
1253 // Include Tocs from children
1254 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1256 //Copy missing outliner names (though the user has been warned against
1257 //having different document class and module selection between master
1259 for (pair<string, docstring> const & name
1260 : childbuffer->params().documentClass().outlinerNames())
1261 backend.addName(name.first, translateIfPossible(name.second));
1266 void InsetInclude::updateCommand()
1271 docstring old_label = label_->getParam("name");
1272 label_->updateLabel(old_label);
1273 // the label might have been adapted (duplicate)
1274 docstring new_label = label_->getParam("name");
1275 if (old_label == new_label)
1278 // update listings parameters...
1279 InsetCommandParams p(INCLUDE_CODE);
1281 InsetListingsParams par(to_utf8(params()["lstparams"]));
1282 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1283 p["lstparams"] = from_utf8(par.params());
1288 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1290 button_.update(screenLabel(), true, false);
1292 Buffer const * const childbuffer = getChildBuffer();
1294 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1297 if (!isListings(params()))
1301 label_->updateBuffer(it, utype);
1303 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1304 if (par.getParamValue("caption").empty()) {
1305 listings_label_ = buffer().B_("Program Listing");
1308 Buffer const & master = *buffer().masterBuffer();
1309 Counters & counters = master.params().documentClass().counters();
1310 docstring const cnt = from_ascii("listing");
1311 listings_label_ = master.B_("Program Listing");
1312 if (counters.hasCounter(cnt)) {
1313 counters.step(cnt, utype);
1314 listings_label_ += " " + convert<docstring>(counters.value(cnt));