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 "BaseClassList.h"
19 #include "buffer_funcs.h"
20 #include "BufferList.h"
21 #include "BufferParams.h"
22 #include "BufferView.h"
24 #include "DispatchResult.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
32 #include "MetricsInfo.h"
33 #include "OutputParams.h"
34 #include "TextClass.h"
35 #include "TocBackend.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/debug.h"
47 #include "support/docstream.h"
48 #include "support/ExceptionMessage.h"
49 #include "support/FileNameList.h"
50 #include "support/filetools.h"
51 #include "support/gettext.h"
52 #include "support/lstrings.h" // contains
53 #include "support/lyxalgo.h"
54 #include "support/convert.h"
56 #include <boost/bind.hpp>
59 using namespace lyx::support;
63 namespace Alert = frontend::Alert;
68 docstring const uniqueID()
70 static unsigned int seed = 1000;
71 return "file" + convert<docstring>(++seed);
75 /// the type of inclusion
77 INCLUDE, VERB, INPUT, VERBAST, LISTINGS, NONE
81 Types type(string const & s)
85 if (s == "verbatiminput")
87 if (s == "verbatiminput*")
89 if (s == "lstinputlisting")
97 Types type(InsetCommandParams const & params)
99 return type(params.getCmdName());
103 bool isListings(InsetCommandParams const & params)
105 return type(params) == LISTINGS;
109 bool isVerbatim(InsetCommandParams const & params)
111 Types const t = type(params);
112 return t == VERB || t == VERBAST;
116 bool isInputOrInclude(InsetCommandParams const & params)
118 Types const t = type(params);
119 return t == INPUT || t == INCLUDE;
123 FileName const masterFileName(Buffer const & buffer)
125 return buffer.masterBuffer()->fileName();
129 void add_preview(RenderMonitoredPreview &, InsetInclude const &, Buffer const &);
132 string const parentFilename(Buffer const & buffer)
134 return buffer.absFileName();
138 EmbeddedFile const includedFilename(Buffer const & buffer,
139 InsetCommandParams const & params)
141 // it is not a good idea to create this EmbeddedFile object
142 // each time, but there seems to be no easy way around.
143 EmbeddedFile file(to_utf8(params["filename"]),
144 onlyPath(parentFilename(buffer)));
145 file.setEmbed(!params["embed"].empty());
146 file.enable(buffer.embedded(), &buffer);
153 InsetInclude::InsetInclude(InsetCommandParams const & p)
154 : InsetCommand(p, "include"), include_label(uniqueID()),
155 preview_(new RenderMonitoredPreview(this)), set_label_(false)
157 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
161 InsetInclude::InsetInclude(InsetInclude const & other)
162 : InsetCommand(other), include_label(other.include_label),
163 preview_(new RenderMonitoredPreview(this)), set_label_(false)
165 preview_->fileChanged(boost::bind(&InsetInclude::fileChanged, this));
169 ParamInfo const & InsetInclude::findInfo(string const & /* cmdName */)
172 // This is only correct for the case of listings, but it'll do for now.
173 // In the other cases, this second parameter should just be empty.
174 static ParamInfo param_info_;
175 if (param_info_.empty()) {
176 param_info_.add("filename", ParamInfo::LATEX_REQUIRED);
177 param_info_.add("lstparams", ParamInfo::LATEX_OPTIONAL);
178 param_info_.add("embed", ParamInfo::LYX_INTERNAL);
184 bool InsetInclude::isCompatibleCommand(string const & s)
186 return type(s) != NONE;
190 void InsetInclude::doDispatch(Cursor & cur, FuncRequest & cmd)
192 BOOST_ASSERT(&cur.buffer() == &buffer());
193 switch (cmd.action) {
195 case LFUN_INSET_MODIFY: {
196 InsetCommandParams p(INCLUDE_CODE);
197 InsetCommandMailer::string2params("include", to_utf8(cmd.argument()), p);
198 if (!p.getCmdName().empty()) {
200 InsetListingsParams par_old(to_utf8(params()["lstparams"]));
201 InsetListingsParams par_new(to_utf8(p["lstparams"]));
202 if (par_old.getParamValue("label") !=
203 par_new.getParamValue("label")
204 && !par_new.getParamValue("label").empty())
205 cur.bv().buffer().changeRefsIfUnique(
206 from_utf8(par_old.getParamValue("label")),
207 from_utf8(par_new.getParamValue("label")),
211 // the embed parameter passed back from the dialog
212 // is "true" or "false", we need to change it.
213 if (p["embed"] == _("false"))
216 p["embed"] = from_utf8(EmbeddedFile(to_utf8(p["filename"]),
217 onlyPath(parentFilename(cur.buffer()))).inzipName());
219 includedFilename(cur.buffer(), p);
220 } catch (ExceptionMessage const & message) {
221 Alert::error(message.title_, message.details_);
222 // do not set parameter if an error happens
226 buffer().updateBibfilesCache();
232 //pass everything else up the chain
234 InsetCommand::doDispatch(cur, cmd);
240 void InsetInclude::setParams(InsetCommandParams const & p)
242 InsetCommand::setParams(p);
245 if (preview_->monitoring())
246 preview_->stopMonitoring();
248 if (type(params()) == INPUT)
249 add_preview(*preview_, *this, buffer());
253 Inset * InsetInclude::clone() const
255 return new InsetInclude(*this);
259 docstring InsetInclude::screenLabel() const
263 switch (type(params())) {
265 temp = buffer().B_("Input");
268 temp = buffer().B_("Verbatim Input");
271 temp = buffer().B_("Verbatim Input*");
274 temp = buffer().B_("Include");
277 temp = listings_label_;
285 if (params()["filename"].empty())
288 temp += from_utf8(onlyFilename(to_utf8(params()["filename"])));
290 if (!params()["embed"].empty())
291 temp += _(" (embedded)");
296 /// return the child buffer if the file is a LyX doc and is loaded
297 Buffer * getChildBuffer(Buffer const & buffer, InsetCommandParams const & params)
299 if (isVerbatim(params) || isListings(params))
302 string const included_file = includedFilename(buffer, params).absFilename();
303 if (!isLyXFilename(included_file))
306 Buffer * childBuffer = theBufferList().getBuffer(included_file);
308 // FIXME: recursive includes
309 return (childBuffer == &buffer) ? 0 : childBuffer;
313 /// return true if the file is or got loaded.
314 Buffer * loadIfNeeded(Buffer const & parent, InsetCommandParams const & params)
316 if (isVerbatim(params) || isListings(params))
319 string const parent_filename = parent.absFileName();
320 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
321 onlyPath(parent_filename));
323 if (!isLyXFilename(included_file.absFilename()))
326 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
328 // the readonly flag can/will be wrong, not anymore I think.
329 if (!included_file.exists())
332 child = theBufferList().newBuffer(included_file.absFilename());
334 // Buffer creation is not possible.
337 if (!child->loadLyXFile(included_file)) {
338 //close the buffer we just opened
339 theBufferList().release(child);
343 child->setParent(&parent);
348 void resetParentBuffer(Buffer const * parent, InsetCommandParams const & params,
351 if (isVerbatim(params) || isListings(params))
354 string const parent_filename = parent->absFileName();
355 FileName const included_file = makeAbsPath(to_utf8(params["filename"]),
356 onlyPath(parent_filename));
358 if (!isLyXFilename(included_file.absFilename()))
361 Buffer * child = theBufferList().getBuffer(included_file.absFilename());
362 // File not opened, nothing to close.
366 // Child document has a different parent, don't close it.
367 if (child->parent() != parent)
373 theBufferList().release(child);
375 updateLabels(*child);
379 int InsetInclude::latex(odocstream & os, OutputParams const & runparams) const
381 string incfile = to_utf8(params()["filename"]);
383 // Do nothing if no file name has been specified
387 FileName const included_file =
388 includedFilename(buffer(), params()).availableFile();
390 // Check we're not trying to include ourselves.
391 // FIXME RECURSIVE INCLUDE
392 // This isn't sufficient, as the inclusion could be downstream.
393 // But it'll have to do for now.
394 if (isInputOrInclude(params()) &&
395 buffer().absFileName() == included_file.absFilename())
397 Alert::error(_("Recursive input"),
398 bformat(_("Attempted to include file %1$s in itself! "
399 "Ignoring inclusion."), from_utf8(incfile)));
403 Buffer const * const masterBuffer = buffer().masterBuffer();
405 // if incfile is relative, make it relative to the master
407 if (!FileName(incfile).isAbsolute()) {
409 incfile = to_utf8(makeRelPath(from_utf8(included_file.absFilename()),
410 from_utf8(masterBuffer->filePath())));
413 // write it to a file (so far the complete file)
414 string const exportfile = changeExtension(incfile, ".tex");
415 string const mangled =
416 DocFileName(changeExtension(included_file.absFilename(),".tex")).
418 FileName const writefile(makeAbsPath(mangled, masterBuffer->temppath()));
422 else if (!isValidLaTeXFilename(incfile)) {
423 frontend::Alert::warning(_("Invalid filename"),
424 _("The following filename is likely to cause trouble "
425 "when running the exported file through LaTeX: ") +
428 LYXERR(Debug::LATEX, "incfile:" << incfile);
429 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
430 LYXERR(Debug::LATEX, "writefile:" << writefile);
432 if (runparams.inComment || runparams.dryrun) {
433 //Don't try to load or copy the file if we're
434 //in a comment or doing a dryrun
435 } else if (isInputOrInclude(params()) &&
436 isLyXFilename(included_file.absFilename())) {
437 //if it's a LyX file and we're inputting or including,
438 //try to load it so we can write the associated latex
439 if (!loadIfNeeded(buffer(), params()))
442 Buffer * tmp = theBufferList().getBuffer(included_file.absFilename());
444 if (tmp->params().baseClass() != masterBuffer->params().baseClass()) {
446 docstring text = bformat(_("Included file `%1$s'\n"
447 "has textclass `%2$s'\n"
448 "while parent file has textclass `%3$s'."),
449 included_file.displayName(),
450 from_utf8(tmp->params().textClass().name()),
451 from_utf8(masterBuffer->params().textClass().name()));
452 Alert::warning(_("Different textclasses"), text);
456 // Make sure modules used in child are all included in master
457 //FIXME It might be worth loading the children's modules into the master
458 //over in BufferParams rather than doing this check.
459 vector<string> const masterModules = masterBuffer->params().getModules();
460 vector<string> const childModules = tmp->params().getModules();
461 vector<string>::const_iterator it = childModules.begin();
462 vector<string>::const_iterator end = childModules.end();
463 for (; it != end; ++it) {
464 string const module = *it;
465 vector<string>::const_iterator found =
466 find(masterModules.begin(), masterModules.end(), module);
467 if (found != masterModules.end()) {
468 docstring text = bformat(_("Included file `%1$s'\n"
469 "uses module `%2$s'\n"
470 "which is not used in parent file."),
471 included_file.displayName(), from_utf8(module));
472 Alert::warning(_("Module not found"), text);
476 tmp->markDepClean(masterBuffer->temppath());
478 // FIXME: handle non existing files
479 // FIXME: Second argument is irrelevant!
480 // since only_body is true, makeLaTeXFile will not look at second
481 // argument. Should we set it to string(), or should makeLaTeXFile
482 // make use of it somehow? (JMarc 20031002)
483 // The included file might be written in a different encoding
484 Encoding const * const oldEnc = runparams.encoding;
485 runparams.encoding = &tmp->params().encoding();
486 tmp->makeLaTeXFile(writefile,
487 masterFileName(buffer()).onlyPath().absFilename(),
489 runparams.encoding = oldEnc;
491 // In this case, it's not a LyX file, so we copy the file
492 // to the temp dir, so that .aux files etc. are not created
493 // in the original dir. Files included by this file will be
494 // found via input@path, see ../Buffer.cpp.
495 unsigned long const checksum_in = included_file.checksum();
496 unsigned long const checksum_out = writefile.checksum();
498 if (checksum_in != checksum_out) {
499 if (!included_file.copyTo(writefile)) {
502 to_utf8(bformat(_("Could not copy the file\n%1$s\n"
503 "into the temporary directory."),
504 from_utf8(included_file.absFilename()))));
510 string const tex_format = (runparams.flavor == OutputParams::LATEX) ?
511 "latex" : "pdflatex";
512 if (isVerbatim(params())) {
513 incfile = latex_path(incfile);
515 os << '\\' << from_ascii(params().getCmdName()) << '{'
516 << from_utf8(incfile) << '}';
517 } else if (type(params()) == INPUT) {
518 runparams.exportdata->addExternalFile(tex_format, writefile,
521 // \input wants file with extension (default is .tex)
522 if (!isLyXFilename(included_file.absFilename())) {
523 incfile = latex_path(incfile);
525 os << '\\' << from_ascii(params().getCmdName())
526 << '{' << from_utf8(incfile) << '}';
528 incfile = changeExtension(incfile, ".tex");
529 incfile = latex_path(incfile);
531 os << '\\' << from_ascii(params().getCmdName())
532 << '{' << from_utf8(incfile) << '}';
534 } else if (type(params()) == LISTINGS) {
535 os << '\\' << from_ascii(params().getCmdName());
536 string const opt = to_utf8(params()["lstparams"]);
537 // opt is set in QInclude dialog and should have passed validation.
538 InsetListingsParams params(opt);
539 if (!params.params().empty())
540 os << "[" << from_utf8(params.params()) << "]";
541 os << '{' << from_utf8(incfile) << '}';
543 runparams.exportdata->addExternalFile(tex_format, writefile,
546 // \include don't want extension and demands that the
547 // file really have .tex
548 incfile = changeExtension(incfile, string());
549 incfile = latex_path(incfile);
551 os << '\\' << from_ascii(params().getCmdName()) << '{'
552 << from_utf8(incfile) << '}';
559 int InsetInclude::plaintext(odocstream & os, OutputParams const &) const
561 if (isVerbatim(params()) || isListings(params())) {
562 os << '[' << screenLabel() << '\n';
563 // FIXME: We don't know the encoding of the file, default to UTF-8.
564 os << includedFilename(buffer(), params()).fileContents("UTF-8");
566 return PLAINTEXT_NEWLINE + 1; // one char on a separate line
568 docstring const str = '[' + screenLabel() + ']';
575 int InsetInclude::docbook(odocstream & os, OutputParams const & runparams) const
577 string incfile = to_utf8(params()["filename"]);
579 // Do nothing if no file name has been specified
583 string const included_file = includedFilename(buffer(), params()).absFilename();
585 // Check we're not trying to include ourselves.
586 // FIXME RECURSIVE INCLUDE
587 // This isn't sufficient, as the inclusion could be downstream.
588 // But it'll have to do for now.
589 if (buffer().absFileName() == included_file) {
590 Alert::error(_("Recursive input"),
591 bformat(_("Attempted to include file %1$s in itself! "
592 "Ignoring inclusion."), from_utf8(incfile)));
596 // write it to a file (so far the complete file)
597 string const exportfile = changeExtension(incfile, ".sgml");
598 DocFileName writefile(changeExtension(included_file, ".sgml"));
600 if (loadIfNeeded(buffer(), params())) {
601 Buffer * tmp = theBufferList().getBuffer(included_file);
603 string const mangled = writefile.mangledFilename();
604 writefile = makeAbsPath(mangled,
605 buffer().masterBuffer()->temppath());
609 LYXERR(Debug::LATEX, "incfile:" << incfile);
610 LYXERR(Debug::LATEX, "exportfile:" << exportfile);
611 LYXERR(Debug::LATEX, "writefile:" << writefile);
613 tmp->makeDocBookFile(writefile, runparams, true);
616 runparams.exportdata->addExternalFile("docbook", writefile,
618 runparams.exportdata->addExternalFile("docbook-xml", writefile,
621 if (isVerbatim(params()) || isListings(params())) {
622 os << "<inlinegraphic fileref=\""
623 << '&' << include_label << ';'
624 << "\" format=\"linespecific\">";
626 os << '&' << include_label << ';';
632 void InsetInclude::validate(LaTeXFeatures & features) const
634 string incfile = to_utf8(params()["filename"]);
637 BOOST_ASSERT(&buffer() == &features.buffer());
639 string const included_file =
640 includedFilename(buffer(), params()).availableFile().absFilename();
642 if (isLyXFilename(included_file))
643 writefile = changeExtension(included_file, ".sgml");
645 writefile = included_file;
647 if (!features.runparams().nice && !isVerbatim(params()) && !isListings(params())) {
648 incfile = DocFileName(writefile).mangledFilename();
649 writefile = makeAbsPath(incfile,
650 buffer().masterBuffer()->temppath()).absFilename();
653 features.includeFile(include_label, writefile);
655 if (isVerbatim(params()))
656 features.require("verbatim");
657 else if (isListings(params()))
658 features.require("listings");
660 // Here we must do the fun stuff...
661 // Load the file in the include if it needs
663 if (loadIfNeeded(buffer(), params())) {
665 Buffer * const tmp = theBufferList().getBuffer(included_file);
666 // make sure the buffer isn't us
667 // FIXME RECURSIVE INCLUDES
668 // This is not sufficient, as recursive includes could be
669 // more than a file away. But it will do for now.
670 if (tmp && tmp != &buffer()) {
671 // We must temporarily change features.buffer,
672 // otherwise it would always be the master buffer,
673 // and nested includes would not work.
674 features.setBuffer(*tmp);
675 tmp->validate(features);
676 features.setBuffer(buffer());
682 void InsetInclude::getLabelList(vector<docstring> & list) const
684 if (isListings(params())) {
685 InsetListingsParams p(to_utf8(params()["lstparams"]));
686 string label = p.getParamValue("label");
688 list.push_back(from_utf8(label));
690 else if (loadIfNeeded(buffer(), params())) {
691 string const included_file = includedFilename(buffer(), params()).absFilename();
692 Buffer * tmp = theBufferList().getBuffer(included_file);
694 tmp->getLabelList(list);
695 tmp->setParent(const_cast<Buffer *>(&buffer()));
700 void InsetInclude::fillWithBibKeys(BiblioInfo & keys,
701 InsetIterator const & /*di*/) const
703 if (loadIfNeeded(buffer(), params())) {
704 string const included_file = includedFilename(buffer(), params()).absFilename();
705 Buffer * tmp = theBufferList().getBuffer(included_file);
706 //FIXME This is kind of a dirty hack and should be made reasonable.
708 keys.fillWithBibKeys(tmp);
709 tmp->setParent(&buffer());
714 void InsetInclude::updateBibfilesCache()
716 Buffer * const tmp = getChildBuffer(buffer(), params());
719 tmp->updateBibfilesCache();
720 tmp->setParent(&buffer());
725 EmbeddedFileList const &
726 InsetInclude::getBibfilesCache(Buffer const & buffer) const
728 Buffer * const tmp = getChildBuffer(buffer, params());
731 EmbeddedFileList const & cache = tmp->getBibfilesCache();
732 tmp->setParent(&buffer);
735 static EmbeddedFileList const empty;
740 void InsetInclude::metrics(MetricsInfo & mi, Dimension & dim) const
742 BOOST_ASSERT(mi.base.bv);
744 bool use_preview = false;
745 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
746 graphics::PreviewImage const * pimage =
747 preview_->getPreviewImage(mi.base.bv->buffer());
748 use_preview = pimage && pimage->image();
752 preview_->metrics(mi, dim);
756 button_.update(screenLabel(), true);
758 button_.metrics(mi, dim);
761 Box b(0, dim.wid, -dim.asc, dim.des);
766 void InsetInclude::draw(PainterInfo & pi, int x, int y) const
768 BOOST_ASSERT(pi.base.bv);
770 bool use_preview = false;
771 if (RenderPreview::status() != LyXRC::PREVIEW_OFF) {
772 graphics::PreviewImage const * pimage =
773 preview_->getPreviewImage(pi.base.bv->buffer());
774 use_preview = pimage && pimage->image();
778 preview_->draw(pi, x, y);
780 button_.draw(pi, x, y);
784 Inset::DisplayType InsetInclude::display() const
786 return type(params()) == INPUT ? Inline : AlignCenter;
795 void InsetInclude::fileChanged() const
797 Buffer const * const buffer = updateFrontend();
801 preview_->removePreview(*buffer);
802 add_preview(*preview_.get(), *this, *buffer);
803 preview_->startLoading(*buffer);
809 bool preview_wanted(InsetCommandParams const & params, Buffer const & buffer)
811 FileName const included_file = includedFilename(buffer, params);
813 return type(params) == INPUT && params.preview() &&
814 included_file.isReadableFile();
818 docstring latexString(InsetInclude const & inset)
821 // We don't need to set runparams.encoding since this will be done
822 // by latex() anyway.
823 OutputParams runparams(0);
824 runparams.flavor = OutputParams::LATEX;
825 inset.latex(os, runparams);
831 void add_preview(RenderMonitoredPreview & renderer, InsetInclude const & inset,
832 Buffer const & buffer)
834 InsetCommandParams const & params = inset.params();
835 if (RenderPreview::status() != LyXRC::PREVIEW_OFF &&
836 preview_wanted(params, buffer)) {
837 renderer.setAbsFile(includedFilename(buffer, params));
838 docstring const snippet = latexString(inset);
839 renderer.addPreview(snippet, buffer);
846 void InsetInclude::addPreview(graphics::PreviewLoader & ploader) const
848 Buffer const & buffer = ploader.buffer();
849 if (!preview_wanted(params(), buffer))
851 preview_->setAbsFile(includedFilename(buffer, params()));
852 docstring const snippet = latexString(*this);
853 preview_->addPreview(snippet, ploader);
857 void InsetInclude::addToToc(ParConstIterator const & cpit) const
859 if (isListings(params())) {
860 InsetListingsParams p(to_utf8(params()["lstparams"]));
861 string caption = p.getParamValue("caption");
864 Toc & toc = buffer().tocBackend().toc("listing");
865 docstring const str = convert<docstring>(toc.size() + 1)
866 + ". " + from_utf8(caption);
867 ParConstIterator pit = cpit;
868 pit.push_back(*this);
869 toc.push_back(TocItem(pit, 0, str));
872 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
876 TocList & toclist = buffer().tocBackend().tocs();
877 TocList const & childtoclist = childbuffer->tocBackend().tocs();
878 TocList::const_iterator it = childtoclist.begin();
879 TocList::const_iterator const end = childtoclist.end();
880 for(; it != end; ++it)
881 toclist[it->first].insert(toclist[it->first].end(),
882 it->second.begin(), it->second.end());
886 void InsetInclude::updateLabels(ParIterator const &)
888 Buffer const * const childbuffer = getChildBuffer(buffer(), params());
890 lyx::updateLabels(*childbuffer, true);
893 if (!isListings(params()))
896 InsetListingsParams const par(to_utf8(params()["lstparams"]));
897 if (par.getParamValue("caption").empty()) {
898 listings_label_.clear();
901 Counters & counters = buffer().params().textClass().counters();
902 docstring const cnt = from_ascii("listing");
903 listings_label_ = buffer().B_("Program Listing");
904 if (counters.hasCounter(cnt)) {
906 listings_label_ += " " + convert<docstring>(counters.value(cnt));
911 void InsetInclude::registerEmbeddedFiles(Buffer const & buffer,
912 EmbeddedFileList & files) const
914 files.registerFile(includedFilename(buffer, params()), this, buffer);
918 void InsetInclude::updateEmbeddedFile(Buffer const & buf,
919 EmbeddedFile const & file)
921 InsetCommandParams p = params();
922 p["filename"] = from_utf8(file.outputFilename());
923 p["embed"] = file.embedded() ? from_utf8(file.inzipName()) : docstring();