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)
8 * \author Bo Peng (embedding stuff)
10 * Full author contact details are available in file CREDITS.
15 #include "InsetInclude.h"
17 #include "LayoutFile.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
24 #include "DispatchResult.h"
25 #include "ErrorList.h"
27 #include "FuncRequest.h"
28 #include "FuncStatus.h"
29 #include "LaTeXFeatures.h"
33 #include "MetricsInfo.h"
34 #include "OutputParams.h"
35 #include "TextClass.h"
36 #include "TocBackend.h"
38 #include "frontends/alert.h"
39 #include "frontends/Painter.h"
41 #include "graphics/PreviewImage.h"
42 #include "graphics/PreviewLoader.h"
44 #include "insets/InsetLabel.h"
45 #include "insets/InsetListingsParams.h"
46 #include "insets/RenderPreview.h"
48 #include "support/debug.h"
49 #include "support/docstream.h"
50 #include "support/FileNameList.h"
51 #include "support/filetools.h"
52 #include "support/gettext.h"
53 #include "support/lstrings.h" // contains
54 #include "support/lyxalgo.h"
55 #include "support/convert.h"
57 #include <boost/bind.hpp>
60 using namespace lyx::support;
64 namespace Alert = frontend::Alert;
69 docstring const uniqueID()
71 static unsigned int seed = 1000;
72 return "file" + convert<docstring>(++seed);
76 /// the type of inclusion
78 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
82 Types type(string const & s)
86 if (s == "verbatiminput")
88 if (s == "verbatiminput*")
90 if (s == "lstinputlisting")
98 Types type(InsetCommandParams const & params)
100 return type(params.getCmdName());
104 bool isListings(InsetCommandParams const & params)
106 return type(params) == LISTINGS;
110 bool isVerbatim(InsetCommandParams const & params)
112 Types const t = type(params);
113 return t == VERB || t == VERBAST;
117 bool isInputOrInclude(InsetCommandParams const & params)
119 Types const t = type(params);
120 return t == INPUT || t == INCLUDE;
124 FileName const masterFileName(Buffer const & buffer)
126 return buffer.masterBuffer()->fileName();
130 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
133 string const parentFilename(Buffer const & buffer)
135 return buffer.absFileName();
139 EmbeddedFile const includedFilename(Buffer const & buffer,
140 InsetCommandParams const & params)
142 // it is not a good idea to create this EmbeddedFile object
143 // each time, but there seems to be no easy way around.
144 EmbeddedFile file(to_utf8(params["filename"]),
145 onlyPath(parentFilename(buffer)));
146 file.setEmbed(!params["embed"].empty());
147 file.setInzipName(to_utf8(params["embed"]));
148 file.enable(buffer.embedded(), &buffer, false);
152 InsetLabel * createLabel(docstring const & label_str)
154 if (label_str.empty())
156 InsetCommandParams icp(LABEL_CODE);
157 icp["name"] = label_str;
158 return new InsetLabel(icp);
164 InsetInclude::InsetInclude(InsetCommandParams const & p)
165 : InsetCommand(p, "include"), include_label(uniqueID()),
166 preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
168 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
170 if (isListings(params())) {
171 InsetListingsParams listing_params(to_utf8(p["lstparams"]));
172 label_ = createLabel(from_utf8(listing_params.getParamValue("label")));
177 InsetInclude::InsetInclude(InsetInclude const & other)
178 : InsetCommand(other), include_label(other.include_label),
179 preview_(new RenderMonitoredPreview(this)), set_label_(false), label_(0)
181 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
184 label_ = new InsetLabel(*other.label_);
188 InsetInclude::~InsetInclude()
191 if (isVerbatim(params()) || isListings(params()))
195 string const parent_filename = buffer().absFileName();
196 FileName const included_file = makeAbsPath(to_utf8(params()["filename"]),
197 onlyPath(parent_filename));
199 if (!isLyXFilename(included_file.absFilename()))
202 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
203 // File not opened, nothing to close.
207 // Child document has a different parent, don't close it.
208 if (child->parent() != &buffer())
212 theBufferList().release(child);
216 void InsetInclude::setBuffer(Buffer & buffer)
220 label_->setBuffer(buffer);
225 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
228 // This is only correct for the case of listings, but it'll do for now.
229 // In the other cases, this second parameter should just be empty.
230 static ParamInfo param_info_;
231 if (param_info_.empty()) {
232 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
233 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
234 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
240 bool InsetInclude::isCompatibleCommand(string const & s)
242 return type(s) != NONE;
246 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
248 BOOST_ASSERT(&cur.buffer() == &buffer());
249 switch (cmd.action) {
251 case LFUN_INSET_MODIFY: {
252 InsetCommandParams p(INCLUDE_CODE);
253 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
254 if (!p.getCmdName().empty()) {
255 Buffer const & buf = cur.buffer();
257 InsetListingsParams new_params(to_utf8(p["lstparams"]));
258 docstring const label_str = from_utf8(new_params.getParamValue("label"));
259 if (label_str.empty())
262 label_->updateCommand(label_str);
264 label_ = createLabel(label_str);
265 label_->setBuffer(buffer());
270 buffer().updateBibfilesCache();
276 //pass everything else up the chain
278 InsetCommand::doDispatch(cur, cmd);
284 void InsetInclude::setParams(InsetCommandParams const & p)
286 InsetCommand::setParams(p);
289 if (preview_->monitoring())
290 preview_->stopMonitoring();
292 if (type(params()) == INPUT)
293 add_preview(*preview_, *this, buffer());
297 docstring InsetInclude::screenLabel() const
301 switch (type(params())) {
303 temp = buffer().B_("Input");
306 temp = buffer().B_("Verbatim Input");
309 temp = buffer().B_("Verbatim Input*");
312 temp = buffer().B_("Include");
315 temp = listings_label_;
323 if (params()["filename"].empty())
326 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
328 if (!params()["embed"].empty())
329 temp += _(" (embedded)");
334 /// return the child buffer if the file is a LyX doc and is loaded
335 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
337 if (isVerbatim(params) || isListings(params))
340 string const included_file = includedFilename(buffer, params).absFilename();
341 if (!isLyXFilename(included_file))
344 Buffer * childBuffer = loadIfNeeded(buffer, params);
346 // FIXME: recursive includes
347 return (childBuffer == &buffer) ? 0 : childBuffer;
351 /// return true if the file is or got loaded.
352 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
354 if (isVerbatim(params) || isListings(params))
357 string const parent_filename = parent.absFileName();
358 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
359 onlyPath(parent_filename));
361 if (!isLyXFilename(included_file.absFilename()))
364 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
366 // the readonly flag can/will be wrong, not anymore I think.
367 if (!included_file.exists())
370 child = theBufferList().newBuffer(included_file.absFilename());
372 // Buffer creation is not possible.
375 if (!child->loadLyXFile(included_file)) {
376 //close the buffer we just opened
377 theBufferList().release(child);
381 if (!child->errorList("Parse").empty()) {
382 // FIXME: Do something.
385 child->setParent(&parent);
390 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
392 string incfile = to_utf8(params()["filename"]);
394 // Do nothing if no file name has been specified
398 FileName const included_file =
399 includedFilename(buffer(), params()).availableFile();
401 // Check we're not trying to include ourselves.
402 // FIXME RECURSIVE INCLUDE
403 // This isn't sufficient, as the inclusion could be downstream.
404 // But it'll have to do for now.
405 if (isInputOrInclude(params()) &&
406 buffer().absFileName() == included_file.absFilename())
408 Alert::error(_("Recursive input"),
409 bformat(_("Attempted to include file %1$s in itself! "
410 "Ignoring inclusion."), from_utf8(incfile)));
414 Buffer const * const masterBuffer = buffer().masterBuffer();
416 // if incfile is relative, make it relative to the master
418 if (!FileName(incfile).isAbsolute()) {
420 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
421 from_utf8(masterBuffer->filePath())));
424 // write it to a file (so far the complete file)
425 string const exportfile = changeExtension(incfile, ".tex");
426 string const mangled =
427 DocFileName(changeExtension(included_file.absFilename(),".tex")).
429 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
433 else if (!isValidLaTeXFilename(incfile)) {
434 frontend::Alert::warning(_("Invalid filename"),
435 _("The following filename is likely to cause trouble "
436 "when running the exported file through LaTeX: ") +
439 LYXERR(Debug::LATEX, "incfile:" << incfile);
440 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
441 LYXERR(Debug::LATEX, "writefile:" << writefile);
443 if (runparams.inComment || runparams.dryrun) {
444 //Don't try to load or copy the file if we're
445 //in a comment or doing a dryrun
446 } else if (isInputOrInclude(params()) &&
447 isLyXFilename(included_file.absFilename())) {
448 //if it's a LyX file and we're inputting or including,
449 //try to load it so we can write the associated latex
450 if (!loadIfNeeded(buffer(), params()))
453 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
455 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
457 docstring text = bformat(_("Included file `%1$s'\n"
458 "has textclass `%2$s'\n"
459 "while parent file has textclass `%3$s'."),
460 included_file.displayName(),
461 from_utf8(tmp->params().documentClass().name()),
462 from_utf8(masterBuffer->params().documentClass().name()));
463 Alert::warning(_("Different textclasses"), text);
466 // Make sure modules used in child are all included in master
467 //FIXME It might be worth loading the children's modules into the master
468 //over in BufferParams rather than doing this check.
469 vector<string> const masterModules = masterBuffer->params().getModules();
470 vector<string> const childModules = tmp->params().getModules();
471 vector<string>::const_iterator it = childModules.begin();
472 vector<string>::const_iterator end = childModules.end();
473 for (; it != end; ++it) {
474 string const module = *it;
475 vector<string>::const_iterator found =
476 find(masterModules.begin(), masterModules.end(), module);
477 if (found != masterModules.end()) {
478 docstring text = bformat(_("Included file `%1$s'\n"
479 "uses module `%2$s'\n"
480 "which is not used in parent file."),
481 included_file.displayName(), from_utf8(module));
482 Alert::warning(_("Module not found"), text);
486 tmp->markDepClean(masterBuffer->temppath());
488 // FIXME: handle non existing files
489 // FIXME: Second argument is irrelevant!
490 // since only_body is true, makeLaTeXFile will not look at second
491 // argument. Should we set it to string(), or should makeLaTeXFile
492 // make use of it somehow? (JMarc 20031002)
493 // The included file might be written in a different encoding
494 Encoding const * const oldEnc = runparams.encoding;
495 runparams.encoding = &tmp->params().encoding();
496 tmp->makeLaTeXFile(writefile,
497 masterFileName(buffer()).onlyPath().absFilename(),
499 runparams.encoding = oldEnc;
501 // In this case, it's not a LyX file, so we copy the file
502 // to the temp dir, so that .aux files etc. are not created
503 // in the original dir. Files included by this file will be
504 // found via input@path, see ../Buffer.cpp.
505 unsigned long const checksum_in = included_file.checksum();
506 unsigned long const checksum_out = writefile.checksum();
508 if (checksum_in != checksum_out) {
509 if (!included_file.copyTo(writefile)) {
512 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
513 "into the temporary directory."),
514 from_utf8(included_file.absFilename()))));
520 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
521 "latex" : "pdflatex";
522 if (isVerbatim(params())) {
523 incfile = latex_path(incfile);
525 os << '\\' << from_ascii(params().getCmdName()) << '{'
526 << from_utf8(incfile) << '}';
527 } else if (type(params()) == INPUT) {
528 runparams.exportdata->addExternalFile(tex_format, writefile,
531 // \input wants file with extension (default is .tex)
532 if (!isLyXFilename(included_file.absFilename())) {
533 incfile = latex_path(incfile);
535 os << '\\' << from_ascii(params().getCmdName())
536 << '{' << from_utf8(incfile) << '}';
538 incfile = changeExtension(incfile, ".tex");
539 incfile = latex_path(incfile);
541 os << '\\' << from_ascii(params().getCmdName())
542 << '{' << from_utf8(incfile) << '}';
544 } else if (type(params()) == LISTINGS) {
545 os << '\\' << from_ascii(params().getCmdName());
546 string const opt = to_utf8(params()["lstparams"]);
547 // opt is set in QInclude dialog and should have passed validation.
548 InsetListingsParams params(opt);
549 if (!params.params().empty())
550 os << "[" << from_utf8(params.params()) << "]";
551 os << '{' << from_utf8(incfile) << '}';
553 runparams.exportdata->addExternalFile(tex_format, writefile,
556 // \include don't want extension and demands that the
557 // file really have .tex
558 incfile = changeExtension(incfile, string());
559 incfile = latex_path(incfile);
561 os << '\\' << from_ascii(params().getCmdName()) << '{'
562 << from_utf8(incfile) << '}';
569 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
571 if (isVerbatim(params()) || isListings(params())) {
572 os << '[' << screenLabel() << '\n';
573 // FIXME: We don't know the encoding of the file, default to UTF-8.
574 os << includedFilename(buffer(), params()).fileContents("UTF-8");
576 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
578 docstring const str = '[' + screenLabel() + ']';
585 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
587 string incfile = to_utf8(params()["filename"]);
589 // Do nothing if no file name has been specified
593 string const included_file = includedFilename(buffer(), params()).absFilename();
595 // Check we're not trying to include ourselves.
596 // FIXME RECURSIVE INCLUDE
597 // This isn't sufficient, as the inclusion could be downstream.
598 // But it'll have to do for now.
599 if (buffer().absFileName() == included_file) {
600 Alert::error(_("Recursive input"),
601 bformat(_("Attempted to include file %1$s in itself! "
602 "Ignoring inclusion."), from_utf8(incfile)));
606 // write it to a file (so far the complete file)
607 string const exportfile = changeExtension(incfile, ".sgml");
608 DocFileName writefile(changeExtension(included_file, ".sgml"));
610 if (loadIfNeeded(buffer(), params())) {
611 Buffer * tmp = theBufferList().getBuffer(included_file);
613 string const mangled = writefile.mangledFilename();
614 writefile = makeAbsPath(mangled,
615 buffer().masterBuffer()->temppath());
619 LYXERR(Debug::LATEX, "incfile:" << incfile);
620 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
621 LYXERR(Debug::LATEX, "writefile:" << writefile);
623 tmp->makeDocBookFile(writefile, runparams, true);
626 runparams.exportdata->addExternalFile("docbook", writefile,
628 runparams.exportdata->addExternalFile("docbook-xml", writefile,
631 if (isVerbatim(params()) || isListings(params())) {
632 os << "<inlinegraphic fileref=\""
633 << '&' << include_label << ';'
634 << "\" format=\"linespecific\">";
636 os << '&' << include_label << ';';
642 void InsetInclude::validate(LaTeXFeatures & features) const
644 string incfile = to_utf8(params()["filename"]);
647 BOOST_ASSERT(&buffer() == &features.buffer());
649 string const included_file =
650 includedFilename(buffer(), params()).availableFile().absFilename();
652 if (isLyXFilename(included_file))
653 writefile = changeExtension(included_file, ".sgml");
655 writefile = included_file;
657 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
658 incfile = DocFileName(writefile).mangledFilename();
659 writefile = makeAbsPath(incfile,
660 buffer().masterBuffer()->temppath()).absFilename();
663 features.includeFile(include_label, writefile);
665 if (isVerbatim(params()))
666 features.require("verbatim");
667 else if (isListings(params()))
668 features.require("listings");
670 // Here we must do the fun stuff...
671 // Load the file in the include if it needs
673 if (loadIfNeeded(buffer(), params())) {
675 Buffer * const tmp = theBufferList().getBuffer(included_file);
676 // make sure the buffer isn't us
677 // FIXME RECURSIVE INCLUDES
678 // This is not sufficient, as recursive includes could be
679 // more than a file away. But it will do for now.
680 if (tmp && tmp != &buffer()) {
681 // We must temporarily change features.buffer,
682 // otherwise it would always be the master buffer,
683 // and nested includes would not work.
684 features.setBuffer(*tmp);
685 tmp->validate(features);
686 features.setBuffer(buffer());
692 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
693 InsetIterator const & /*di*/) const
695 if (loadIfNeeded(buffer(), params())) {
696 string const included_file = includedFilename(buffer(), params()).absFilename();
697 Buffer * tmp = theBufferList().getBuffer(included_file);
698 //FIXME This is kind of a dirty hack and should be made reasonable.
700 keys.fillWithBibKeys(tmp);
701 tmp->setParent(&buffer());
706 void InsetInclude::updateBibfilesCache()
708 Buffer * const tmp = getChildBuffer(buffer(), params());
711 tmp->updateBibfilesCache();
712 tmp->setParent(&buffer());
717 EmbeddedFileList const &
718 InsetInclude::getBibfilesCache(Buffer const & buffer) const
720 Buffer * const tmp = getChildBuffer(buffer, params());
723 EmbeddedFileList const & cache = tmp->getBibfilesCache();
724 tmp->setParent(&buffer);
727 static EmbeddedFileList const empty;
732 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
734 BOOST_ASSERT(mi.base.bv);
736 bool use_preview = false;
737 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
738 graphics::PreviewImage const * pimage =
739 preview_->getPreviewImage(mi.base.bv->buffer());
740 use_preview = pimage && pimage->image();
744 preview_->metrics(mi, dim);
748 button_.update(screenLabel(), true);
750 button_.metrics(mi, dim);
753 Box b(0, dim.wid, -dim.asc, dim.des);
758 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
760 BOOST_ASSERT(pi.base.bv);
762 bool use_preview = false;
763 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
764 graphics::PreviewImage const * pimage =
765 preview_->getPreviewImage(pi.base.bv->buffer());
766 use_preview = pimage && pimage->image();
770 preview_->draw(pi, x, y);
772 button_.draw(pi, x, y);
776 Inset::DisplayType InsetInclude::display() const
778 return type(params()) == INPUT ? Inline : AlignCenter;
787 void InsetInclude::fileChanged() const
789 Buffer const * const buffer = updateFrontend();
793 preview_->removePreview(*buffer);
794 add_preview(*preview_.get(), *this, *buffer);
795 preview_->startLoading(*buffer);
801 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
803 FileName const included_file = includedFilename(buffer, params);
805 return type(params) == INPUT && params.preview() &&
806 included_file.isReadableFile();
810 docstring latexString(InsetInclude const & inset)
813 // We don't need to set runparams.encoding since this will be done
814 // by latex() anyway.
815 OutputParams runparams(0);
816 runparams.flavor = OutputParams::LATEX;
817 inset.latex(os, runparams);
823 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
824 Buffer const & buffer)
826 InsetCommandParams const & params = inset.params();
827 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
828 preview_wanted(params, buffer)) {
829 renderer.setAbsFile(includedFilename(buffer, params));
830 docstring const snippet = latexString(inset);
831 renderer.addPreview(snippet, buffer);
838 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
840 Buffer const & buffer = ploader.buffer();
841 if (!preview_wanted(params(), buffer))
843 preview_->setAbsFile(includedFilename(buffer, params()));
844 docstring const snippet = latexString(*this);
845 preview_->addPreview(snippet, ploader);
849 void InsetInclude::addToToc(ParConstIterator const & cpit) const
851 bool const embedded_status = !params()["embed"].empty();
852 TocBackend & backend = buffer().tocBackend();
854 if (isListings(params())) {
856 label_->addToToc(cpit);
858 InsetListingsParams p(to_utf8(params()["lstparams"]));
859 string caption = p.getParamValue("caption");
862 Toc & toc = backend.toc("listing");
863 docstring str = convert<docstring>(toc.size() + 1)
864 + ". " + from_utf8(caption);
865 if (embedded_status) {
866 backend.toc("embedded").push_back(TocItem(cpit, 0, str));
867 str += _(" (embedded)");
869 ParConstIterator pit = cpit;
870 pit.push_back(*this);
871 toc.push_back(TocItem(pit, 0, str));
874 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
877 // Add it to the embedded list nonetheless.
878 backend.toc("embedded").push_back(TocItem(cpit, 0,
879 params()["filename"]));
883 Toc & toc = backend.toc("child");
884 docstring str = childbuffer->fileName().displayName();
885 if (embedded_status) {
886 backend.toc("embedded").push_back(TocItem(cpit, 0, str));
887 str += _(" (embedded)");
889 toc.push_back(TocItem(cpit, 0, str));
891 TocList & toclist = backend.tocs();
892 TocList const & childtoclist = childbuffer->tocBackend().tocs();
893 TocList::const_iterator it = childtoclist.begin();
894 TocList::const_iterator const end = childtoclist.end();
895 for(; it != end; ++it)
896 toclist[it->first].insert(toclist[it->first].end(),
897 it->second.begin(), it->second.end());
901 void InsetInclude::updateLabels(ParIterator const & it)
903 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
905 lyx::updateLabels(*childbuffer, true);
908 if (!isListings(params()))
912 label_->updateLabels(it);
914 InsetListingsParams const par(to_utf8(params()["lstparams"]));
915 if (par.getParamValue("caption").empty()) {
916 listings_label_.clear();
919 Counters & counters = buffer().params().documentClass().counters();
920 docstring const cnt = from_ascii("listing");
921 listings_label_ = buffer().B_("Program Listing");
922 if (counters.hasCounter(cnt)) {
924 listings_label_ += " " + convert<docstring>(counters.value(cnt));
929 void InsetInclude::registerEmbeddedFiles(EmbeddedFileList & files) const
931 files.registerFile(includedFilename(buffer(), params()), this, buffer());
935 void InsetInclude::updateEmbeddedFile(EmbeddedFile const & file)
937 InsetCommandParams p = params();
938 p["filename"] = from_utf8(file.outputFilename());
939 p["embed"] = file.embedded() ? from_utf8(file.inzipName()) : docstring();