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"
22 #include "support/debug.h"
23 #include "DispatchResult.h"
25 #include "FuncRequest.h"
26 #include "FuncStatus.h"
27 #include "support/gettext.h"
28 #include "LaTeXFeatures.h"
32 #include "MetricsInfo.h"
33 #include "OutputParams.h"
34 #include "TocBackend.h"
35 #include "TextClass.h"
37 #include "frontends/alert.h"
38 #include "frontends/Painter.h"
40 #include "graphics/PreviewImage.h"
41 #include "graphics/PreviewLoader.h"
43 #include "insets/RenderPreview.h"
44 #include "insets/InsetListingsParams.h"
46 #include "support/docstream.h"
47 #include "support/ExceptionMessage.h"
48 #include "support/FileNameList.h"
49 #include "support/filetools.h"
50 #include "support/lstrings.h" // contains
51 #include "support/lyxalgo.h"
52 #include "support/convert.h"
54 #include <boost/bind.hpp>
57 using namespace lyx::support;
61 namespace Alert = frontend::Alert;
66 docstring const uniqueID()
68 static unsigned int seed = 1000;
69 return "file" + convert<docstring>(++seed);
73 /// the type of inclusion
75 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
79 Types type(string const & s)
83 if (s == "verbatiminput")
85 if (s == "verbatiminput*")
87 if (s == "lstinputlisting")
95 Types type(InsetCommandParams const & params)
97 return type(params.getCmdName());
101 bool isListings(InsetCommandParams const & params)
103 return type(params) == LISTINGS;
107 bool isVerbatim(InsetCommandParams const & params)
109 Types const t = type(params);
110 return t == VERB || t == VERBAST;
114 bool isInputOrInclude(InsetCommandParams const & params)
116 Types const t = type(params);
117 return t == INPUT || t == INCLUDE;
121 FileName const masterFileName(Buffer const & buffer)
123 return buffer.masterBuffer()->fileName();
127 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
130 string const parentFilename(Buffer const & buffer)
132 return buffer.absFileName();
136 EmbeddedFile const includedFilename(Buffer const & buffer,
137 InsetCommandParams const & params)
139 // it is not a good idea to create this EmbeddedFile object
140 // each time, but there seems to be no easy way around.
141 EmbeddedFile file(to_utf8(params["filename"]),
142 onlyPath(parentFilename(buffer)));
143 file.setEmbed(params["embed"] == _("true") ? true : false);
144 file.enable(buffer.embedded(), &buffer);
151 InsetInclude::InsetInclude(InsetCommandParams const & p)
152 : InsetCommand(p, "include"), include_label(uniqueID()),
153 preview_(new RenderMonitoredPreview(this)), set_label_(false)
155 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
159 InsetInclude::InsetInclude(InsetInclude const & other)
160 : InsetCommand(other), include_label(other.include_label),
161 preview_(new RenderMonitoredPreview(this)), set_label_(false)
163 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
167 CommandInfo const * InsetInclude::findInfo(string const & /* cmdName */)
170 // This is only correct for the case of listings, but it'll do for now.
171 // In the other cases, this second parameter should just be empty.
172 static const char * const paramnames[] = {"filename", "embed", "lstparams", ""};
173 static const bool isoptional[] = {false, false, true};
174 static const CommandInfo info = {3, paramnames, isoptional};
179 bool InsetInclude::isCompatibleCommand(string const & s)
181 return type(s) != NONE;
185 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
187 switch (cmd.action) {
189 case LFUN_INSET_MODIFY: {
190 InsetCommandParams p(INCLUDE_CODE);
191 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
192 if (!p.getCmdName().empty()) {
194 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
195 InsetListingsParams par_new(to_utf8(p["lstparams"]));
196 if (par_old.getParamValue("label") !=
197 par_new.getParamValue("label")
198 && !par_new.getParamValue("label").empty())
199 cur.bv().buffer().changeRefsIfUnique(
200 from_utf8(par_old.getParamValue("label")),
201 from_utf8(par_new.getParamValue("label")),
206 includedFilename(cur.buffer(), p);
207 } catch (ExceptionMessage const & message) {
208 Alert::error(message.title_, message.details_);
209 // do not set parameter if an error happens
212 set(p, cur.buffer());
213 cur.buffer().updateBibfilesCache();
219 //pass everything else up the chain
221 InsetCommand::doDispatch(cur, cmd);
227 void InsetInclude::set(InsetCommandParams const & p, Buffer const & buffer)
232 if (preview_->monitoring())
233 preview_->stopMonitoring();
235 if (type(params()) == INPUT)
236 add_preview(*preview_, *this, buffer);
240 Inset * InsetInclude::clone() const
242 return new InsetInclude(*this);
246 docstring const InsetInclude::getScreenLabel(Buffer const & buf) const
250 switch (type(params())) {
252 temp = buf.B_("Input");
255 temp = buf.B_("Verbatim Input");
258 temp = buf.B_("Verbatim Input*");
261 temp = buf.B_("Include");
264 temp = listings_label_;
272 if (params()["filename"].empty())
275 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
277 if (params()["embed"] == _("true"))
278 temp += _(" (embedded)");
283 /// return the child buffer if the file is a LyX doc and is loaded
284 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
286 if (isVerbatim(params) || isListings(params))
289 string const included_file = includedFilename(buffer, params).absFilename();
290 if (!isLyXFilename(included_file))
293 Buffer * childBuffer = theBufferList().getBuffer(included_file);
295 //FIXME RECURSIVE INCLUDES
296 if (childBuffer == & buffer)
302 /// return true if the file is or got loaded.
303 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
305 if (isVerbatim(params) || isListings(params))
308 string const parent_filename = parent.absFileName();
309 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
310 onlyPath(parent_filename));
312 if (!isLyXFilename(included_file.absFilename()))
315 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
317 // the readonly flag can/will be wrong, not anymore I think.
318 if (!included_file.exists())
321 child = theBufferList().newBuffer(included_file.absFilename());
323 // Buffer creation is not possible.
326 if (!child->loadLyXFile(included_file)) {
327 //close the buffer we just opened
328 theBufferList().release(child);
332 child->setParent(&parent);
337 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
340 if (isVerbatim(params) || isListings(params))
343 string const parent_filename = parent->absFileName();
344 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
345 onlyPath(parent_filename));
347 if (!isLyXFilename(included_file.absFilename()))
350 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
351 // File not opened, nothing to close.
355 // Child document has a different parent, don't close it.
356 if (child->parent() != parent)
362 theBufferList().release(child);
364 updateLabels(*child);
368 int InsetInclude::latex(Buffer const & buffer, odocstream & os,
369 OutputParams const & runparams) const
371 string incfile(to_utf8(params()["filename"]));
373 // Do nothing if no file name has been specified
377 FileName const included_file = includedFilename(buffer, params()).availableFile();
379 //Check we're not trying to include ourselves.
380 //FIXME RECURSIVE INCLUDE
381 //This isn't sufficient, as the inclusion could be downstream.
382 //But it'll have to do for now.
383 if (isInputOrInclude(params()) &&
384 buffer.absFileName() == included_file.absFilename())
386 Alert::error(_("Recursive input"),
387 bformat(_("Attempted to include file %1$s in itself! "
388 "Ignoring inclusion."), from_utf8(incfile)));
392 Buffer const * const masterBuffer = buffer.masterBuffer();
394 // if incfile is relative, make it relative to the master
396 if (!FileName(incfile).isAbsolute()) {
398 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
399 from_utf8(masterBuffer->filePath())));
402 // write it to a file (so far the complete file)
403 string const exportfile = changeExtension(incfile, ".tex");
404 string const mangled =
405 DocFileName(changeExtension(included_file.absFilename(),".tex")).
407 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
411 else if (!isValidLaTeXFilename(incfile)) {
412 frontend::Alert::warning(_("Invalid filename"),
413 _("The following filename is likely to cause trouble "
414 "when running the exported file through LaTeX: ") +
417 LYXERR(Debug::LATEX, "incfile:" << incfile);
418 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
419 LYXERR(Debug::LATEX, "writefile:" << writefile);
421 if (runparams.inComment || runparams.dryrun) {
422 //Don't try to load or copy the file if we're
423 //in a comment or doing a dryrun
424 } else if (isInputOrInclude(params()) &&
425 isLyXFilename(included_file.absFilename())) {
426 //if it's a LyX file and we're inputting or including,
427 //try to load it so we can write the associated latex
428 if (!loadIfNeeded(buffer, params()))
431 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
433 if (tmp->params().getBaseClass() != masterBuffer->params().getBaseClass()) {
435 docstring text = bformat(_("Included file `%1$s'\n"
436 "has textclass `%2$s'\n"
437 "while parent file has textclass `%3$s'."),
438 included_file.displayName(),
439 from_utf8(tmp->params().getTextClass().name()),
440 from_utf8(masterBuffer->params().getTextClass().name()));
441 Alert::warning(_("Different textclasses"), text);
445 // Make sure modules used in child are all included in master
446 //FIXME It might be worth loading the children's modules into the master
447 //over in BufferParams rather than doing this check.
448 vector<string> const masterModules = masterBuffer->params().getModules();
449 vector<string> const childModules = tmp->params().getModules();
450 vector<string>::const_iterator it = childModules.begin();
451 vector<string>::const_iterator end = childModules.end();
452 for (; it != end; ++it) {
453 string const module = *it;
454 vector<string>::const_iterator found =
455 find(masterModules.begin(), masterModules.end(), module);
456 if (found != masterModules.end()) {
457 docstring text = bformat(_("Included file `%1$s'\n"
458 "uses module `%2$s'\n"
459 "which is not used in parent file."),
460 included_file.displayName(), from_utf8(module));
461 Alert::warning(_("Module not found"), text);
465 tmp->markDepClean(masterBuffer->temppath());
467 // FIXME: handle non existing files
468 // FIXME: Second argument is irrelevant!
469 // since only_body is true, makeLaTeXFile will not look at second
470 // argument. Should we set it to string(), or should makeLaTeXFile
471 // make use of it somehow? (JMarc 20031002)
472 // The included file might be written in a different encoding
473 Encoding const * const oldEnc = runparams.encoding;
474 runparams.encoding = &tmp->params().encoding();
475 tmp->makeLaTeXFile(writefile,
476 masterFileName(buffer).onlyPath().absFilename(),
478 runparams.encoding = oldEnc;
480 // In this case, it's not a LyX file, so we copy the file
481 // to the temp dir, so that .aux files etc. are not created
482 // in the original dir. Files included by this file will be
483 // found via input@path, see ../Buffer.cpp.
484 unsigned long const checksum_in = included_file.checksum();
485 unsigned long const checksum_out = writefile.checksum();
487 if (checksum_in != checksum_out) {
488 if (!included_file.copyTo(writefile)) {
491 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
492 "into the temporary directory."),
493 from_utf8(included_file.absFilename()))));
499 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
500 "latex" : "pdflatex";
501 if (isVerbatim(params())) {
502 incfile = latex_path(incfile);
504 os << '\\' << from_ascii(params().getCmdName()) << '{'
505 << from_utf8(incfile) << '}';
506 } else if (type(params()) == INPUT) {
507 runparams.exportdata->addExternalFile(tex_format, writefile,
510 // \input wants file with extension (default is .tex)
511 if (!isLyXFilename(included_file.absFilename())) {
512 incfile = latex_path(incfile);
514 os << '\\' << from_ascii(params().getCmdName())
515 << '{' << from_utf8(incfile) << '}';
517 incfile = changeExtension(incfile, ".tex");
518 incfile = latex_path(incfile);
520 os << '\\' << from_ascii(params().getCmdName())
521 << '{' << from_utf8(incfile) << '}';
523 } else if (type(params()) == LISTINGS) {
524 os << '\\' << from_ascii(params().getCmdName());
525 string const opt = to_utf8(params()["lstparams"]);
526 // opt is set in QInclude dialog and should have passed validation.
527 InsetListingsParams params(opt);
528 if (!params.params().empty())
529 os << "[" << from_utf8(params.params()) << "]";
530 os << '{' << from_utf8(incfile) << '}';
532 runparams.exportdata->addExternalFile(tex_format, writefile,
535 // \include don't want extension and demands that the
536 // file really have .tex
537 incfile = changeExtension(incfile, string());
538 incfile = latex_path(incfile);
540 os << '\\' << from_ascii(params().getCmdName()) << '{'
541 << from_utf8(incfile) << '}';
548 int InsetInclude::plaintext(Buffer const & buffer, odocstream & os,
549 OutputParams const &) const
551 if (isVerbatim(params()) || isListings(params())) {
552 os << '[' << getScreenLabel(buffer) << '\n';
553 // FIXME: We don't know the encoding of the file, default to UTF-8.
554 os << includedFilename(buffer, params()).fileContents("UTF-8");
556 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
558 docstring const str = '[' + getScreenLabel(buffer) + ']';
565 int InsetInclude::docbook(Buffer const & buffer, odocstream & os,
566 OutputParams const & runparams) const
568 string incfile = to_utf8(params()["filename"]);
570 // Do nothing if no file name has been specified
574 string const included_file = includedFilename(buffer, params()).absFilename();
576 //Check we're not trying to include ourselves.
577 //FIXME RECURSIVE INCLUDE
578 //This isn't sufficient, as the inclusion could be downstream.
579 //But it'll have to do for now.
580 if (buffer.absFileName() == included_file) {
581 Alert::error(_("Recursive input"),
582 bformat(_("Attempted to include file %1$s in itself! "
583 "Ignoring inclusion."), from_utf8(incfile)));
587 // write it to a file (so far the complete file)
588 string const exportfile = changeExtension(incfile, ".sgml");
589 DocFileName writefile(changeExtension(included_file, ".sgml"));
591 if (loadIfNeeded(buffer, params())) {
592 Buffer * tmp = theBufferList().getBuffer(included_file);
594 string const mangled = writefile.mangledFilename();
595 writefile = makeAbsPath(mangled,
596 buffer.masterBuffer()->temppath());
600 LYXERR(Debug::LATEX, "incfile:" << incfile);
601 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
602 LYXERR(Debug::LATEX, "writefile:" << writefile);
604 tmp->makeDocBookFile(writefile, runparams, true);
607 runparams.exportdata->addExternalFile("docbook", writefile,
609 runparams.exportdata->addExternalFile("docbook-xml", writefile,
612 if (isVerbatim(params()) || isListings(params())) {
613 os << "<inlinegraphic fileref=\""
614 << '&' << include_label << ';'
615 << "\" format=\"linespecific\">";
617 os << '&' << include_label << ';';
623 void InsetInclude::validate(LaTeXFeatures & features) const
625 string incfile = to_utf8(params()["filename"]);
628 Buffer const & buffer = features.buffer();
630 string const included_file = includedFilename(buffer, params()).availableFile().absFilename();
632 if (isLyXFilename(included_file))
633 writefile = changeExtension(included_file, ".sgml");
635 writefile = included_file;
637 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
638 incfile = DocFileName(writefile).mangledFilename();
639 writefile = makeAbsPath(incfile,
640 buffer.masterBuffer()->temppath()).absFilename();
643 features.includeFile(include_label, writefile);
645 if (isVerbatim(params()))
646 features.require("verbatim");
647 else if (isListings(params()))
648 features.require("listings");
650 // Here we must do the fun stuff...
651 // Load the file in the include if it needs
653 if (loadIfNeeded(buffer, params())) {
655 Buffer * const tmp = theBufferList().getBuffer(included_file);
656 // make sure the buffer isn't us
657 // FIXME RECURSIVE INCLUDES
658 // This is not sufficient, as recursive includes could be
659 // more than a file away. But it will do for now.
660 if (tmp && tmp != & buffer) {
661 // We must temporarily change features.buffer,
662 // otherwise it would always be the master buffer,
663 // and nested includes would not work.
664 features.setBuffer(*tmp);
665 tmp->validate(features);
666 features.setBuffer(buffer);
672 void InsetInclude::getLabelList(Buffer const & buffer,
673 vector<docstring> & list) const
675 if (isListings(params())) {
676 InsetListingsParams p(to_utf8(params()["lstparams"]));
677 string label = p.getParamValue("label");
679 list.push_back(from_utf8(label));
681 else if (loadIfNeeded(buffer, params())) {
682 string const included_file = includedFilename(buffer, params()).absFilename();
683 Buffer * tmp = theBufferList().getBuffer(included_file);
685 tmp->getLabelList(list);
686 tmp->setParent(const_cast<Buffer *>(&buffer));
691 void InsetInclude::fillWithBibKeys(Buffer const & buffer,
692 BiblioInfo & keys, InsetIterator const & /*di*/) const
694 if (loadIfNeeded(buffer, params())) {
695 string const included_file = includedFilename(buffer, params()).absFilename();
696 Buffer * tmp = theBufferList().getBuffer(included_file);
697 //FIXME This is kind of a dirty hack and should be made reasonable.
699 keys.fillWithBibKeys(tmp);
700 tmp->setParent(&buffer);
705 void InsetInclude::updateBibfilesCache(Buffer const & buffer)
707 Buffer * const tmp = getChildBuffer(buffer, params());
710 tmp->updateBibfilesCache();
711 tmp->setParent(&buffer);
716 EmbeddedFileList const &
717 InsetInclude::getBibfilesCache(Buffer const & buffer) const
719 Buffer * const tmp = getChildBuffer(buffer, params());
722 EmbeddedFileList const & cache = tmp->getBibfilesCache();
723 tmp->setParent(&buffer);
726 static EmbeddedFileList const empty;
731 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
733 BOOST_ASSERT(mi.base.bv);
735 bool use_preview = false;
736 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
737 graphics::PreviewImage const * pimage =
738 preview_->getPreviewImage(mi.base.bv->buffer());
739 use_preview = pimage && pimage->image();
743 preview_->metrics(mi, dim);
747 button_.update(getScreenLabel(mi.base.bv->buffer()),
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 const latex_string(InsetInclude const & inset, Buffer const & buffer)
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(buffer, 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 = latex_string(inset, buffer);
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)) {
842 preview_->setAbsFile(includedFilename(buffer, params()));
843 docstring const snippet = latex_string(*this, buffer);
844 preview_->addPreview(snippet, ploader);
849 void InsetInclude::addToToc(TocList & toclist, Buffer const & buffer,
850 ParConstIterator const & pit) const
852 if (isListings(params())) {
853 InsetListingsParams p(to_utf8(params()["lstparams"]));
854 string caption = p.getParamValue("caption");
857 Toc & toc = toclist["listing"];
858 docstring const str = convert<docstring>(toc.size() + 1)
859 + ". " + from_utf8(caption);
860 // This inset does not have a valid ParConstIterator
861 // so it has to use the iterator of its parent paragraph
862 toc.push_back(TocItem(pit, 0, str));
865 Buffer const * const childbuffer = getChildBuffer(buffer, params());
869 TocList const & childtoclist = childbuffer->tocBackend().tocs();
870 TocList::const_iterator it = childtoclist.begin();
871 TocList::const_iterator const end = childtoclist.end();
872 for(; it != end; ++it)
873 toclist[it->first].insert(toclist[it->first].end(),
874 it->second.begin(), it->second.end());
878 void InsetInclude::updateLabels(Buffer const & buffer, ParIterator const &)
880 Buffer const * const childbuffer = getChildBuffer(buffer, params());
882 lyx::updateLabels(*childbuffer, true);
883 else if (isListings(params())) {
884 InsetListingsParams const par(to_utf8(params()["lstparams"]));
885 if (par.getParamValue("caption").empty())
886 listings_label_.clear();
888 Counters & counters = buffer.params().getTextClass().counters();
889 docstring const cnt = from_ascii("listing");
890 if (counters.hasCounter(cnt)) {
892 listings_label_ = buffer.B_("Program Listing ")
893 + convert<docstring>(counters.value(cnt));
895 listings_label_ = buffer.B_("Program Listing");
901 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
902 EmbeddedFileList & files) const
904 files.registerFile(includedFilename(buffer, params()), this, buffer);
908 void InsetInclude::updateEmbeddedFile(Buffer const & buf,
909 EmbeddedFile const & file)
911 InsetCommandParams p = params();
912 p["filename"] = from_utf8(file.outputFilename());
913 p["embedded"] = file.embedded() ? _("true") : _("false");