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()
204 void InsetInclude::setBuffer(Buffer & buffer)
206 InsetCommand::setBuffer(buffer);
208 label_->setBuffer(buffer);
212 void InsetInclude::setChildBuffer(Buffer * buffer)
214 child_buffer_ = buffer;
218 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
221 // This is only correct for the case of listings, but it'll do for now.
222 // In the other cases, this second parameter should just be empty.
223 static ParamInfo param_info_;
224 if (param_info_.empty()) {
225 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
226 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
227 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
233 bool InsetInclude::isCompatibleCommand(string const & s)
235 return type(s) != NONE;
239 bool InsetInclude::needsCProtection(bool const /*maintext*/, bool const fragile) const
241 // We need to \cprotect all types in fragile context
246 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
248 switch (cmd.action()) {
250 case LFUN_INSET_EDIT: {
251 editIncluded(to_utf8(params()["filename"]));
255 case LFUN_INSET_MODIFY: {
256 // It should be OK just to invalidate the cache in setParams()
258 // child_buffer_ = 0;
259 InsetCommandParams p(INCLUDE_CODE);
260 if (cmd.getArg(0) == "changetype") {
262 InsetCommand::doDispatch(cur, cmd);
265 InsetCommand::string2params(to_utf8(cmd.argument()), p);
266 if (!p.getCmdName().empty()) {
268 InsetListingsParams new_params(to_utf8(p["lstparams"]));
269 docstring const new_label =
270 from_utf8(new_params.getParamValue("label"));
272 if (new_label.empty()) {
278 old_label = label_->getParam("name");
280 label_ = createLabel(buffer_, new_label);
281 label_->setBuffer(buffer());
284 if (new_label != old_label) {
285 label_->updateLabelAndRefs(new_label, &cur);
286 // the label might have been adapted (duplicate)
287 if (new_label != label_->getParam("name")) {
288 new_params.addParam("label", "{" +
289 to_utf8(label_->getParam("name")) + "}", true);
290 p["lstparams"] = from_utf8(new_params.params());
297 cur.forceBufferUpdate();
299 cur.noScreenUpdate();
303 //pass everything else up the chain
305 InsetCommand::doDispatch(cur, cmd);
311 void InsetInclude::editIncluded(string const & file)
313 string const ext = support::getExtension(file);
315 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, file);
318 // tex file or other text file in verbatim mode
319 theFormats().edit(buffer(),
320 support::makeAbsPath(file, support::onlyPath(buffer().absFileName())),
325 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
326 FuncStatus & flag) const
328 switch (cmd.action()) {
330 case LFUN_INSET_EDIT:
331 flag.setEnabled(true);
334 case LFUN_INSET_MODIFY:
335 if (cmd.getArg(0) == "changetype")
336 return InsetCommand::getStatus(cur, cmd, flag);
338 flag.setEnabled(true);
342 return InsetCommand::getStatus(cur, cmd, flag);
347 void InsetInclude::setParams(InsetCommandParams const & p)
349 // invalidate the cache
352 InsetCommand::setParams(p);
355 if (preview_->monitoring())
356 preview_->stopMonitoring();
358 if (type(params()) == INPUT)
359 add_preview(*preview_, *this, buffer());
363 bool InsetInclude::isChildIncluded() const
365 std::list<std::string> includeonlys =
366 buffer().params().getIncludedChildren();
367 if (includeonlys.empty())
369 return (std::find(includeonlys.begin(),
371 to_utf8(params()["filename"])) != includeonlys.end());
375 docstring InsetInclude::screenLabel() const
379 switch (type(params())) {
381 temp = buffer().B_("Input");
384 temp = buffer().B_("Verbatim Input");
387 temp = buffer().B_("Verbatim Input*");
390 if (isChildIncluded())
391 temp = buffer().B_("Include");
393 temp += buffer().B_("Include (excluded)");
396 temp = listings_label_;
399 LASSERT(false, temp = buffer().B_("Unknown"));
405 if (params()["filename"].empty())
408 temp += from_utf8(onlyFileName(to_utf8(params()["filename"])));
414 Buffer * InsetInclude::getChildBuffer() const
416 Buffer * childBuffer = loadIfNeeded();
418 // FIXME RECURSIVE INCLUDE
419 // This isn't sufficient, as the inclusion could be downstream.
420 // But it'll have to do for now.
421 return (childBuffer == &buffer()) ? 0 : childBuffer;
425 Buffer * InsetInclude::loadIfNeeded() const
427 // This is for background export and preview. We don't even want to
428 // try to load the cloned child document again.
429 if (buffer().isClone())
430 return child_buffer_;
432 // Don't try to load it again if we failed before.
433 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
436 FileName const included_file = includedFileName(buffer(), params());
437 // Use cached Buffer if possible.
438 if (child_buffer_ != 0) {
439 if (theBufferList().isLoaded(child_buffer_)
440 // additional sanity check: make sure the Buffer really is
441 // associated with the file we want.
442 && child_buffer_ == theBufferList().getBuffer(included_file))
443 return child_buffer_;
444 // Buffer vanished, so invalidate cache and try to reload.
448 if (!isLyXFileName(included_file.absFileName()))
451 Buffer * child = theBufferList().getBuffer(included_file);
453 // the readonly flag can/will be wrong, not anymore I think.
454 if (!included_file.exists())
457 child = theBufferList().newBuffer(included_file.absFileName());
459 // Buffer creation is not possible.
462 // Set parent before loading, such that macros can be tracked
463 child->setParent(&buffer());
465 if (child->loadLyXFile() != Buffer::ReadSuccess) {
466 failedtoload_ = true;
468 //close the buffer we just opened
469 theBufferList().release(child);
473 if (!child->errorList("Parse").empty()) {
474 // FIXME: Do something.
477 // The file was already loaded, so, simply
478 // inform parent buffer about local macros.
479 Buffer const * parent = &buffer();
480 child->setParent(parent);
482 child->listMacroNames(macros);
483 MacroNameSet::const_iterator cit = macros.begin();
484 MacroNameSet::const_iterator end = macros.end();
485 for (; cit != end; ++cit)
486 parent->usermacros.insert(*cit);
489 // Cache the child buffer.
490 child_buffer_ = child;
495 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
497 string incfile = to_utf8(params()["filename"]);
499 // Do nothing if no file name has been specified
503 FileName const included_file = includedFileName(buffer(), params());
505 // Check we're not trying to include ourselves.
506 // FIXME RECURSIVE INCLUDE
507 // This isn't sufficient, as the inclusion could be downstream.
508 // But it'll have to do for now.
509 if (isInputOrInclude(params()) &&
510 buffer().absFileName() == included_file.absFileName())
512 Alert::error(_("Recursive input"),
513 bformat(_("Attempted to include file %1$s in itself! "
514 "Ignoring inclusion."), from_utf8(incfile)));
518 Buffer const * const masterBuffer = buffer().masterBuffer();
520 // if incfile is relative, make it relative to the master
522 if (!FileName::isAbsolute(incfile)) {
524 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
525 from_utf8(masterBuffer->filePath())));
528 string exppath = incfile;
529 if (!runparams.export_folder.empty()) {
530 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
531 FileName(exppath).onlyPath().createPath();
534 // write it to a file (so far the complete file)
538 if (type(params()) == LISTINGS) {
539 exportfile = exppath;
540 mangled = DocFileName(included_file).mangledFileName();
542 exportfile = changeExtension(exppath, ".tex");
543 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
549 else if (!runparams.silent)
550 ; // no warning wanted
551 else if (!isValidLaTeXFileName(incfile)) {
552 frontend::Alert::warning(_("Invalid filename"),
553 _("The following filename will cause troubles "
554 "when running the exported file through LaTeX: ") +
556 } else if (!isValidDVIFileName(incfile)) {
557 frontend::Alert::warning(_("Problematic filename for DVI"),
558 _("The following filename can cause troubles "
559 "when running the exported file through LaTeX "
560 "and opening the resulting DVI: ") +
561 from_utf8(incfile), true);
564 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
565 buffer().temppath() : masterBuffer->temppath()));
567 LYXERR(Debug::LATEX, "incfile:" << incfile);
568 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
569 LYXERR(Debug::LATEX, "writefile:" << writefile);
571 string const tex_format = flavor2format(runparams.flavor);
573 switch (type(params())) {
576 incfile = latex_path(incfile);
578 os << '\\' << from_ascii(params().getCmdName()) << '{'
579 << from_utf8(incfile) << '}';
583 runparams.exportdata->addExternalFile(tex_format, writefile,
586 // \input wants file with extension (default is .tex)
587 if (!isLyXFileName(included_file.absFileName())) {
588 incfile = latex_path(incfile);
590 os << '\\' << from_ascii(params().getCmdName())
591 << '{' << from_utf8(incfile) << '}';
593 incfile = changeExtension(incfile, ".tex");
594 incfile = latex_path(incfile);
596 os << '\\' << from_ascii(params().getCmdName())
597 << '{' << from_utf8(incfile) << '}';
602 // Here, listings and minted have sligthly different behaviors.
603 // Using listings, it is always possible to have a caption,
604 // even for non-floats. Using minted, only floats can have a
605 // caption. So, with minted we use the following strategy.
606 // If a caption was specified but the float parameter was not,
607 // we ourselves add a caption above the listing (because the
608 // listing comes from a file and might span several pages).
609 // Otherwise, if float was specified, the floating listing
610 // environment provided by minted is used. In either case, the
611 // label parameter is taken as the label by which the float
612 // can be referenced, otherwise it will have the meaning
613 // intended by minted. In this last case, the label will
614 // serve as a sort of caption that, however, will be shown
615 // by minted only if the frame parameter is also specified.
616 bool const use_minted = buffer().params().use_minted;
617 runparams.exportdata->addExternalFile(tex_format, writefile,
619 string const opt = to_utf8(params()["lstparams"]);
620 // opt is set in QInclude dialog and should have passed validation.
621 InsetListingsParams lstparams(opt);
622 docstring parameters = from_utf8(lstparams.params());
627 bool isfloat = lstparams.isFloat();
628 // Get float placement, language, caption, and
629 // label, then remove the relative options if minted.
630 vector<docstring> opts =
631 getVectorFromString(parameters, from_ascii(","), false);
632 vector<docstring> latexed_opts;
633 for (size_t i = 0; i < opts.size(); ++i) {
634 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
635 if (prefixIs(opts[i], from_ascii("float=")))
636 placement = opts[i].substr(6);
637 opts.erase(opts.begin() + i--);
638 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
639 language = opts[i].substr(9);
640 opts.erase(opts.begin() + i--);
641 } else if (prefixIs(opts[i], from_ascii("caption="))) {
642 caption = params().prepareCommand(runparams, trim(opts[i].substr(8), "{}"),
643 ParamInfo::HANDLING_LATEXIFY);
644 opts.erase(opts.begin() + i--);
646 latexed_opts.push_back(from_ascii("caption=") + caption);
647 } else if (prefixIs(opts[i], from_ascii("label="))) {
648 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
649 ParamInfo::HANDLING_ESCAPE);
650 opts.erase(opts.begin() + i--);
652 latexed_opts.push_back(from_ascii("label={") + label + "}");
654 if (use_minted && !label.empty()) {
655 if (isfloat || !caption.empty())
656 label = trim(label, "{}");
658 opts.push_back(from_ascii("label=") + label);
661 if (!latexed_opts.empty())
662 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
663 parameters = getStringFromVector(opts, from_ascii(","));
664 if (language.empty())
665 language = from_ascii("TeX");
666 if (use_minted && isfloat) {
667 os << breakln << "\\begin{listing}";
668 if (!placement.empty())
669 os << '[' << placement << "]";
671 } else if (use_minted && !caption.empty()) {
672 os << breakln << "\\lyxmintcaption[t]{" << caption;
674 os << "\\label{" << label << "}";
677 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
678 if (!parameters.empty())
679 os << "[" << parameters << "]";
681 os << '{' << ascii_lowercase(language) << '}';
682 os << '{' << incfile << '}';
683 if (use_minted && isfloat) {
684 if (!caption.empty())
685 os << breakln << "\\caption{" << caption << "}";
687 os << breakln << "\\label{" << label << "}";
688 os << breakln << "\\end{listing}\n";
693 runparams.exportdata->addExternalFile(tex_format, writefile,
696 // \include don't want extension and demands that the
697 // file really have .tex
698 incfile = changeExtension(incfile, string());
699 incfile = latex_path(incfile);
701 os << '\\' << from_ascii(params().getCmdName()) << '{'
702 << from_utf8(incfile) << '}';
709 if (runparams.inComment || runparams.dryrun)
710 // Don't try to load or copy the file if we're
711 // in a comment or doing a dryrun
714 if (isInputOrInclude(params()) &&
715 isLyXFileName(included_file.absFileName())) {
716 // if it's a LyX file and we're inputting or including,
717 // try to load it so we can write the associated latex
719 Buffer * tmp = loadIfNeeded();
721 if (!runparams.silent) {
722 docstring text = bformat(_("Could not load included "
724 "Please, check whether it actually exists."),
725 included_file.displayName());
726 throw ExceptionMessage(ErrorException, _("Error: "),
732 if (!runparams.silent) {
733 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
735 docstring text = bformat(_("Included file `%1$s'\n"
736 "has textclass `%2$s'\n"
737 "while parent file has textclass `%3$s'."),
738 included_file.displayName(),
739 from_utf8(tmp->params().documentClass().name()),
740 from_utf8(masterBuffer->params().documentClass().name()));
741 Alert::warning(_("Different textclasses"), text, true);
744 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
745 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
746 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
747 docstring text = bformat(_("Included file `%1$s'\n"
748 "has use-non-TeX-fonts set to `%2$s'\n"
749 "while parent file has use-non-TeX-fonts set to `%3$s'."),
750 included_file.displayName(),
752 from_utf8(master_tf));
753 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
756 // Make sure modules used in child are all included in master
757 // FIXME It might be worth loading the children's modules into the master
758 // over in BufferParams rather than doing this check.
759 LayoutModuleList const masterModules = masterBuffer->params().getModules();
760 LayoutModuleList const childModules = tmp->params().getModules();
761 LayoutModuleList::const_iterator it = childModules.begin();
762 LayoutModuleList::const_iterator end = childModules.end();
763 for (; it != end; ++it) {
764 string const module = *it;
765 LayoutModuleList::const_iterator found =
766 find(masterModules.begin(), masterModules.end(), module);
767 if (found == masterModules.end()) {
768 docstring text = bformat(_("Included file `%1$s'\n"
769 "uses module `%2$s'\n"
770 "which is not used in parent file."),
771 included_file.displayName(), from_utf8(module));
772 Alert::warning(_("Module not found"), text);
777 tmp->markDepClean(masterBuffer->temppath());
779 // Don't assume the child's format is latex
780 string const inc_format = tmp->params().bufferFormat();
781 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
782 theFormats().extension(inc_format)));
784 // FIXME: handle non existing files
785 // The included file might be written in a different encoding
787 Encoding const * const oldEnc = runparams.encoding;
788 Language const * const oldLang = runparams.master_language;
789 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
790 // the children must be encoded in plain utf8!
791 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
792 encodings.fromLyXName("utf8-plain")
793 : &tmp->params().encoding();
794 runparams.master_language = buffer().params().language;
795 runparams.par_begin = 0;
796 runparams.par_end = tmp->paragraphs().size();
797 runparams.is_child = true;
798 Buffer::ExportStatus retval =
799 tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
800 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
801 if (retval == Buffer::ExportKilled && buffer().isClone() &&
802 buffer().isExporting()) {
803 // We really shouldn't get here, I don't think.
804 LYXERR0("No conversion exception?");
805 throw ConversionException();
807 else if (retval != Buffer::ExportSuccess) {
808 if (!runparams.silent) {
809 docstring msg = bformat(_("Included file `%1$s' "
810 "was not exported correctly.\n "
811 "LaTeX export is probably incomplete."),
812 included_file.displayName());
813 ErrorList const & el = tmp->errorList("Export");
815 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
816 msg, el.begin()->error, el.begin()->description);
817 throw ExceptionMessage(ErrorException, _("Error: "), msg);
820 runparams.encoding = oldEnc;
821 runparams.master_language = oldLang;
822 runparams.is_child = false;
824 // If needed, use converters to produce a latex file from the child
825 if (tmpwritefile != writefile) {
827 Converters::RetVal const retval =
828 theConverters().convert(tmp, tmpwritefile, writefile,
829 included_file, inc_format, tex_format, el);
830 if (retval == Converters::KILLED && buffer().isClone() &&
831 buffer().isExporting()) {
832 // We really shouldn't get here, I don't think.
833 LYXERR0("No conversion exception?");
834 throw ConversionException();
835 } else if (retval != Converters::SUCCESS && !runparams.silent) {
836 docstring msg = bformat(_("Included file `%1$s' "
837 "was not exported correctly.\n "
838 "LaTeX export is probably incomplete."),
839 included_file.displayName());
841 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
842 msg, el.begin()->error, el.begin()->description);
843 throw ExceptionMessage(ErrorException, _("Error: "), msg);
847 // In this case, it's not a LyX file, so we copy the file
848 // to the temp dir, so that .aux files etc. are not created
849 // in the original dir. Files included by this file will be
850 // found via either the environment variable TEXINPUTS, or
851 // input@path, see ../Buffer.cpp.
852 unsigned long const checksum_in = included_file.checksum();
853 unsigned long const checksum_out = writefile.checksum();
855 if (checksum_in != checksum_out) {
856 if (!included_file.copyTo(writefile)) {
859 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
860 "into the temporary directory."),
861 from_utf8(included_file.absFileName()))));
869 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
874 // For verbatim and listings, we just include the contents of the file as-is.
875 // In the case of listings, we wrap it in <pre>.
876 bool const listing = isListings(params());
877 if (listing || isVerbatim(params())) {
879 xs << html::StartTag("pre");
880 // FIXME: We don't know the encoding of the file, default to UTF-8.
881 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
883 xs << html::EndTag("pre");
887 // We don't (yet) know how to Input or Include non-LyX files.
888 // (If we wanted to get really arcane, we could run some tex2html
889 // converter on the included file. But that's just masochistic.)
890 FileName const included_file = includedFileName(buffer(), params());
891 if (!isLyXFileName(included_file.absFileName())) {
893 frontend::Alert::warning(_("Unsupported Inclusion"),
894 bformat(_("LyX does not know how to include non-LyX files when "
895 "generating HTML output. Offending file:\n%1$s"),
896 params()["filename"]));
900 // In the other cases, we will generate the HTML and include it.
902 // Check we're not trying to include ourselves.
903 // FIXME RECURSIVE INCLUDE
904 if (buffer().absFileName() == included_file.absFileName()) {
905 Alert::error(_("Recursive input"),
906 bformat(_("Attempted to include file %1$s in itself! "
907 "Ignoring inclusion."), params()["filename"]));
911 Buffer const * const ibuf = loadIfNeeded();
915 // are we generating only some paragraphs, or all of them?
916 bool const all_pars = !rp.dryrun ||
917 (rp.par_begin == 0 &&
918 rp.par_end == (int)buffer().text().paragraphs().size());
920 OutputParams op = rp;
924 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
926 xs << XHTMLStream::ESCAPE_NONE
927 << "<!-- Included file: "
928 << from_utf8(included_file.absFileName())
929 << XHTMLStream::ESCAPE_NONE
935 int InsetInclude::plaintext(odocstringstream & os,
936 OutputParams const & op, size_t) const
938 // just write the filename if we're making a tooltip or toc entry,
939 // or are generating this for advanced search
940 if (op.for_tooltip || op.for_toc || op.for_search) {
941 os << '[' << screenLabel() << '\n'
942 << getParam("filename") << "\n]";
943 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
946 if (isVerbatim(params()) || isListings(params())) {
947 os << '[' << screenLabel() << '\n'
948 // FIXME: We don't know the encoding of the file, default to UTF-8.
949 << includedFileName(buffer(), params()).fileContents("UTF-8")
951 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
954 Buffer const * const ibuf = loadIfNeeded();
956 docstring const str = '[' + screenLabel() + ']';
960 writePlaintextFile(*ibuf, os, op);
965 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
967 string incfile = to_utf8(params()["filename"]);
969 // Do nothing if no file name has been specified
973 string const included_file = includedFileName(buffer(), params()).absFileName();
975 // Check we're not trying to include ourselves.
976 // FIXME RECURSIVE INCLUDE
977 // This isn't sufficient, as the inclusion could be downstream.
978 // But it'll have to do for now.
979 if (buffer().absFileName() == included_file) {
980 Alert::error(_("Recursive input"),
981 bformat(_("Attempted to include file %1$s in itself! "
982 "Ignoring inclusion."), from_utf8(incfile)));
986 string exppath = incfile;
987 if (!runparams.export_folder.empty()) {
988 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
989 FileName(exppath).onlyPath().createPath();
992 // write it to a file (so far the complete file)
993 string const exportfile = changeExtension(exppath, ".sgml");
994 DocFileName writefile(changeExtension(included_file, ".sgml"));
996 Buffer * tmp = loadIfNeeded();
998 string const mangled = writefile.mangledFileName();
999 writefile = makeAbsPath(mangled,
1000 buffer().masterBuffer()->temppath());
1001 if (!runparams.nice)
1004 LYXERR(Debug::LATEX, "incfile:" << incfile);
1005 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
1006 LYXERR(Debug::LATEX, "writefile:" << writefile);
1008 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
1011 runparams.exportdata->addExternalFile("docbook", writefile,
1013 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1016 if (isVerbatim(params()) || isListings(params())) {
1017 os << "<inlinegraphic fileref=\""
1018 << '&' << include_label << ';'
1019 << "\" format=\"linespecific\">";
1021 os << '&' << include_label << ';';
1027 void InsetInclude::validate(LaTeXFeatures & features) const
1029 LATTEST(&buffer() == &features.buffer());
1031 string incfile = to_utf8(params()["filename"]);
1032 string const included_file =
1033 includedFileName(buffer(), params()).absFileName();
1036 if (isLyXFileName(included_file))
1037 writefile = changeExtension(included_file, ".sgml");
1039 writefile = included_file;
1041 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1042 incfile = DocFileName(writefile).mangledFileName();
1043 writefile = makeAbsPath(incfile,
1044 buffer().masterBuffer()->temppath()).absFileName();
1047 features.includeFile(include_label, writefile);
1049 features.useInsetLayout(getLayout());
1050 if (isVerbatim(params()))
1051 features.require("verbatim");
1052 else if (isListings(params())) {
1053 if (buffer().params().use_minted) {
1054 features.require("minted");
1055 string const opts = to_utf8(params()["lstparams"]);
1056 InsetListingsParams lstpars(opts);
1057 if (!lstpars.isFloat() && contains(opts, "caption="))
1058 features.require("lyxmintcaption");
1060 features.require("listings");
1063 // Here we must do the fun stuff...
1064 // Load the file in the include if it needs
1066 Buffer * const tmp = loadIfNeeded();
1068 // the file is loaded
1069 // make sure the buffer isn't us
1070 // FIXME RECURSIVE INCLUDES
1071 // This is not sufficient, as recursive includes could be
1072 // more than a file away. But it will do for now.
1073 if (tmp && tmp != &buffer()) {
1074 // We must temporarily change features.buffer,
1075 // otherwise it would always be the master buffer,
1076 // and nested includes would not work.
1077 features.setBuffer(*tmp);
1078 // Maybe this is already a child
1079 bool const is_child =
1080 features.runparams().is_child;
1081 features.runparams().is_child = true;
1082 tmp->validate(features);
1083 features.runparams().is_child = is_child;
1084 features.setBuffer(buffer());
1090 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1092 Buffer * child = loadIfNeeded();
1095 // FIXME RECURSIVE INCLUDE
1096 // This isn't sufficient, as the inclusion could be downstream.
1097 // But it'll have to do for now.
1098 if (child == &buffer())
1100 child->collectBibKeys(checkedFiles);
1104 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1106 LBUFERR(mi.base.bv);
1108 bool use_preview = false;
1109 if (RenderPreview::previewText()) {
1110 graphics::PreviewImage const * pimage =
1111 preview_->getPreviewImage(mi.base.bv->buffer());
1112 use_preview = pimage && pimage->image();
1116 preview_->metrics(mi, dim);
1120 button_.update(screenLabel(), true, false);
1122 button_.metrics(mi, dim);
1125 Box b(0, dim.wid, -dim.asc, dim.des);
1130 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1132 LBUFERR(pi.base.bv);
1134 bool use_preview = false;
1135 if (RenderPreview::previewText()) {
1136 graphics::PreviewImage const * pimage =
1137 preview_->getPreviewImage(pi.base.bv->buffer());
1138 use_preview = pimage && pimage->image();
1142 preview_->draw(pi, x, y);
1144 button_.draw(pi, x, y);
1148 void InsetInclude::write(ostream & os) const
1150 params().Write(os, &buffer());
1154 string InsetInclude::contextMenuName() const
1156 return "context-include";
1160 Inset::DisplayType InsetInclude::display() const
1162 return type(params()) == INPUT ? Inline : AlignCenter;
1166 docstring InsetInclude::layoutName() const
1168 if (isListings(params()))
1169 return from_ascii("IncludeListings");
1170 return InsetCommand::layoutName();
1178 void InsetInclude::fileChanged() const
1180 Buffer const * const buffer = updateFrontend();
1184 preview_->removePreview(*buffer);
1185 add_preview(*preview_, *this, *buffer);
1186 preview_->startLoading(*buffer);
1192 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1194 FileName const included_file = includedFileName(buffer, params);
1196 return type(params) == INPUT && params.preview() &&
1197 included_file.isReadableFile();
1201 docstring latexString(InsetInclude const & inset)
1203 odocstringstream ods;
1205 // We don't need to set runparams.encoding since this will be done
1206 // by latex() anyway.
1207 OutputParams runparams(0);
1208 runparams.flavor = OutputParams::LATEX;
1209 runparams.for_preview = true;
1210 inset.latex(os, runparams);
1216 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1217 Buffer const & buffer)
1219 InsetCommandParams const & params = inset.params();
1220 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1221 renderer.setAbsFile(includedFileName(buffer, params));
1222 docstring const snippet = latexString(inset);
1223 renderer.addPreview(snippet, buffer);
1230 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1231 graphics::PreviewLoader & ploader) const
1233 Buffer const & buffer = ploader.buffer();
1234 if (!preview_wanted(params(), buffer))
1236 preview_->setAbsFile(includedFileName(buffer, params()));
1237 docstring const snippet = latexString(*this);
1238 preview_->addPreview(snippet, ploader);
1242 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1243 UpdateType utype, TocBackend & backend) const
1245 if (isListings(params())) {
1247 label_->addToToc(cpit, output_active, utype, backend);
1248 TocBuilder & b = backend.builder("listing");
1249 b.pushItem(cpit, screenLabel(), output_active);
1250 InsetListingsParams p(to_utf8(params()["lstparams"]));
1251 b.argumentItem(from_utf8(p.getParamValue("caption")));
1254 Buffer const * const childbuffer = getChildBuffer();
1256 TocBuilder & b = backend.builder("child");
1257 docstring str = childbuffer ? childbuffer->fileName().displayName()
1259 b.pushItem(cpit, str, output_active);
1265 // Update the child's tocBackend. The outliner uses the master's, but
1266 // the navigation menu uses the child's.
1267 childbuffer->tocBackend().update(output_active, utype);
1268 // Include Tocs from children
1269 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1271 //Copy missing outliner names (though the user has been warned against
1272 //having different document class and module selection between master
1274 for (pair<string, docstring> const & name
1275 : childbuffer->params().documentClass().outlinerNames())
1276 backend.addName(name.first, translateIfPossible(name.second));
1281 void InsetInclude::updateCommand()
1286 docstring old_label = label_->getParam("name");
1287 label_->updateLabel(old_label);
1288 // the label might have been adapted (duplicate)
1289 docstring new_label = label_->getParam("name");
1290 if (old_label == new_label)
1293 // update listings parameters...
1294 InsetCommandParams p(INCLUDE_CODE);
1296 InsetListingsParams par(to_utf8(params()["lstparams"]));
1297 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1298 p["lstparams"] = from_utf8(par.params());
1303 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1305 button_.update(screenLabel(), true, false);
1307 Buffer const * const childbuffer = getChildBuffer();
1309 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1312 if (!isListings(params()))
1316 label_->updateBuffer(it, utype);
1318 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1319 if (par.getParamValue("caption").empty()) {
1320 listings_label_ = buffer().B_("Program Listing");
1323 Buffer const & master = *buffer().masterBuffer();
1324 Counters & counters = master.params().documentClass().counters();
1325 docstring const cnt = from_ascii("listing");
1326 listings_label_ = master.B_("Program Listing");
1327 if (counters.hasCounter(cnt)) {
1328 counters.step(cnt, utype);
1329 listings_label_ += " " + convert<docstring>(counters.value(cnt));