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/FileName.h"
59 #include "support/FileNameList.h"
60 #include "support/filetools.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/lstrings.h" // contains
64 #include "support/lyxalgo.h"
65 #include "support/mutex.h"
66 #include "support/ExceptionMessage.h"
68 #include "support/bind.h"
71 using namespace lyx::support;
75 namespace Alert = frontend::Alert;
80 docstring const uniqueID()
82 static unsigned int seed = 1000;
84 Mutex::Locker lock(&mutex);
85 return "file" + convert<docstring>(++seed);
89 /// the type of inclusion
91 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
95 Types type(string const & s)
99 if (s == "verbatiminput")
101 if (s == "verbatiminput*")
103 if (s == "lstinputlisting" || s == "inputminted")
111 Types type(InsetCommandParams const & params)
113 return type(params.getCmdName());
117 bool isListings(InsetCommandParams const & params)
119 return type(params) == LISTINGS;
123 bool isVerbatim(InsetCommandParams const & params)
125 Types const t = type(params);
126 return t == VERB || t == VERBAST;
130 bool isInputOrInclude(InsetCommandParams const & params)
132 Types const t = type(params);
133 return t == INPUT || t == INCLUDE;
137 FileName const masterFileName(Buffer const & buffer)
139 return buffer.masterBuffer()->fileName();
143 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
146 string const parentFileName(Buffer const & buffer)
148 return buffer.absFileName();
152 FileName const includedFileName(Buffer const & buffer,
153 InsetCommandParams const & params)
155 return makeAbsPath(ltrim(to_utf8(params["filename"])),
156 onlyPath(parentFileName(buffer)));
160 InsetLabel * createLabel(Buffer * buf, docstring const & label_str)
162 if (label_str.empty())
164 InsetCommandParams icp(LABEL_CODE);
165 icp["name"] = label_str;
166 return new InsetLabel(buf, icp);
170 char_type replaceCommaInBraces(docstring & params)
172 // Code point from private use area
173 char_type private_char = 0xE000;
175 for (char_type & c : params) {
180 else if (c == ',' && count)
189 InsetInclude::InsetInclude(Buffer * buf, InsetCommandParams const & p)
190 : InsetCommand(buf, p), include_label(uniqueID()),
191 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
192 set_label_(false), label_(0), child_buffer_(0), file_exist_(false)
194 preview_->connect([=](){ fileChanged(); });
196 if (isListings(params())) {
197 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
198 label_ = createLabel(buffer_, from_utf8(listing_params.getParamValue("label")));
199 } else if (isInputOrInclude(params()) && buf)
204 InsetInclude::InsetInclude(InsetInclude const & other)
205 : InsetCommand(other), include_label(other.include_label),
206 preview_(make_unique<RenderMonitoredPreview>(this)), failedtoload_(false),
207 set_label_(false), label_(0), child_buffer_(0), file_exist_(other.file_exist_)
209 preview_->connect([=](){ fileChanged(); });
212 label_ = new InsetLabel(*other.label_);
216 InsetInclude::~InsetInclude()
222 void InsetInclude::setBuffer(Buffer & buffer)
224 InsetCommand::setBuffer(buffer);
226 label_->setBuffer(buffer);
230 void InsetInclude::setChildBuffer(Buffer * buffer)
232 child_buffer_ = buffer;
236 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
239 // This is only correct for the case of listings, but it'll do for now.
240 // In the other cases, this second parameter should just be empty.
241 static ParamInfo param_info_;
242 if (param_info_.empty()) {
243 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
244 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
245 param_info_.add("literal", ParamInfo::LYX_INTERNAL);
251 bool InsetInclude::isCompatibleCommand(string const & s)
253 return type(s) != NONE;
257 bool InsetInclude::needsCProtection(bool const /*maintext*/, bool const fragile) const
259 // We need to \cprotect all types in fragile context
264 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
266 switch (cmd.action()) {
268 case LFUN_INSET_EDIT: {
269 editIncluded(ltrim(to_utf8(params()["filename"])));
273 case LFUN_INSET_MODIFY: {
274 // It should be OK just to invalidate the cache in setParams()
276 // child_buffer_ = 0;
277 InsetCommandParams p(INCLUDE_CODE);
278 if (cmd.getArg(0) == "changetype") {
280 InsetCommand::doDispatch(cur, cmd);
283 InsetCommand::string2params(to_utf8(cmd.argument()), p);
284 if (!p.getCmdName().empty()) {
286 InsetListingsParams new_params(to_utf8(p["lstparams"]));
287 docstring const new_label =
288 from_utf8(new_params.getParamValue("label"));
290 if (new_label.empty()) {
296 old_label = label_->getParam("name");
298 label_ = createLabel(buffer_, new_label);
299 label_->setBuffer(buffer());
302 if (new_label != old_label) {
303 label_->updateLabelAndRefs(new_label, &cur);
304 // the label might have been adapted (duplicate)
305 if (new_label != label_->getParam("name")) {
306 new_params.addParam("label", "{" +
307 to_utf8(label_->getParam("name")) + "}", true);
308 p["lstparams"] = from_utf8(new_params.params());
315 cur.forceBufferUpdate();
317 cur.noScreenUpdate();
321 case LFUN_MOUSE_RELEASE: {
322 if (cmd.modifier() == ControlModifier) {
323 FileName const incfile = includedFileName(buffer(), params());
324 string const & incname = incfile.absFileName();
325 editIncluded(incname);
331 //pass everything else up the chain
333 InsetCommand::doDispatch(cur, cmd);
339 void InsetInclude::editIncluded(string const & f)
341 if (isLyXFileName(f)) {
342 FuncRequest fr(LFUN_BUFFER_CHILD_OPEN, f);
345 // tex file or other text file in verbatim mode
346 theFormats().edit(buffer(),
347 support::makeAbsPath(f, support::onlyPath(buffer().absFileName())),
352 bool InsetInclude::getStatus(Cursor & cur, FuncRequest const & cmd,
353 FuncStatus & flag) const
355 switch (cmd.action()) {
357 case LFUN_INSET_EDIT:
358 flag.setEnabled(true);
361 case LFUN_INSET_MODIFY:
362 if (cmd.getArg(0) == "changetype")
363 return InsetCommand::getStatus(cur, cmd, flag);
365 flag.setEnabled(true);
369 return InsetCommand::getStatus(cur, cmd, flag);
374 void InsetInclude::setParams(InsetCommandParams const & p)
376 // invalidate the cache
379 InsetCommand::setParams(p);
382 if (preview_->monitoring())
383 preview_->stopMonitoring();
385 if (type(params()) == INPUT)
386 add_preview(*preview_, *this, buffer());
390 bool InsetInclude::isChildIncluded() const
392 std::list<std::string> includeonlys =
393 buffer().params().getIncludedChildren();
394 if (includeonlys.empty())
396 return (std::find(includeonlys.begin(),
398 ltrim(to_utf8(params()["filename"]))) != includeonlys.end());
402 docstring InsetInclude::screenLabel() const
404 docstring pre = file_exist_ ? docstring() : _("FILE MISSING:");
408 switch (type(params())) {
410 temp = buffer().B_("Input");
413 temp = buffer().B_("Verbatim Input");
416 temp = buffer().B_("Verbatim Input*");
419 if (isChildIncluded())
420 temp = buffer().B_("Include");
422 temp += buffer().B_("Include (excluded)");
425 temp = listings_label_;
428 LASSERT(false, temp = buffer().B_("Unknown"));
434 if (ltrim(params()["filename"]).empty())
437 temp += from_utf8(onlyFileName(ltrim(to_utf8(params()["filename"]))));
439 return pre.empty() ? temp : pre + from_ascii(" ") + temp;
443 Buffer * InsetInclude::getChildBuffer() const
445 Buffer * childBuffer = loadIfNeeded();
447 // FIXME RECURSIVE INCLUDE
448 // This isn't sufficient, as the inclusion could be downstream.
449 // But it'll have to do for now.
450 return (childBuffer == &buffer()) ? 0 : childBuffer;
454 Buffer * InsetInclude::loadIfNeeded() const
456 // This is for background export and preview. We don't even want to
457 // try to load the cloned child document again.
458 if (buffer().isClone())
459 return child_buffer_;
461 // Don't try to load it again if we failed before.
462 if (failedtoload_ || isVerbatim(params()) || isListings(params()))
465 FileName const included_file = includedFileName(buffer(), params());
466 // Use cached Buffer if possible.
467 if (child_buffer_ != 0) {
468 if (theBufferList().isLoaded(child_buffer_)
469 // additional sanity check: make sure the Buffer really is
470 // associated with the file we want.
471 && child_buffer_ == theBufferList().getBuffer(included_file))
472 return child_buffer_;
473 // Buffer vanished, so invalidate cache and try to reload.
477 if (!isLyXFileName(included_file.absFileName()))
480 Buffer * child = theBufferList().getBuffer(included_file);
482 // the readonly flag can/will be wrong, not anymore I think.
483 if (!included_file.exists())
486 child = theBufferList().newBuffer(included_file.absFileName());
488 // Buffer creation is not possible.
491 // Set parent before loading, such that macros can be tracked
492 child->setParent(&buffer());
494 if (child->loadLyXFile() != Buffer::ReadSuccess) {
495 failedtoload_ = true;
497 //close the buffer we just opened
498 theBufferList().release(child);
502 if (!child->errorList("Parse").empty()) {
503 // FIXME: Do something.
506 // The file was already loaded, so, simply
507 // inform parent buffer about local macros.
508 Buffer const * parent = &buffer();
509 child->setParent(parent);
511 child->listMacroNames(macros);
512 MacroNameSet::const_iterator cit = macros.begin();
513 MacroNameSet::const_iterator end = macros.end();
514 for (; cit != end; ++cit)
515 parent->usermacros.insert(*cit);
518 // Cache the child buffer.
519 child_buffer_ = child;
524 void InsetInclude::latex(otexstream & os, OutputParams const & runparams) const
526 string incfile = ltrim(to_utf8(params()["filename"]));
528 // Warn if no file name has been specified
529 if (incfile.empty()) {
530 frontend::Alert::warning(_("No file name specified"),
531 _("An included file name is empty.\n"
532 "Ignoring Inclusion"),
536 // Warn if file doesn't exist
537 if (!includedFileExist()) {
538 frontend::Alert::warning(_("Included file not found"),
539 bformat(_("The included file\n"
541 "has not been found. LyX will ignore the inclusion."),
547 FileName const included_file = includedFileName(buffer(), params());
549 // Check we're not trying to include ourselves.
550 // FIXME RECURSIVE INCLUDE
551 // This isn't sufficient, as the inclusion could be downstream.
552 // But it'll have to do for now.
553 if (isInputOrInclude(params()) &&
554 buffer().absFileName() == included_file.absFileName())
556 Alert::error(_("Recursive input"),
557 bformat(_("Attempted to include file %1$s in itself! "
558 "Ignoring inclusion."), from_utf8(incfile)));
562 Buffer const * const masterBuffer = buffer().masterBuffer();
564 // if incfile is relative, make it relative to the master
566 if (!FileName::isAbsolute(incfile)) {
568 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFileName()),
569 from_utf8(masterBuffer->filePath())));
572 string exppath = incfile;
573 if (!runparams.export_folder.empty()) {
574 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
575 FileName(exppath).onlyPath().createPath();
578 // write it to a file (so far the complete file)
582 if (type(params()) == LISTINGS) {
583 exportfile = exppath;
584 mangled = DocFileName(included_file).mangledFileName();
586 exportfile = changeExtension(exppath, ".tex");
587 mangled = DocFileName(changeExtension(included_file.absFileName(), ".tex")).
593 else if (!runparams.silent)
594 ; // no warning wanted
595 else if (!isValidLaTeXFileName(incfile)) {
596 frontend::Alert::warning(_("Invalid filename"),
597 _("The following filename will cause troubles "
598 "when running the exported file through LaTeX: ") +
600 } else if (!isValidDVIFileName(incfile)) {
601 frontend::Alert::warning(_("Problematic filename for DVI"),
602 _("The following filename can cause troubles "
603 "when running the exported file through LaTeX "
604 "and opening the resulting DVI: ") +
605 from_utf8(incfile), true);
608 FileName const writefile(makeAbsPath(mangled, runparams.for_preview ?
609 buffer().temppath() : masterBuffer->temppath()));
611 LYXERR(Debug::LATEX, "incfile:" << incfile);
612 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
613 LYXERR(Debug::LATEX, "writefile:" << writefile);
615 string const tex_format = flavor2format(runparams.flavor);
617 switch (type(params())) {
620 incfile = latex_path(incfile);
622 os << '\\' << from_ascii(params().getCmdName()) << '{'
623 << from_utf8(incfile) << '}';
627 runparams.exportdata->addExternalFile(tex_format, writefile,
630 // \input wants file with extension (default is .tex)
631 if (!isLyXFileName(included_file.absFileName())) {
632 incfile = latex_path(incfile);
634 os << '\\' << from_ascii(params().getCmdName())
635 << '{' << from_utf8(incfile) << '}';
637 incfile = changeExtension(incfile, ".tex");
638 incfile = latex_path(incfile);
640 os << '\\' << from_ascii(params().getCmdName())
641 << '{' << from_utf8(incfile) << '}';
646 // Here, listings and minted have sligthly different behaviors.
647 // Using listings, it is always possible to have a caption,
648 // even for non-floats. Using minted, only floats can have a
649 // caption. So, with minted we use the following strategy.
650 // If a caption was specified but the float parameter was not,
651 // we ourselves add a caption above the listing (because the
652 // listing comes from a file and might span several pages).
653 // Otherwise, if float was specified, the floating listing
654 // environment provided by minted is used. In either case, the
655 // label parameter is taken as the label by which the float
656 // can be referenced, otherwise it will have the meaning
657 // intended by minted. In this last case, the label will
658 // serve as a sort of caption that, however, will be shown
659 // by minted only if the frame parameter is also specified.
660 bool const use_minted = buffer().params().use_minted;
661 runparams.exportdata->addExternalFile(tex_format, writefile,
663 string const opt = to_utf8(params()["lstparams"]);
664 // opt is set in QInclude dialog and should have passed validation.
665 InsetListingsParams lstparams(opt);
666 docstring parameters = from_utf8(lstparams.params());
671 bool isfloat = lstparams.isFloat();
672 // We are going to split parameters at commas, so
673 // replace commas that are not parameter separators
674 // with a code point from the private use area
675 char_type comma = replaceCommaInBraces(parameters);
676 // Get float placement, language, caption, and
677 // label, then remove the relative options if minted.
678 vector<docstring> opts =
679 getVectorFromString(parameters, from_ascii(","), false);
680 vector<docstring> latexed_opts;
681 for (size_t i = 0; i < opts.size(); ++i) {
682 // Restore replaced commas
683 opts[i] = subst(opts[i], comma, ',');
684 if (use_minted && prefixIs(opts[i], from_ascii("float"))) {
685 if (prefixIs(opts[i], from_ascii("float=")))
686 placement = opts[i].substr(6);
687 opts.erase(opts.begin() + i--);
688 } else if (use_minted && prefixIs(opts[i], from_ascii("language="))) {
689 language = opts[i].substr(9);
690 opts.erase(opts.begin() + i--);
691 } else if (prefixIs(opts[i], from_ascii("caption="))) {
692 caption = params().prepareCommand(runparams, trim(opts[i].substr(8), "{}"),
693 ParamInfo::HANDLING_LATEXIFY);
694 opts.erase(opts.begin() + i--);
696 latexed_opts.push_back(from_ascii("caption={") + caption + "}");
697 } else if (prefixIs(opts[i], from_ascii("label="))) {
698 label = params().prepareCommand(runparams, trim(opts[i].substr(6), "{}"),
699 ParamInfo::HANDLING_ESCAPE);
700 opts.erase(opts.begin() + i--);
702 latexed_opts.push_back(from_ascii("label={") + label + "}");
704 if (use_minted && !label.empty()) {
705 if (isfloat || !caption.empty())
706 label = trim(label, "{}");
708 opts.push_back(from_ascii("label=") + label);
711 if (!latexed_opts.empty())
712 opts.insert(opts.end(), latexed_opts.begin(), latexed_opts.end());
713 parameters = getStringFromVector(opts, from_ascii(","));
714 if (language.empty())
715 language = from_ascii("TeX");
716 if (use_minted && isfloat) {
717 os << breakln << "\\begin{listing}";
718 if (!placement.empty())
719 os << '[' << placement << "]";
721 } else if (use_minted && !caption.empty()) {
722 os << breakln << "\\lyxmintcaption[t]{" << caption;
724 os << "\\label{" << label << "}";
727 os << (use_minted ? "\\inputminted" : "\\lstinputlisting");
728 if (!parameters.empty())
729 os << "[" << parameters << "]";
731 os << '{' << ascii_lowercase(language) << '}';
732 os << '{' << incfile << '}';
733 if (use_minted && isfloat) {
734 if (!caption.empty())
735 os << breakln << "\\caption{" << caption << "}";
737 os << breakln << "\\label{" << label << "}";
738 os << breakln << "\\end{listing}\n";
743 runparams.exportdata->addExternalFile(tex_format, writefile,
746 // \include don't want extension and demands that the
747 // file really have .tex
748 incfile = changeExtension(incfile, string());
749 incfile = latex_path(incfile);
751 os << '\\' << from_ascii(params().getCmdName()) << '{'
752 << from_utf8(incfile) << '}';
759 if (runparams.inComment || runparams.dryrun)
760 // Don't try to load or copy the file if we're
761 // in a comment or doing a dryrun
764 if (isInputOrInclude(params()) &&
765 isLyXFileName(included_file.absFileName())) {
766 // if it's a LyX file and we're inputting or including,
767 // try to load it so we can write the associated latex
769 Buffer * tmp = loadIfNeeded();
771 if (!runparams.silent) {
772 docstring text = bformat(_("Could not load included "
774 "Please, check whether it actually exists."),
775 included_file.displayName());
776 throw ExceptionMessage(ErrorException, _("Error: "),
782 if (!runparams.silent) {
783 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
785 docstring text = bformat(_("Included file `%1$s'\n"
786 "has textclass `%2$s'\n"
787 "while parent file has textclass `%3$s'."),
788 included_file.displayName(),
789 from_utf8(tmp->params().documentClass().name()),
790 from_utf8(masterBuffer->params().documentClass().name()));
791 Alert::warning(_("Different textclasses"), text, true);
794 string const child_tf = tmp->params().useNonTeXFonts ? "true" : "false";
795 string const master_tf = masterBuffer->params().useNonTeXFonts ? "true" : "false";
796 if (tmp->params().useNonTeXFonts != masterBuffer->params().useNonTeXFonts) {
797 docstring text = bformat(_("Included file `%1$s'\n"
798 "has use-non-TeX-fonts set to `%2$s'\n"
799 "while parent file has use-non-TeX-fonts set to `%3$s'."),
800 included_file.displayName(),
802 from_utf8(master_tf));
803 Alert::warning(_("Different use-non-TeX-fonts settings"), text, true);
805 else if (tmp->params().inputenc != masterBuffer->params().inputenc) {
806 docstring text = bformat(_("Included file `%1$s'\n"
807 "uses input encoding \"%2$s\" [%3$s]\n"
808 "while parent file uses input encoding \"%4$s\" [%5$s]."),
809 included_file.displayName(),
810 _(tmp->params().inputenc),
811 from_utf8(tmp->params().encoding().guiName()),
812 _(masterBuffer->params().inputenc),
813 from_utf8(masterBuffer->params().encoding().guiName()));
814 Alert::warning(_("Different LaTeX input encodings"), text, true);
817 // Make sure modules used in child are all included in master
818 // FIXME It might be worth loading the children's modules into the master
819 // over in BufferParams rather than doing this check.
820 LayoutModuleList const masterModules = masterBuffer->params().getModules();
821 LayoutModuleList const childModules = tmp->params().getModules();
822 LayoutModuleList::const_iterator it = childModules.begin();
823 LayoutModuleList::const_iterator end = childModules.end();
824 for (; it != end; ++it) {
825 string const module = *it;
826 LayoutModuleList::const_iterator found =
827 find(masterModules.begin(), masterModules.end(), module);
828 if (found == masterModules.end()) {
829 docstring text = bformat(_("Included file `%1$s'\n"
830 "uses module `%2$s'\n"
831 "which is not used in parent file."),
832 included_file.displayName(), from_utf8(module));
833 Alert::warning(_("Module not found"), text, true);
838 tmp->markDepClean(masterBuffer->temppath());
840 // Don't assume the child's format is latex
841 string const inc_format = tmp->params().bufferFormat();
842 FileName const tmpwritefile(changeExtension(writefile.absFileName(),
843 theFormats().extension(inc_format)));
845 // FIXME: handle non existing files
846 // The included file might be written in a different encoding
848 Encoding const * const oldEnc = runparams.encoding;
849 Language const * const oldLang = runparams.master_language;
850 // If the master uses non-TeX fonts (XeTeX, LuaTeX),
851 // the children must be encoded in plain utf8!
852 runparams.encoding = masterBuffer->params().useNonTeXFonts ?
853 encodings.fromLyXName("utf8-plain") : oldEnc;
854 runparams.master_language = buffer().params().language;
855 runparams.par_begin = 0;
856 runparams.par_end = tmp->paragraphs().size();
857 runparams.is_child = true;
858 Buffer::ExportStatus retval =
859 tmp->makeLaTeXFile(tmpwritefile, masterFileName(buffer()).
860 onlyPath().absFileName(), runparams, Buffer::OnlyBody);
861 if (retval == Buffer::ExportKilled && buffer().isClone() &&
862 buffer().isExporting()) {
863 // We really shouldn't get here, I don't think.
864 LYXERR0("No conversion exception?");
865 throw ConversionException();
867 else if (retval != Buffer::ExportSuccess) {
868 if (!runparams.silent) {
869 docstring msg = bformat(_("Included file `%1$s' "
870 "was not exported correctly.\n "
871 "LaTeX export is probably incomplete."),
872 included_file.displayName());
873 ErrorList const & el = tmp->errorList("Export");
875 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
876 msg, el.begin()->error, el.begin()->description);
877 throw ExceptionMessage(ErrorException, _("Error: "), msg);
880 runparams.encoding = oldEnc;
881 runparams.master_language = oldLang;
882 runparams.is_child = false;
884 // If needed, use converters to produce a latex file from the child
885 if (tmpwritefile != writefile) {
887 Converters::RetVal const retval =
888 theConverters().convert(tmp, tmpwritefile, writefile,
889 included_file, inc_format, tex_format, el);
890 if (retval == Converters::KILLED && buffer().isClone() &&
891 buffer().isExporting()) {
892 // We really shouldn't get here, I don't think.
893 LYXERR0("No conversion exception?");
894 throw ConversionException();
895 } else if (retval != Converters::SUCCESS && !runparams.silent) {
896 docstring msg = bformat(_("Included file `%1$s' "
897 "was not exported correctly.\n "
898 "LaTeX export is probably incomplete."),
899 included_file.displayName());
901 msg = bformat(from_ascii("%1$s\n\n%2$s\n\n%3$s"),
902 msg, el.begin()->error, el.begin()->description);
903 throw ExceptionMessage(ErrorException, _("Error: "), msg);
907 // In this case, it's not a LyX file, so we copy the file
908 // to the temp dir, so that .aux files etc. are not created
909 // in the original dir. Files included by this file will be
910 // found via either the environment variable TEXINPUTS, or
911 // input@path, see ../Buffer.cpp.
912 unsigned long const checksum_in = included_file.checksum();
913 unsigned long const checksum_out = writefile.checksum();
915 if (checksum_in != checksum_out) {
916 if (!included_file.copyTo(writefile)) {
919 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
920 "into the temporary directory."),
921 from_utf8(included_file.absFileName()))));
929 docstring InsetInclude::xhtml(XHTMLStream & xs, OutputParams const & rp) const
934 // For verbatim and listings, we just include the contents of the file as-is.
935 // In the case of listings, we wrap it in <pre>.
936 bool const listing = isListings(params());
937 if (listing || isVerbatim(params())) {
939 xs << html::StartTag("pre");
940 // FIXME: We don't know the encoding of the file, default to UTF-8.
941 xs << includedFileName(buffer(), params()).fileContents("UTF-8");
943 xs << html::EndTag("pre");
947 // We don't (yet) know how to Input or Include non-LyX files.
948 // (If we wanted to get really arcane, we could run some tex2html
949 // converter on the included file. But that's just masochistic.)
950 FileName const included_file = includedFileName(buffer(), params());
951 if (!isLyXFileName(included_file.absFileName())) {
953 frontend::Alert::warning(_("Unsupported Inclusion"),
954 bformat(_("LyX does not know how to include non-LyX files when "
955 "generating HTML output. Offending file:\n%1$s"),
956 ltrim(params()["filename"])));
960 // In the other cases, we will generate the HTML and include it.
962 // Check we're not trying to include ourselves.
963 // FIXME RECURSIVE INCLUDE
964 if (buffer().absFileName() == included_file.absFileName()) {
965 Alert::error(_("Recursive input"),
966 bformat(_("Attempted to include file %1$s in itself! "
967 "Ignoring inclusion."), ltrim(params()["filename"])));
971 Buffer const * const ibuf = loadIfNeeded();
975 // are we generating only some paragraphs, or all of them?
976 bool const all_pars = !rp.dryrun ||
977 (rp.par_begin == 0 &&
978 rp.par_end == (int)buffer().text().paragraphs().size());
980 OutputParams op = rp;
984 ibuf->writeLyXHTMLSource(xs.os(), op, Buffer::IncludedFile);
986 xs << XHTMLStream::ESCAPE_NONE
987 << "<!-- Included file: "
988 << from_utf8(included_file.absFileName())
989 << XHTMLStream::ESCAPE_NONE
995 int InsetInclude::plaintext(odocstringstream & os,
996 OutputParams const & op, size_t) const
998 // just write the filename if we're making a tooltip or toc entry,
999 // or are generating this for advanced search
1000 if (op.for_tooltip || op.for_toc || op.for_search) {
1001 os << '[' << screenLabel() << '\n'
1002 << ltrim(getParam("filename")) << "\n]";
1003 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1006 if (isVerbatim(params()) || isListings(params())) {
1007 if (op.for_search) {
1008 os << '[' << screenLabel() << ']';
1011 os << '[' << screenLabel() << '\n'
1012 // FIXME: We don't know the encoding of the file, default to UTF-8.
1013 << includedFileName(buffer(), params()).fileContents("UTF-8")
1016 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
1019 Buffer const * const ibuf = loadIfNeeded();
1021 docstring const str = '[' + screenLabel() + ']';
1025 writePlaintextFile(*ibuf, os, op);
1030 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
1032 string incfile = ltrim(to_utf8(params()["filename"]));
1034 // Do nothing if no file name has been specified
1035 if (incfile.empty())
1038 string const included_file = includedFileName(buffer(), params()).absFileName();
1040 // Check we're not trying to include ourselves.
1041 // FIXME RECURSIVE INCLUDE
1042 // This isn't sufficient, as the inclusion could be downstream.
1043 // But it'll have to do for now.
1044 if (buffer().absFileName() == included_file) {
1045 Alert::error(_("Recursive input"),
1046 bformat(_("Attempted to include file %1$s in itself! "
1047 "Ignoring inclusion."), from_utf8(incfile)));
1051 string exppath = incfile;
1052 if (!runparams.export_folder.empty()) {
1053 exppath = makeAbsPath(exppath, runparams.export_folder).realPath();
1054 FileName(exppath).onlyPath().createPath();
1057 // write it to a file (so far the complete file)
1058 string const exportfile = changeExtension(exppath, ".sgml");
1059 DocFileName writefile(changeExtension(included_file, ".sgml"));
1061 Buffer * tmp = loadIfNeeded();
1063 string const mangled = writefile.mangledFileName();
1064 writefile = makeAbsPath(mangled,
1065 buffer().masterBuffer()->temppath());
1066 if (!runparams.nice)
1069 LYXERR(Debug::LATEX, "incfile:" << incfile);
1070 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
1071 LYXERR(Debug::LATEX, "writefile:" << writefile);
1073 tmp->makeDocBookFile(writefile, runparams, Buffer::OnlyBody);
1076 runparams.exportdata->addExternalFile("docbook", writefile,
1078 runparams.exportdata->addExternalFile("docbook-xml", writefile,
1081 if (isVerbatim(params()) || isListings(params())) {
1082 os << "<inlinegraphic fileref=\""
1083 << '&' << include_label << ';'
1084 << "\" format=\"linespecific\">";
1086 os << '&' << include_label << ';';
1092 void InsetInclude::validate(LaTeXFeatures & features) const
1094 LATTEST(&buffer() == &features.buffer());
1096 string incfile = ltrim(to_utf8(params()["filename"]));
1097 string const included_file =
1098 includedFileName(buffer(), params()).absFileName();
1101 if (isLyXFileName(included_file))
1102 writefile = changeExtension(included_file, ".sgml");
1104 writefile = included_file;
1106 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
1107 incfile = DocFileName(writefile).mangledFileName();
1108 writefile = makeAbsPath(incfile,
1109 buffer().masterBuffer()->temppath()).absFileName();
1112 features.includeFile(include_label, writefile);
1114 features.useInsetLayout(getLayout());
1115 if (isVerbatim(params()))
1116 features.require("verbatim");
1117 else if (isListings(params())) {
1118 if (buffer().params().use_minted) {
1119 features.require("minted");
1120 string const opts = to_utf8(params()["lstparams"]);
1121 InsetListingsParams lstpars(opts);
1122 if (!lstpars.isFloat() && contains(opts, "caption="))
1123 features.require("lyxmintcaption");
1125 features.require("listings");
1128 // Here we must do the fun stuff...
1129 // Load the file in the include if it needs
1131 Buffer * const tmp = loadIfNeeded();
1133 // the file is loaded
1134 // make sure the buffer isn't us
1135 // FIXME RECURSIVE INCLUDES
1136 // This is not sufficient, as recursive includes could be
1137 // more than a file away. But it will do for now.
1138 if (tmp && tmp != &buffer()) {
1139 // We must temporarily change features.buffer,
1140 // otherwise it would always be the master buffer,
1141 // and nested includes would not work.
1142 features.setBuffer(*tmp);
1143 // Maybe this is already a child
1144 bool const is_child =
1145 features.runparams().is_child;
1146 features.runparams().is_child = true;
1147 tmp->validate(features);
1148 features.runparams().is_child = is_child;
1149 features.setBuffer(buffer());
1155 void InsetInclude::collectBibKeys(InsetIterator const & /*di*/, FileNameList & checkedFiles) const
1157 Buffer * child = loadIfNeeded();
1160 // FIXME RECURSIVE INCLUDE
1161 // This isn't sufficient, as the inclusion could be downstream.
1162 // But it'll have to do for now.
1163 if (child == &buffer())
1165 child->collectBibKeys(checkedFiles);
1169 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
1171 LBUFERR(mi.base.bv);
1173 bool use_preview = false;
1174 if (RenderPreview::previewText()) {
1175 graphics::PreviewImage const * pimage =
1176 preview_->getPreviewImage(mi.base.bv->buffer());
1177 use_preview = pimage && pimage->image();
1181 preview_->metrics(mi, dim);
1185 button_.update(screenLabel(), true, false);
1187 button_.metrics(mi, dim);
1190 Box b(0, dim.wid, -dim.asc, dim.des);
1195 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
1197 LBUFERR(pi.base.bv);
1199 bool use_preview = false;
1200 if (RenderPreview::previewText()) {
1201 graphics::PreviewImage const * pimage =
1202 preview_->getPreviewImage(pi.base.bv->buffer());
1203 use_preview = pimage && pimage->image();
1207 preview_->draw(pi, x, y);
1209 button_.draw(pi, x, y);
1213 void InsetInclude::write(ostream & os) const
1215 params().Write(os, &buffer());
1219 string InsetInclude::contextMenuName() const
1221 return "context-include";
1225 Inset::DisplayType InsetInclude::display() const
1227 return type(params()) == INPUT ? Inline : AlignCenter;
1231 docstring InsetInclude::layoutName() const
1233 if (isListings(params()))
1234 return from_ascii("IncludeListings");
1235 return InsetCommand::layoutName();
1243 void InsetInclude::fileChanged() const
1245 Buffer const * const buffer = updateFrontend();
1249 preview_->removePreview(*buffer);
1250 add_preview(*preview_, *this, *buffer);
1251 preview_->startLoading(*buffer);
1257 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
1259 FileName const included_file = includedFileName(buffer, params);
1261 return type(params) == INPUT && params.preview() &&
1262 included_file.isReadableFile();
1266 docstring latexString(InsetInclude const & inset)
1268 odocstringstream ods;
1270 // We don't need to set runparams.encoding since this will be done
1271 // by latex() anyway.
1272 OutputParams runparams(0);
1273 runparams.flavor = OutputParams::LATEX;
1274 runparams.for_preview = true;
1275 inset.latex(os, runparams);
1281 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
1282 Buffer const & buffer)
1284 InsetCommandParams const & params = inset.params();
1285 if (RenderPreview::previewText() && preview_wanted(params, buffer)) {
1286 renderer.setAbsFile(includedFileName(buffer, params));
1287 docstring const snippet = latexString(inset);
1288 renderer.addPreview(snippet, buffer);
1295 void InsetInclude::addPreview(DocIterator const & /*inset_pos*/,
1296 graphics::PreviewLoader & ploader) const
1298 Buffer const & buffer = ploader.buffer();
1299 if (!preview_wanted(params(), buffer))
1301 preview_->setAbsFile(includedFileName(buffer, params()));
1302 docstring const snippet = latexString(*this);
1303 preview_->addPreview(snippet, ploader);
1307 void InsetInclude::addToToc(DocIterator const & cpit, bool output_active,
1308 UpdateType utype, TocBackend & backend) const
1310 if (isListings(params())) {
1312 label_->addToToc(cpit, output_active, utype, backend);
1313 TocBuilder & b = backend.builder("listing");
1314 b.pushItem(cpit, screenLabel(), output_active);
1315 InsetListingsParams p(to_utf8(params()["lstparams"]));
1316 b.argumentItem(from_utf8(p.getParamValue("caption")));
1319 Buffer const * const childbuffer = getChildBuffer();
1321 TocBuilder & b = backend.builder("child");
1322 docstring str = childbuffer ? childbuffer->fileName().displayName()
1324 b.pushItem(cpit, str, output_active);
1330 // Update the child's tocBackend. The outliner uses the master's, but
1331 // the navigation menu uses the child's.
1332 childbuffer->tocBackend().update(output_active, utype);
1333 // Include Tocs from children
1334 childbuffer->inset().addToToc(DocIterator(), output_active, utype,
1336 //Copy missing outliner names (though the user has been warned against
1337 //having different document class and module selection between master
1339 for (pair<string, docstring> const & name
1340 : childbuffer->params().documentClass().outlinerNames())
1341 backend.addName(name.first, translateIfPossible(name.second));
1346 void InsetInclude::updateCommand()
1351 docstring old_label = label_->getParam("name");
1352 label_->updateLabel(old_label);
1353 // the label might have been adapted (duplicate)
1354 docstring new_label = label_->getParam("name");
1355 if (old_label == new_label)
1358 // update listings parameters...
1359 InsetCommandParams p(INCLUDE_CODE);
1361 InsetListingsParams par(to_utf8(params()["lstparams"]));
1362 par.addParam("label", "{" + to_utf8(new_label) + "}", true);
1363 p["lstparams"] = from_utf8(par.params());
1368 void InsetInclude::updateBuffer(ParIterator const & it, UpdateType utype)
1370 file_exist_ = includedFileExist();
1372 button_.update(screenLabel(), true, false);
1374 Buffer const * const childbuffer = getChildBuffer();
1376 childbuffer->updateBuffer(Buffer::UpdateChildOnly, utype);
1379 if (!isListings(params()))
1383 label_->updateBuffer(it, utype);
1385 InsetListingsParams const par(to_utf8(params()["lstparams"]));
1386 if (par.getParamValue("caption").empty()) {
1387 listings_label_ = buffer().B_("Program Listing");
1390 Buffer const & master = *buffer().masterBuffer();
1391 Counters & counters = master.params().documentClass().counters();
1392 docstring const cnt = from_ascii("listing");
1393 listings_label_ = master.B_("Program Listing");
1394 if (counters.hasCounter(cnt)) {
1395 counters.step(cnt, utype);
1396 listings_label_ += " " + convert<docstring>(counters.value(cnt));
1401 bool InsetInclude::includedFileExist() const
1403 // check whether the included file exist
1404 string incFileName = ltrim(to_utf8(params()["filename"]));
1406 support::makeAbsPath(incFileName,
1407 support::onlyPath(buffer().absFileName()));